如何将函数应用到Pandas数据框的两列数据

80 浏览
0 Comments

如何将函数应用到Pandas数据框的两列数据

假设我有一个 df,它具有列 \'ID\',\'col_1\',\'col_2\'。然后我定义了一个函数:

f = lambda x,y:my_function_expression

现在我想把 f 应用到 df 的两列 \'col_1\',\'col_2\',以逐元素计算新列 \'col_3\',有点像:

df['col_3'] = df[['col_1','col_2']].apply(f)  
# Pandas gives : TypeError: ('() takes exactly 2 arguments (1 given)'

该如何操作?

**添加以下详细示例**

import pandas as pd
df = pd.DataFrame({'ID':['1','2','3'], 'col_1': [0,2,3], 'col_2':[1,4,5]})
mylist = ['a','b','c','d','e','f']
def get_sublist(sta,end):
    return mylist[sta:end+1]
#df['col_3'] = df[['col_1','col_2']].apply(get_sublist,axis=1)
# expect above to output df as below 
  ID  col_1  col_2            col_3
0  1      0      1       ['a', 'b']
1  2      2      4  ['c', 'd', 'e']
2  3      3      5  ['d', 'e', 'f']

admin 更改状态以发布 2023年5月20日
0
0 Comments

下面是在数据框上使用 apply 的示例,我使用了 axis=1 进行调用。

需要注意的是,与尝试向函数 f 传递两个值不同,重写函数来接受一个 pandas Series 对象,然后通过索引 Series 来获取所需的值。

In [49]: df
Out[49]: 
          0         1
0  1.000000  0.000000
1 -0.494375  0.570994
2  1.000000  0.000000
3  1.876360 -0.229738
4  1.000000  0.000000
In [50]: def f(x):    
   ....:  return x[0] + x[1]  
   ....:  
In [51]: df.apply(f, axis=1) #passes a Series object, row-wise
Out[51]: 
0    1.000000
1    0.076619
2    1.000000
3    1.646622
4    1.000000

根据您的用例,有时有助于创建一个 pandas group 对象,然后在组上使用 apply

0
0 Comments

在Pandas中,有一种简洁的方法可以完成这个任务:

df['col_3'] = df.apply(lambda x: f(x.col_1, x.col_2), axis=1)

这样可以让f成为一个具有多个输入值的用户定义函数,并使用(安全的)列名而不是(不安全的)数字索引来访问列。

以数据为例(基于原始问题):

import pandas as pd
df = pd.DataFrame({'ID':['1', '2', '3'], 'col_1': [0, 2, 3], 'col_2':[1, 4, 5]})
mylist = ['a', 'b', 'c', 'd', 'e', 'f']
def get_sublist(sta,end):
    return mylist[sta:end+1]
df['col_3'] = df.apply(lambda x: get_sublist(x.col_1, x.col_2), axis=1)

print(df)的输出:

  ID  col_1  col_2      col_3
0  1      0      1     [a, b]
1  2      2      4  [c, d, e]
2  3      3      5  [d, e, f]

如果您的列名包含空格或与现有的数据框属性共享名称,您可以使用方括号进行索引:

df['col_3'] = df.apply(lambda x: f(x['col 1'], x['col 2']), axis=1)

0