Data Handling using Pandas - I
Working with rows and columns
Change and select DataFrame data with loc, drop and rename.
Adding and changing. df['NewCol'] = values adds a new column (or updates it, if the label already exists). df.loc['label'] = values adds (or updates) a row. If you give too few values, Python raises a ValueError.
Deleting. drop() removes rows or columns: drop(label, axis=0) deletes rows; drop([labels], axis=1) deletes columns. For example, df = df.drop(['Hindi', 'Art'], axis=1) removes two columns.
Renaming. rename({old: new}, axis='index') renames row labels, and axis='columns' renames column labels. Labels you do not mention stay as they are.
Selecting.
- loc[row, column] selects by labels: df.loc['Maths', 'Asha'];
- label slices include the end: df.loc['Maths':'Science'];
- Boolean conditions: df.loc['Maths'] > 80 gives True or False for each column; a list of True/False values picks rows: df.loc[[True, False, True]] keeps rows 1 and 3.
Remember: axis 0 means rows, axis 1 means columns.
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.