首页 > 解决方案 > 如何使用 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)

标签: pythonpandasnumpy

解决方案


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 表达式中调用其他函数。


推荐阅读