假设我有一个df列'ID', 'col_1', 'col_2'.我定义了一个函数:
f = lambda x, y : my_function_expression.
现在我想应用fto 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)'
Run Code Online (Sandbox Code Playgroud)
怎么做 ?
** 添加详细示例如下 ***
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 …Run Code Online (Sandbox Code Playgroud) 我可以.map(func)在df中的任何列上使用,例如:
df=DataFrame({'a':[1,2,3,4,5,6],'b':[2,3,4,5,6,7]})
df['a']=df['a'].map(lambda x: x > 1)
Run Code Online (Sandbox Code Playgroud)
我还可以:
df['a'],df['b']=df['a'].map(lambda x: x > 1),df['b'].map(lambda x: x > 1)
Run Code Online (Sandbox Code Playgroud)
是否有更多的pythonic方法将函数应用于所有列或整个帧(没有循环)?