python - 如何使用 np.where 的返回值或在其中应用函数
问题描述
我有一个这样的数据框如何使用 np.where 的返回值
samples= pd.DataFrame({'data':['1','2', '5','6','2','1']})
Output :
data
0 1
1 2
2 6
3 5
4 2
5 1
我可以用 :
samples['result'] = np.where(samples['data'] > samples['data'].shift(-1), 'High', 'Low')
output :
data result
0 1 Low
1 2 High
2 6 High
3 5 Low
4 2 Low
5 1 Low
如果结果很高,我想创建一个新列并从数据列中获取值
expect output :
if result == High, create new column and get value from data on that row, or call a function
data result final
0 1 Low NaN
1 2 High 2 if High do somthing with other function
2 6 High 6 else
3 5 Low NaN if Low call other function
4 2 Low NaN
5 1 Low NaN
或者如果我可以调用一个函数 insdie np.where()
a = print('this is High')
b = print('this is Low')
final = np.where(samples['data'] > samples['data'].shift(-1), a, b)
解决方案
apply
可以axis=1
做到:
>>> samples['final'] = samples.agg(lambda row: row['data'] if row['result'] == 'High' else np.nan, axis=1)
>>> samples
data result final
0 1 Low NaN
1 2 Low NaN
2 5 Low NaN
3 6 High 6
4 2 High 2
5 1 Low NaN
您可以在 lambda 表达式中调用其他函数。
推荐阅读
- ios - 在 TableView 单元格中处理从 Firebase 检索数据的更好方法
- python - 使用 Python 导入文件 - 如果文件不存在,如何跳过?
- h2 - 如何在 H2 数据库中执行 N 次查询?
- javascript - 如何通过单击更改按钮的颜色
- r - 如何将向量写入数据表同一行的几列?
- python - 在python中创建曲率动画
- angular - 用于 Anguar 7 的 MSAL 库配置以与 tenant.b2clogin.com 一起使用
- shell - 将小时数添加到文本文件中的所有时间戳
- python - 具有来自两个非重叠列的值的熊猫数据透视表
- java - 从 github 克隆现有 Android 项目时出错