gpt4 book ai didi

python - 有没有办法让 pandas 中的函数更通用?

转载 作者:行者123 更新时间:2023-12-01 08:09:00 35 4
gpt4 key购买 nike

我正在为数据集编写一些函数,我想知道是否有一种方法可以编写这些函数,使它们能够在列可能具有不同名称的多个数据集上工作。

def calc(df):
a = df.groupby(['Region', 'Year'], as_index=False)["Sales"].sum()
print(a.to_string(index=False))

这个函数工作没有任何问题,因为我指定了列名称。无论如何,有没有做这样的事情:

def calc(df, x1, x2, x3):
a = df.groupby([x1, x2], as_index=False)[x3].sum()
print(a.to_string(index=False))

并像这样输入值:

if __name__ == "__main__":
report2(df, df['Region'], df['Year'], df["Sales"])

当我尝试这样做时,我总是收到错误:

Traceback (most recent call last):
File "sales_record.py", line 60, in <module>
calc(df, df['Region'], df['Year'], df["Sales"])
File "sales_record.py", line 54, in calc
answer = df.groupby([x1, x2], as_index=False)[x3].sum()
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\core\base.py", line 265, in __getitem__
.format(missing=str(bad_keys)[1:-1]))
KeyError: 'Columns not found: 7200, 22500, 82500, 1800, 45000, 9000, 99000, 18000, 22000, 8400, 110000, 16500, 54000, 112500, 3000'

任何帮助将不胜感激。

最佳答案

最简单的是调用列名称:

calc(df, 'Region', 'Year', "Sales")

您的解决方案应该稍微改变一下才能工作 - 也传递 Series 而不是 DaatFrame - 检查 this - 它也称为语法糖:

def calc1(x1, x2, x3):
a = x3.groupby([x1, x2], as_index=False).sum()
print(a.to_string(index=False))

calc1(df['Region'], df['Year'], df["Sales"])

关于python - 有没有办法让 pandas 中的函数更通用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55378869/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com