Python Pandas GroupBy 返回空白行

标签 python pandas

我正在尝试对具有

的数据框进行分组
date
month_year
business_id
sales
cost

作者:

df.groupby(['month_year', 'business_id'])[['sales','cost']].sum()

返回结果:

month_year  business_id  sales  cost
2016/01     1             44     43 
            2             55     43
            3             55     34 

但是我需要将此 df 插入到 SQL 表中,并且需要格式为平面表,每行包含 Month_year:

month_year  business_id  sales  cost
2016/01     1             44     43 
2016/01     2             55     43
2016/01     3             55     34 

我该如何实现这一目标? (注意实际数据有不同月份)

最佳答案

将 .reset_index() 添加到 groupby 的末尾:

df.groupby(['month_year', 'business_id'])[['sales','cost']].sum().reset_index()

关于Python Pandas GroupBy 返回空白行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43127509/

相关文章:

python - 创建一个可以通过 Pip 和 virtualenv 安装的简单包

python - 给定等边三角形的 2D 角坐标的 3D 法线向量

python - 更新字典并在键存在时追加

python - 值更改时的标签行 pandas

python - 使用上一行值来计算日志

python - 向 100K+ 数据集添加行

python - Windows 上的 Jenkins : UE4 packaging for iOS fails with "Host key verification failed."

python - 将 loc 应用于 2 列值 Pandas

python - 在 pandas DataFrame 中添加元素很困难

python - Pandas - 迭代数据框行并更新 df(一行代码)