gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:18:21 25 4
gpt4 key购买 nike

我使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com