Count NaN values

Python Practice › Pandas Programs › Program 54

Count NaN values

EasyPandas Programs · 54 of 95

Write a pandas program to count NaN values.

Output
2

Approach

  1. isna().sum().sum().

Solution

Python
import numpy as npimport pandas as pddf = pd.DataFrame({"name": ["Alex", "John", "Peter", "Klaus"], "age": [30, np.nan, 29, np.nan]})print(df.isna().sum().sum())
Output
2

Learn the concept

New to this topic? Read the lesson, then come back.

More pandas programs

← All 95 Pandas Programs

Replace NaN with a value

Python Practice › Pandas Programs › Program 53

Replace NaN with a value

EasyPandas Programs · 53 of 95

Write a pandas program to replace NaN in a column with a fixed value.

Output
    name   age
0   Alex  30.0
1   John   0.0
2  Peter  29.0
3  Klaus   0.0

Approach

  1. fillna(value).

Solution

Python
import numpy as npimport pandas as pddf = pd.DataFrame({"name": ["Alex", "John", "Peter", "Klaus"], "age": [30, np.nan, 29, np.nan]})df["age"] = df["age"].fillna(0)print(df)
Output
    name   age
0   Alex  30.0
1   John   0.0
2  Peter  29.0
3  Klaus   0.0

Learn the concept

New to this topic? Read the lesson, then come back.

More pandas programs

← All 95 Pandas Programs

Population per country

Python Practice › Pandas Programs › Program 52

Population per country

EasyPandas Programs · 52 of 95

Write a pandas program to total the population per country from a data set.

Output
country
China    46700000
India    40300000
USA        980000
Name: population, dtype: int64

Approach

  1. groupby("country")["population"].sum().

Solution

Python
import pandas as pddata = pd.DataFrame({    "country": ["India", "China", "India", "USA", "China"],    "city": ["Pune", "Shanghai", "Delhi", "Austin", "Beijing"],    "population": [7_400_000, 24_900_000, 32_900_000, 980_000, 21_800_000],})print(data.groupby("country")["population"].sum().sort_values(ascending=False))
Output
country
China    46700000
India    40300000
USA        980000
Name: population, dtype: int64

Learn the concept

New to this topic? Read the lesson, then come back.

More pandas programs

← All 95 Pandas Programs

Write a tab-separated file

Python Practice › Pandas Programs › Program 51

Write a tab-separated file

EasyPandas Programs · 51 of 95

Write a pandas program to write a DataFrame to a CSV file with a tab separator.

Output
name	age	salary
Alex	30	50000
John	27	65000

Approach

  1. to_csv(sep="\t").

Solution

Python
import pandas as pddf = pd.DataFrame({"name": ["Alex", "John"], "age": [30, 27], "salary": [50000, 65000]})df.to_csv("people.tsv", sep="\t", index=False)print(open("people.tsv").read())
Output
name	age	salary
Alex	30	50000
John	27	65000

Learn the concept

New to this topic? Read the lesson, then come back.

More pandas programs

← All 95 Pandas Programs

Reorder columns

Python Practice › Pandas Programs › Program 50

Reorder columns

EasyPandas Programs · 50 of 95

Write a pandas program to change the order of columns.

Output
   salary  name  age
0   50000  Alex   30
1   65000  John   27

Approach

  1. Select columns in the new order.

Solution

Python
import pandas as pddf = pd.DataFrame({"name": ["Alex", "John"], "age": [30, 27], "salary": [50000, 65000]})print(df[["salary", "name", "age"]])
Output
   salary  name  age
0   50000  Alex   30
1   65000  John   27

Learn the concept

New to this topic? Read the lesson, then come back.

More pandas programs

← All 95 Pandas Programs

Rename all columns

Python Practice › Pandas Programs › Program 49

Rename all columns

EasyPandas Programs · 49 of 95

Write a pandas program to rename columns C1, C2, C3 to A, B, C.

Output
   A  B  C
0  1  6  8
1  3  8  2
2  9  0  6

Approach

  1. rename(columns={...}).

Solution

Python
import pandas as pddf = pd.DataFrame({"C1": [1, 3, 9], "C2": [6, 8, 0], "C3": [8, 2, 6]})print(df.rename(columns={"C1": "A", "C2": "B", "C3": "C"}))
Output
   A  B  C
0  1  6  8
1  3  8  2
2  9  0  6

Learn the concept

New to this topic? Read the lesson, then come back.

More pandas programs

← All 95 Pandas Programs

Column headers

Python Practice › Pandas Programs › Program 48

Column headers

EasyPandas Programs · 48 of 95

Write a pandas program to get a list of column headers.

Output
['name', 'sport']

Approach

  1. df.columns.tolist().

Solution

Python
import pandas as pddf = pd.DataFrame({"name": ["Virat", "Messi", "Kobe"], "sport": ["cricket", "football", "basketball"]})print(df.columns.tolist())
Output
['name', 'sport']

Learn the concept

New to this topic? Read the lesson, then come back.

More pandas programs

← All 95 Pandas Programs

Iterate over rows

Python Practice › Pandas Programs › Program 47

Iterate over rows

EasyPandas Programs · 47 of 95

Write a pandas program to iterate over the rows.

Output
Yash    78
Rakesh  80
Suresh  60

Approach

  1. itertuples() is fast and gives named fields.

Solution

Python
import pandas as pddf = pd.DataFrame([{"name": "Yash", "percentage": 78}, {"name": "Rakesh", "percentage": 80}, {"name": "Suresh", "percentage": 60}])for row in df.itertuples(index=False):    print(f"{row.name:<7} {row.percentage}")
Output
Yash    78
Rakesh  80
Suresh  60
Tip

Prefer column operations over loops when you can; they are much faster on large data.

Learn the concept

New to this topic? Read the lesson, then come back.

More pandas programs

← All 95 Pandas Programs

Add a column

Python Practice › Pandas Programs › Program 46

Add a column

EasyPandas Programs · 46 of 95

Write a pandas program to add a salary column.

Output
    name  age  salary
0   Alex   30   50000
1   John   27   65000
2  Peter   29   58000
3  Klaus   33   66000

Approach

  1. Assign a list to a new column name.

Solution

Python
import pandas as pddf = pd.DataFrame({"name": ["Alex", "John", "Peter", "Klaus"], "age": [30, 27, 29, 33]})df["salary"] = [50000, 65000, 58000, 66000]print(df)
Output
    name  age  salary
0   Alex   30   50000
1   John   27   65000
2  Peter   29   58000
3  Klaus   33   66000

Learn the concept

New to this topic? Read the lesson, then come back.

More pandas programs

← All 95 Pandas Programs

Delete rows

Python Practice › Pandas Programs › Program 45

Delete rows

EasyPandas Programs · 45 of 95

Write a pandas program to delete John’s record.

Output
    name  age
0   Alex   30
2  Peter   29
3  Klaus   33

Approach

  1. Keep the rows that do not match.

Solution

Python
import pandas as pddf = pd.DataFrame({"name": ["Alex", "John", "Peter", "Klaus"], "age": [30, 27, 29, 33]})print(df[df["name"] != "John"])
Output
    name  age
0   Alex   30
2  Peter   29
3  Klaus   33

Learn the concept

New to this topic? Read the lesson, then come back.

More pandas programs

← All 95 Pandas Programs