假设我有一个 df
有 'ID', 'col_1', 'col_2'
列。我定义了一个函数:
f = lambda x, y : my_function_expression
。
Now I want to apply the f
to df
’s two columns 'col_1', 'col_2'
to element-wise calculate a new column 'col_3'
, somewhat like :
df['col_3'] = df[['col_1','col_2']].apply(f)
# Pandas gives : TypeError: ('<lambda>() 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']
原文由 bigbug 发布,翻译遵循 CC BY-SA 4.0 许可协议
在 Pandas 中有一种简洁的单行方式:
这允许
f
成为具有多个输入值的用户定义函数,并使用(安全)列名而不是(不安全)数字索引来访问列。数据示例(基于原始问题):
print(df)
的输出:如果您的列名包含空格或与现有数据框属性共享名称,则可以使用方括号进行索引: