Pandas 使用 DataFrame.dropna() 方法只删除所有列都是 NaN 值的行,如何做?[今日热搜 ]

Pandas 使用 DataFrame.dropna() 方法只删除所有列都是 NaN 值的行,如何做?[今日热搜 ]

已邀请:
import pandas as pd

roll_no = [501, 502, 503, 504, 505]

data = pd.DataFrame({
'Id': [621, 645, 210, 345, None],
'Age': [19, None, 18, 21, None],
'Income($)': [4000, 5000, None, 3500, None],
'Expense($)': [3000, 2000, 2500, 25000, None]

})
print("Initial DataFrame:")
print(data)

print("")

data = data.dropna(how='all')
print("DataFrame after removing rows with NaN value in All Columns:")
print(data)
输出:

Initial DataFrame:
Id Age Income($) Expense($)
0 621.0 19.0 4000.0 3000.0
1 645.0 NaN 5000.0 2000.0
2 210.0 18.0 NaN 2500.0
3 345.0 21.0 3500.0 25000.0
4 NaN NaN NaN NaN

DataFrame after removing rows with NaN value in All Columns:
Id Age Income($) Expense($)
0 621.0 19.0 4000.0 3000.0
1 645.0 NaN 5000.0 2000.0
2 210.0 18.0 NaN 2500.0
3 345.0 21.0 3500.0 25000.0
它只删除 DataFrame 中所有字段中含有 NaN 值的行。我们在 dropna() 方法中设置 how='all',让该方法只在行的所有列值都是 NaN 时才删除行

要回复问题请先登录注册