pandas-groupby - group by 创建多个文件

标签 pandas-groupby

我使用 pandas groupby 编写了一段代码,它正在运行。 我的问题是如何将每个组保存在 Excel 工作表中。 例如你有一组水果 ['apple', 'grapes',.....'mango '] 我想将 apple 保存在一个 excel 中,然后在另一个 excel 中打个哈欠

import pandas as pd

df = pd.read_excel('C://Desktop/test/file.xlsx')
g = df.groupby('fruits')
for fruits, fruits_g in g:
        print(fruits)
        print(fruits_g)
Mango 
  name   id   purchase   fruits
1  john  877          2  Mango 

apple
  name   id   purchase  fruits
0   ram  654          5  apple
3  Sam   546          5  apple

BlueB
   name   id   purchase   fruits
7  david  767          9  black 

grapes
  name   id   purchase   fruits
2  Dan   454          1  grapes
4   sys  890          7  grapes

mango
  name   id   purchase  fruits
5  baka  786          6  mango

strawB
    name   id   purchase  fruits
6  silver  887          9  straw

如何为每组水果创建一个excel?

最佳答案

这可以使用 pandas.DataFrame.to_excel 来完成:

import pandas as pd

df = pd.DataFrame({
    "Fruit": ["apple", "orange", "banana", "apple", "orange"],
    "Name": ["John", "Sam", "David", "Rebeca", "Sydney"],
    "ID": [877, 546, 767, 887, 890],
    "Purchase": [1, 2, 5, 6, 4]
})

grouped = df.groupby("Fruit")

# run this to generate separate Excel files
for fruit, group in grouped:
    group.to_excel(excel_writer=f"{fruit}.xlsx", sheet_name=fruit, index=False)

# run this to generate a single Excel file with separate sheets
with pd.ExcelWriter("fruits.xlsx") as writer:
    for fruit, group in grouped:
        group.to_excel(excel_writer=writer, sheet_name=fruit, index=False)

关于pandas-groupby - group by 创建多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57496820/

相关文章:

python - 在组内使用 pandas.shift()

python - Pandas groupBy 与条件分组

python - Pandas groupby 意味着不在日期时间列上工作

python - 在 pandas 中绘制 groupby 操作的结果

pandas - 使用 GeoPandas 从点创建多边形

python - 使用 Pandas groupby 如何使用加法聚合一列列表?

python - 将 kwargs 添加到带有字典参数的 pandas apply 语句

python - 从 Python pandas 中的空间数据创建 bin - 可能使用 groupby、diff 和 cut?

python-3.x - 如何对Python Pandas groupby对象进行不同长度的切片?

python - 如何聚合group by并在出现某个值后丢弃行?