【发布时间】:2012-10-31 04:01:08
【问题描述】:
假设我有一个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: ('<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']
【问题讨论】:
-
我在下面的 url 找到了一个相关的问答,但我的问题是通过两个现有列计算一个新列,而不是 2 from 1 。 stackoverflow.com/questions/12356501/…