4 回答
TA贡献1805条经验 获得超9个赞
您可以使用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')
TA贡献1780条经验 获得超1个赞
享受:
df['Age'] = np.where((df.Age.isnull() == True) & (df.Pclass==1), 35, df['Age])
df['Age'] = np.where((df.Age.isnull() == True) & (df.Pclass==2), 30, df['Age])
df['Age'] = np.where((df.Age.isnull() == True) & (df.Pclass==3), 25, df['Age])
TA贡献1936条经验 获得超6个赞
我想这样的事情应该有效,
df['Age'][ df['Age'].isnull() & df['lass'] == 1] = 35
df['Age'][ df['Age'].isnull() & df['lass'] == 2] = 30
df['Age'][ df['Age'].isnull() & df['lass'] == 3] = 25
TA贡献1796条经验 获得超4个赞
在导入pandas之前先将csv文件转换成如下图:
Age,Class
32,2
26,3
,1
36,1
24,3
,2
,3
现在导入 csv 文件并将值分配给 Nan。
import pandas as pd
df = pd.read_csv(YOUR_CSV_FILE)
df.loc[ (df.Age.isna()) & (df.Class==1) ] = 35,1
df.loc[ (df.Age.isna()) & (df.Class==2) ] = 30,1
df.loc[ (df.Age.isna()) & (df.Class==3) ] = 25,1
- 4 回答
- 0 关注
- 134 浏览
添加回答
举报