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

标签 python pandas function generics

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

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/

相关文章:

python-2.7 - 如何更新 pandas 数据框列中的值,直到同一列中第一次出现值?

Python属性错误: 'Series' object has no attribute 'isdigit'

C代码,搜索功能

javascript - 通过按钮将变量传递给函数(HTML/Javascript)

python - 在 Django 中使用用户输入构建动态查询

python - python 中的 Cron 解析器和验证

python - 字符串python中的空格

python - 使用另一个数据帧中的值对对数据帧进行子化

python - 从函数返回用户提供的值

python - 将嵌套字典替换为空数据帧