作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在为数据集编写一些函数,我想知道是否有一种方法可以编写这些函数,使它们能够在列可能具有不同名称的多个数据集上工作。
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/
我是一名优秀的程序员,十分优秀!