首页 > 解决方案 > 使用 Pandas 用条件填充 NULL 值的最佳方法?

问题描述

因此,例如,我有一个数据如下所示:

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

我正在尝试根据以下条件填充 NULL 值:

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

标签: pythonpandasdataframe

解决方案


使用fillna是正确的方法,但您可以这样做:

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

推荐阅读