简体   繁体   English

将函数应用于熊猫中的不同列

[英]Apply function to different columns in pandas

I have a puzzling case, my data frame look like this 我有一个令人费解的案例,我的数据框看起来像这样

  id    high low medium count
0  0     0    4    8     12
1  1     5    2    1      8

I want to generate 3 additional columns for each of the level: high, low medium. 我想为每个级别生成3个其他列:高,低中。

I defined a function 我定义了一个功能

def foo(row['high']):
    return  (1/3+row['high']/(1+row['count']))

I think I need to apply this function 3 times, and change the row['high'], row['low'] and row['medium']. 我认为我需要应用此函数3次,并更改row ['high'],row ['low']和row ['medium']。

I've used something like 我用过类似的东西

df = df.apply(foo,axis=1)

However, it doesn't work. 但是,它不起作用。 I wonder if there is a good way (maybe I could just apply this function once?) to do this.... 我想知道是否有一个好方法(也许我可以只应用一次此功能?)。

You can't define a function that has an indexed variable as a parameter name. 您不能定义将索引变量作为参数名称的函数。 Change this: 更改此:

def foo(row['high']):

to this: 对此:

def foo(row):

But, for what you are doing, you don't need to apply a function. 但是,对于您正在做的事情,您无需应用功能。 It can be accomplished with operations on the columns. 可以通过对列进行操作来完成。

(1/3)+df['high']/(1+df['count'])

# returns:
0    0.333333
1    0.888889
dtype: float64

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM