如何在特定的熊猫数据框列上自定义函数调用顺序?

问题描述 投票:0回答:1

我有一个自定义功能列表:

Func =[{'func':'push','col':'A'},{'func':'pull','col':'B'}]
def push : #do something
def pull : #do something

我的数据框:

id  A   B
1  23  24
2  99  88

我希望按照上面提到的列表'Func'在列表中指定的特定顺序对该数据帧进行操作。例如,首先在columnA上调用函数“ Push”,获取该输出数据帧,然后在新数据帧上调用函数“ Pull”。

python pandas list dataframe dictionary
1个回答
0
投票

由于函数是python中的一等公民,因此您可以将它们作为值放入dict中,

然后只是迭代您列出并在所需列上调用该函数:

编辑:现在使用exec将函数名称作为字符串(请参阅OP注释)

import pandas as pd

df = pd.DataFrame({"A":[23,99], "B":[24,88]})

def push(series):
  series -= 1
def pull(series):
  series /= 2

print("before:")
print(df)

Func =[{'func':'push','col':'A'},{'func':'pull','col':'B'}]

for f in Func:
  exec('{}(df[f["col"]])'.format(f['func']))

print("after:")
print(df)

输出:

before:
    A   B
0  23  24
1  99  88
after:
    A     B
0  22  12.0
1  98  44.0
© www.soinside.com 2019 - 2024. All rights reserved.