首页 > 解决方案 > 使用 Pandas 更新 CSV 文件中的 Nan 值,并在 CSV 的其他列上使用 if else 条件

问题描述

我想根据人的类别更新年龄列中的 Nan 值。csv 文件包含年龄和人的类别。
如果这个人是一等的,他的年龄是 35。
如果这个人是二等的,他的年龄是 30。
如果这个人是三等的,他的年龄是 25。

Csv File
Age   Class
32     2
26     3
Nan    1
36     1
24     3
Nan    2
Nan    3


Update Csv File
Age   Class
32     2
26     3
35     1
36     1
24     3
30     2
25     3

我尝试了一些熊猫功能,但没有奏效。

df[ (df.Age.isnull()) & (df.Pclass==1) ]['Age'] = 35
df[ (df.Age.isnull()) & (df.Pclass==2) ]['Age'] = 30
df[ (df.Age.isnull()) & (df.Pclass==3) ]['Age'] = 25

请提供解决方案....

标签: pythonpandas

解决方案


您可以使用map

age_dict={1:35, 2:30, 3:25}

# read csv
df = pd.read_csv('in_file.csv')

# update the missing ages
df['Age'] = df['Age'].fillna(df['Class'].map(age_dict))

# save csv
df.to_csv('out_file.csv')

推荐阅读