如何将功能应用于熊猫df

时间:2020-07-09 09:01:53

标签: python pandas

这是我的问题。我有这个Excel文件,当我通过熊猫导入时,我得到了这个DF:

   one  two     three
0   12  0.0     NaN
1   34  NaN     NaN
2   56  34.0    NaN
3   67  5.0     NaN
4   45  0.0     NaN

现在我想应用检查功能:

if 'two' > 0:
    then 'three' = 'two'
else
    'three' = 'one'

这里是完整代码:

import pandas as pd
df = pd.read_excel('test.xlsx')
df.fillna(0.0, inplace=True)
def func(one, two):
    three = one
    if two > 0:
        three = two
    return three
df['three'] = df.apply(func(['one'], ['two']), axis='columns')

但是我得到了以下错误消息:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-f84fe01cb9a5> in <module>
----> 1 df['three'] = df.apply(func(['one'], ['two']), axis='columns')

<ipython-input-11-7cfcd0a409d1> in func(one, two)
      1 def func(one, two):
      2     three = one
----> 3     if two > 0:
      4         three = two
      5     return three

TypeError: '>' not supported between instances of 'list' and 'int'

怎么了?如何将列表更改为int?谢谢!

1 个答案:

答案 0 :(得分:1)

尝试一下,np.where

df['three'] = np.where(df['two'] > 0, 'two', 'one')