Skip to main content
 首页 » 编程设计

python之按 Dataframe 中的列分组并为每个组创建单独的 csv

2024年10月17日8傻小

我有一个 1 GB 的巨大 csv 文件,其中包含每天的记录。示例如下

Date        orderquantity 
 
2015-06-19   23 
2015-06-19   30 
2015-06-20   33 
2015-06-20   40 

所以每天都有记录,Python Pandas 数据框中是否有一种有效的方法,我可以根据日期对数据进行分组,然后将其存储为每个日期的单独 csv。

我上面例子的输出结果是

  CSV 1  
Date           orderquantity 
2015-06-19      23 
2015-06-19      30 
 
CSV 2 
 Date           orderquantity 
 2015-06-20     33 
 2015-06-20     40 

我是否必须喜欢在数据框中按日期排序/分组,然后使用 for 循环遍历整个数据框?

请您参考如下方法:

试试这个:

for name, group in df.groupby('Date'): 
    group.to_csv('{}.csv'.format(name), index=False)