例如,我有一个数据如下所示:
df = pd.DataFrame([[np.NaN, '1-5'], [np.NaN, '26-100'], ['Yes', 'More than 1000'], ['No', '26-100'], ['Yes', '1-5']], columns=['self_employed', 'no_employees'])
df
self_employed no_employees
0 nan 1-5
1 nan 26-100
2 Yes More than 1000
3 No 26-100
4 Yes 1-5我试图根据以下条件填充空值:
If no_employees is '1-6' then 'Yes', otherwise 'No'我能够使用字典完成这一工作,例如:
self_employed_dict = {'1-5': 'Yes', '6-25': 'No', '26-100': 'No', '100-500': 'No', 'More than 1000':'No', '500-1000': 'No'}
df['self_employed'] = df['self_employed'].fillna(df['no_employees'].map(self_employed_dict))但我想知道是否有一种更好、更简单的方法来做到这一点。在这个例子中,我不得不为自己编写字典来映射它,那么我如何才能聪明地做到这一点呢?
预期的输出如下所示:
self_employed no_employees
0 Yes 1-5
1 No 26-100
2 Yes More than 1000
3 No 26-100
4 Yes 1-5发布于 2020-12-27 22:08:18
使用填充物是正确的方法,但是您可以这样做:
values = df['no_employees'].eq('1-5').map({False: 'No', True: 'Yes'})
df['self_employed'] = df['self_employed'].fillna(values)
print(df)输出
self_employed no_employees
0 Yes 1-5
1 No 26-100
2 Yes More than 1000
3 No 26-100
4 Yes 1-5发布于 2020-12-27 22:44:37
答案取决于你的熊猫版本。有两种情况:
print(df['self_employed'].isna()).any()将返回False 和/或
type(df.iloc[0,0])返回str类型。
在这种情况下,您的dataframe的所有元素都是string类型的,fillna()将无法工作。这是因为fillna()函数不会对字符串nan作出反应,因此可以使用update()。helper = df['no_employees'].eq('1-5').map({False: 'No', True: 'Yes'}).to_frame('self_employed')
df.update(other=helper, filter_func=lambda x: df['self_employed'].eq('nan'))print(df['self_employed'].isna()).any()将返回True 和/或
type(df.iloc[0,0])返回类型floatvalues = df['no_employees'].eq('1-5').map({False: 'No', True: 'Yes'})
df['self_employed'] = df['self_employed'].fillna(values)这会让你:
self_employed no_employees
0 Yes 1-5
1 No 26-100
2 Yes More than 1000
3 No 26-100
4 Yes 1-5发布于 2020-12-27 22:09:34
https://stackoverflow.com/questions/65470708
复制相似问题