分组以创建多个文件

时间:2019-08-14 14:34:44

标签: pandas-groupby

我已经使用pandas groupby编写了代码,并且可以正常工作。 我的问题是如何将每个组保存在Excel工作表中。 例如,您有一组水果['apple','grapes',.....'mango '] 我想将苹果保存在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?

1 个答案:

答案 0 :(得分:0)

这可以使用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)