如何在python中的函数中将局部函数应用于数据框的特定列?

时间:2019-10-15 18:56:22

标签: python function

我正在尝试在python中定义一个函数,其中特定列中数据框中的负值上限为零。因此,我定义了一个将x作为输入的函数,如果它为负数,则将其上限为零(cap0),然后将此函数应用于特定的列。但是,当我用python编写函数时,它会继续运行(就像我的函数没有关闭一样)。如果可以帮助我,请感谢。

P.S。我对python很新

def captozero(df, cap_vars):
   def cap0(x):
       x_out = x.copy()
       x_out = np.where(x_out < 0, 0, x)
       return x_out
   df_out = df.copy()
   df_out = df_out.apply(lambda x: cap0(x) if x.name in [cap_vars] else x)
   return df_out

2 个答案:

答案 0 :(得分:2)

有一个numpy函数,用于比较结果并取最大值。 就您而言,

for i in cap_vars:
    df[i] = np.maximum(df[i], 0)

或者您可以在每列中使用np.where

for i in cap_vars:
    df[i] = np.where(df[i] < 0, 0, df[i])

答案 1 :(得分:1)

有一个功能DataFrame.clip可用于此目的:

import pandas as pd
df = pd.DataFrame({'col1':[-1,2,4],'col2':[2,-3,5], 'col3':[1,2,3]})
print(df, '\n')

df.update(df[['col1', 'col2']].clip(0))

print(df)

产生以下输出:

   col1  col2  col3
0    -1     2     1
1     2    -3     2
2     4     5     3 

   col1  col2  col3
0     0     2     1
1     2     0     2
2     4     5     3

请注意使用更新功能使用新剪切的版本覆盖数据框中的列