如何根据其他列的某些值替换列的 nan 值
How to replace nan values of a column based on certain values of other column
我有两列,col1 指的是教育水平,col2 指的是他们的工作。
col2 有一些 nan 值,所以我想根据第 1 列的值替换这个 nan 值。
例如,如果 col1='bachelor' 那么 col2 必须是 ='teacher'
if col1='high school' then col2='actor'.. 依此类推,我有 7 个不同的 col1.
值
我试过创建这样的函数:
def rep_nan(x):
if x['col1']=='bachelor':
x['col2']='teacher'
elif x['col1']=='blabla':
x['col2']='blabla'
.....
elif x['col1']='high school':
x['col2']='actor'
然后我应用到我的数据集:
df.apply(rep_nan,axis=1)
但结果是 None 列
哪里出错了?或者我该如何完成这项任务?
你可以在这里制作字典:
rep_nan = {
'bachelor': 'tacher',
'blabla': 'blabla',
'high school': 'actor'
}
然后我们可以将 nan 值替换为:
df.loc[df['col2'].isnull(), 'col2'] = df[df['col2'].isnull()]['col1'].replace(rep_nan)
例如:
>>> df
col1 col2
0 bachelor None
1 bachelor clown
2 blabla None
3 high school None
>>> df.loc[df['col2'].isnull(), 'col2'] = df[df['col2'].isnull()]['col1'].replace(rep_nan)
>>> df
col1 col2
0 bachelor tacher
1 bachelor clown
2 blabla blabla
3 high school actor
我有两列,col1 指的是教育水平,col2 指的是他们的工作。 col2 有一些 nan 值,所以我想根据第 1 列的值替换这个 nan 值。 例如,如果 col1='bachelor' 那么 col2 必须是 ='teacher' if col1='high school' then col2='actor'.. 依此类推,我有 7 个不同的 col1.
值我试过创建这样的函数:
def rep_nan(x):
if x['col1']=='bachelor':
x['col2']='teacher'
elif x['col1']=='blabla':
x['col2']='blabla'
.....
elif x['col1']='high school':
x['col2']='actor'
然后我应用到我的数据集:
df.apply(rep_nan,axis=1)
但结果是 None 列
哪里出错了?或者我该如何完成这项任务?
你可以在这里制作字典:
rep_nan = {
'bachelor': 'tacher',
'blabla': 'blabla',
'high school': 'actor'
}
然后我们可以将 nan 值替换为:
df.loc[df['col2'].isnull(), 'col2'] = df[df['col2'].isnull()]['col1'].replace(rep_nan)
例如:
>>> df
col1 col2
0 bachelor None
1 bachelor clown
2 blabla None
3 high school None
>>> df.loc[df['col2'].isnull(), 'col2'] = df[df['col2'].isnull()]['col1'].replace(rep_nan)
>>> df
col1 col2
0 bachelor tacher
1 bachelor clown
2 blabla blabla
3 high school actor