๐Ÿ“˜ CodingMarble Learn

Pandas DataFrame: Working with a Whole Table

A DataFrame is a two-dimensional table in pandas, with labelled rows (the index) and labelled columns. Every column is a Series. You can build one from a dictionary of Series, from a list of dictionaries or by reading a CSV file. You can display it, walk through it row by row or column by column, add, select, delete and rename rows and columns, pick data with loc, iloc or a condition, and save it back to a CSV file.

๐ŸŽฌ Step-by-step story

  1. A DataFrame is a table: many Series standing side by side.
  2. Build it from a list of dictionaries or read it from a CSV file.
  3. Display it, check its shape, and walk it row by row or column by column.
  4. Add, delete and rename rows and columns.
  5. Pick data with loc, iloc or a condition, then save it with to_csv.
  6. Your turn: choose a command and watch which cells light up.

Tip: drag the 3D scene to turn it. Use two fingers to zoom.

๐Ÿค” Common doubts, cleared

What is the difference between a Series and a DataFrame?

A Series is one column with an index. A DataFrame is a table of many such columns sharing one row index.

Why do I see NaN after making a DataFrame from a list of dicts?

If a row's dictionary does not have a key that other rows have, that cell is missing, so pandas writes NaN.

When should I use iterrows()?

When you need to handle each row one at a time, for example to print a message for each student. For simple maths on a whole column, use the column directly (df.Marks + 5); it is faster.

What does axis=1 mean in drop()?

axis=1 means columns (across). axis=0 means rows (down), and it is the default.

Why did my drop() not change the table?

drop() returns a new table. Write df = df.drop(...) or add inplace=True.

Why must I use & instead of and?

A condition on a column gives many True/False values. Python's and works on one value only; & works value by value. Put brackets around each condition.

What does index=False do in to_csv()?

It stops pandas from writing the row labels (0, 1, 2 โ€ฆ) as an extra first column in the file.

What is a DataFrame?

A DataFrame is a two-dimensional labelled data structure. Two-dimensional means it has rows and columns, like a table. Each row has a label (the row index) and each column has a name (the column label). Each column is a Series, so different columns can hold different types (text, numbers).

Useful attributes: df.shape (rows, columns), df.index, df.columns, df.dtypes, df.size (number of cells), df.values, df.T (swap rows and columns), df.empty.

Create a DataFrame from a dict of Series, a list of dicts or a CSV

From a dictionary of Series

name  = pd.Series(['Asha', 'Ravi', 'Mohan'])
marks = pd.Series([92, 75, 58])
df = pd.DataFrame({'Name': name, 'Marks': marks})

Dictionary keys become column names. If the Series have different indexes, pandas joins all labels and fills gaps with NaN.

From a list of dictionaries

rows = [{'Name': 'Asha', 'Marks': 92},
        {'Name': 'Ravi', 'Marks': 75, 'City': 'Pune'}]
df = pd.DataFrame(rows)     # each dict is one row; missing City โ†’ NaN

From a CSV file

df = pd.read_csv('marks.csv')            # first line = column names
df = pd.read_csv('marks.csv', sep=',', header=0)

You can also make a DataFrame from a dictionary of lists or from a 2D list with columns= and index=.

Displaying a DataFrame

print(df)          # whole table
df.head(3)         # first 3 rows (default 5)
df.tail(2)         # last 2 rows
df.shape           # (5, 3)
df.describe()      # count, mean, min, max โ€ฆ of number columns

Iterating over rows and columns

Iteration means going through items one by one in a loop.

for i, row in df.iterrows():      # row by row
    print(i, row['Name'], row['Marks'])

for col, values in df.items():    # column by column
    print(col, values.tolist())

iterrows() gives (row label, row as a Series). items() (older name iteritems()) gives (column name, column as a Series).

Add, select, delete and rename rows and columns

Columns

df['Grade'] = ['A1', 'B1', 'C2', 'A2', 'C1']   # add (or change) a column
df['Marks']                    # select one column (a Series)
df[['Name', 'Marks']]          # select many columns (a DataFrame)
df = df.drop('Grade', axis=1)  # delete a column
del df['City']                 # another way to delete

Rows

df.loc[5] = ['Neha', 88, 'Pune']   # add a row with label 5
df.loc[2]                          # select a row
df = df.drop(2)                    # delete row labelled 2 (axis=0 is default)

Rename

df = df.rename(columns={'Marks': 'Score'})
df = df.rename(index={0: 'r0'})

drop() and rename() return a new DataFrame; assign it back, or use inplace=True.

Label indexing and boolean indexing

Label-based: loc

df.loc[2, 'City']            # one cell
df.loc[1:3, 'Name':'Marks']  # labels, end included

Position-based: iloc

df.iloc[0:2]        # rows at positions 0, 1 (end not included)
df.iloc[0, 1]       # row 0, column 1

Boolean indexing

df[df.Marks > 80]
df[(df.City == 'Delhi') & (df.Marks > 90)]   # & = and, | = or, use brackets
df.loc[df.Marks < 60, 'Name']

Importing and exporting CSV files

A CSV (comma-separated values) file is plain text: one row per line, values separated by commas. Any spreadsheet can open it.

df = pd.read_csv('marks.csv')                 # import
df.to_csv('result.csv')                       # export with index
df.to_csv('result.csv', index=False)          # export without the index column
df.to_csv('result.txt', sep='\t')            # tab-separated

Try it: your class result sheet

Type 6 rows (Name, Marks, City) in any spreadsheet and save as marks.csv. In Python: read it, print df.shape, add a column Pass = df.Marks >= 33, filter students above 80, and save them with to_csv('toppers.csv', index=False). Open toppers.csv in the spreadsheet. Before each line, predict the answer; then check. Compare with steps 4 and 5 of the 3D.

Key formulas and definitions

Worked examples

1. Create a DataFrame of three students from a dictionary of Series and print its shape.

n = pd.Series(['Asha','Ravi','Mohan']); m = pd.Series([92,75,58]); df = pd.DataFrame({'Name': n, 'Marks': m}); df.shape โ†’ (3, 2).

2. rows = [{'a': 1, 'b': 2}, {'a': 5, 'c': 7}]. What DataFrame does pd.DataFrame(rows) make?

Columns a, b, c. Row 0: 1, 2, NaN. Row 1: 5, NaN, 7. Missing keys become NaN.

3. Using the 5-row df (Asha 92 Delhi, Ravi 75 Pune, Mohan 58 Agra, Zoya 81 Delhi, Kabir 66 Jaipur), write code to show names of Delhi students.

df.loc[df.City == 'Delhi', 'Name'] โ†’ Asha, Zoya.

4. Add a column Result that says 'Pass' for Marks โ‰ฅ 60 and 'Retest' otherwise.

One simple way: df['Result'] = 'Pass'; df.loc[df.Marks < 60, 'Result'] = 'Retest'. Only Mohan (58) gets Retest.

5. What is the difference between df.loc[1:3] and df.iloc[1:3] for the default index 0โ€“4?

loc uses labels and includes the end: rows 1, 2, 3 (3 rows). iloc uses positions and leaves out the end: rows 1, 2 (2 rows).

6. Delete the City column, rename Marks to Score and save to 'final.csv' without the index.

df = df.drop('City', axis=1); df = df.rename(columns={'Marks': 'Score'}); df.to_csv('final.csv', index=False).

7. Print each student's name with 5 extra marks using iterrows().

for i, row in df.iterrows(): print(row['Name'], row['Marks'] + 5) โ†’ Asha 97, Ravi 80, Mohan 63, Zoya 86, Kabir 71.

Common mistakes

Practice quiz

1. In a DataFrame made from a list of dictionaries, each dictionary becomes a:
2. df.shape for 6 rows and 4 columns is:
3. Which loops over the table row by row?
4. To delete column 'City' you write:
5. Which saves a DataFrame to a CSV file?

Practice: answer these yourself

Type or choose your answer, then press Check. Use a hint if you are stuck; the full solution appears after you answer.

Frequently asked questions

What is a DataFrame in pandas Class 12?

A DataFrame is a two-dimensional labelled table with rows and columns, where each column is a Series.

What is the difference between loc and iloc?

loc selects by labels and includes the end of a slice; iloc selects by integer positions and leaves out the end.

How do you import and export CSV in pandas?

Use pd.read_csv('file.csv') to import and df.to_csv('file.csv', index=False) to export.

Where this is taught

CBSE (India)Class 12Data Handling using Pandas and Data Visualization

Learn first

Learn next

Related lessons

All Informatics Practices lessons