DataFrames

Creating DataFrames from dictionaries, lists and CSV files; selecting, adding, deleting and renaming rows and columns.

Computer Science/Informatics Practices5 questions

The essentials

A DataFrame is a two-dimensional labelled data structure, like a table with rows and columns. Each column is a Series. Rows have an index and columns have names.

Key points

  • From a dictionary of lists: pd.DataFrame({'Name': ['A', 'B', 'C'], 'Marks': [70, 85, 60]}) gives 3 rows and 2 columns; the keys become column names.
  • From a list of dictionaries: each dictionary becomes a row; missing keys give NaN.
  • From a list of lists: pd.DataFrame([[1, 'A'], [2, 'B']], columns=['Roll', 'Name']).
  • From a CSV file: pd.read_csv('marks.csv').
  • Attributes: shape (rows, columns), index, columns, dtypes, size, T (transpose), empty.
  • Selecting a column: df['Marks'] or df.Marks. Several columns: df[['Name', 'Marks']].
  • Adding a column: df['Grade'] = ['B', 'A', 'C'].
  • Adding a row: df.loc['new_label'] = [values].
  • Deleting: df.drop('Grade', axis=1) removes a column; df.drop('r2', axis=0) removes a row. drop() returns a new DataFrame and leaves the original unchanged unless inplace=True is used or the result is assigned back.
  • Renaming: df.rename(columns={'Marks': 'Score'}) or df.rename(index={0: 'r1'}).
  • head() and tail() show the first or last rows.

Exam tips

  • After every change, update the shape (rows, columns) in your head; many questions ask for df.shape.
  • axis = 0 refers to rows (index), axis = 1 to columns.

Common mistakes

  • Forgetting axis=1 when dropping a column.
  • Assuming drop() changes the original DataFrame automatically.

Practice questions

Practice this topic