相关疑难解决方法(0)

如何将函数应用于两列Pandas数据帧

假设我有一个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)

python dataframe pandas

289
推荐指数
13
解决办法
37万
查看次数

如何将Pandas的"apply"功能用于多个列?

当使用具有以下数据帧的多个列时,我在使用Pandas应用函数时遇到一些问题

df = DataFrame ({'a' : np.random.randn(6),
                 'b' : ['foo', 'bar'] * 3,
                 'c' : np.random.randn(6)})
Run Code Online (Sandbox Code Playgroud)

以及以下功能

def my_test(a, b):
    return a % b
Run Code Online (Sandbox Code Playgroud)

当我尝试应用此功能时:

df['Value'] = df.apply(lambda row: my_test(row[a], row[c]), axis=1)
Run Code Online (Sandbox Code Playgroud)

我收到错误消息:

NameError: ("global name 'a' is not defined", u'occurred at index 0')
Run Code Online (Sandbox Code Playgroud)

我不明白这个消息,我正确地定义了这个名字.

我非常感谢你对这个问题的任何帮助

更新

谢谢你的帮助.我确实用代码做了一些语法错误,索引应该放''.但是我使用更复杂的功能仍然存在同样的问题,例如:

def my_test(a):
    cum_diff = 0
    for ix in df.index():
        cum_diff = cum_diff + (a - df['a'][ix])
    return cum_diff 
Run Code Online (Sandbox Code Playgroud)

谢谢

python apply dataframe python-2.7 pandas

228
推荐指数
4
解决办法
38万
查看次数

标签 统计

dataframe ×2

pandas ×2

python ×2

apply ×1

python-2.7 ×1