将方法列表中的方法应用于 pandas 数据框 [英] Apply a method from a list of methods to pandas dataframe
问题描述
这是我的第一个问题,请耐心等待.
this is my first question here so please be patient with me.
我的问题如下:
假设我们有一个pandas数据框,我们想将一些pd.Series方法动态地应用于此数据框的一组列.为什么下面的示例不起作用?
Assume we have a pandas Dataframe and we want to apply dynamically some pd.Series methods to a set of columns of this Dataframe. Why the following example doesn't work?
testframe=pd.DataFrame.from_dict({'col1': [1,2] ,'col2': [3,4] })
funcdict={'col1':[pd.Series.astype,str.replace],'col2':[pd.Series.astype,str.replace]}
argdict= {'col1':[['str'],['1','A']],'col2':[['str'],['3','B']]}
for col in testframe.columns:
for func in funcdict[col]:
idx=funcdict[col].index(func)
testframe[col]=testframe[col].func(*argdict[col][idx])
预期结果将是
col1 col2
0 'A' 'B'
1 '1' '4'
但是我却得到了
AttributeError: 'Series' object has no attribute 'func'
非常
testframe['col1']=testframe['col1'].astype(*argdict['col1'][0])
可以按预期工作,因此尽管存在
works as expected, so somehow python seems to have a problem with the '.func' syntax despite the fact that
print(func)
产生所需的输出:函数NDFrame.astype at 0x00000186954EB840"等.
yields the desired output: 'function NDFrame.astype at 0x00000186954EB840' etc.
推荐答案
您调用方法的语法不正确.您可以通过两种方法在Python中调用方法.
Your syntax for calling a method is incorrect. There are 2 ways you can call a method in Python.
直接
如您所见,这将起作用.请注意,astype
并未引用其他对象,它是属于pd.Series
的方法的实际名称.
As you found, this will work. Note that astype
isn't referencing some other object, it's the actual name of the method belonging to pd.Series
.
testframe['col1'] = testframe['col1'].astype(*argdict['col1'][0])
功能性
该功能方法明确表明astype
是该方法的名称.
The functional method demonstrates explicitly that astype
is the name of the method.
from operator import methodcaller
testframe['col1'] = methodcaller('astype', *argdict['col1'][0])(testframe[col])
尝试testframe[col].func(...)
永远不会起作用,因为func
不是pd.Series
方法的名称.
Trying testframe[col].func(...)
will never work as func
is not the name of a pd.Series
method.
这篇关于将方法列表中的方法应用于 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!