python - 使用 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
解决方案
使用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
推荐阅读
- android - 使用 PJSIP 开源库进行 VoIP 媒体和信号处理
- c++ - 位图算法
- python - raw_input() 无法正确运行,因为语法分析器
- prestashop-1.7 - 如何将本地开发的 Prestashop 移动到托管服务器
- makefile - GNU 制作 | 如何在源代码层次结构和编译器输出 h-hy 之间创建依赖关系?
- python - 从字典创建字典列表
- laravel-5.8 - laravel 中的作用域是什么,使用它的优缺点是什么?
- r - 我可以在 lmer 中使用 bootMer 获得置信区间吗?
- ios - 警告:非特定平台“*”的“可用”属性中存在意外的版本号
- javascript - 如何在 React-Native 中获取 Android 版本号?(不是 API 级别编号)