[英]Exporting a dataframe to several csv files based on value in a column in python
I have the following code for exporting each "id" to a separate csv file.我有以下代码用于将每个“id”导出到单独的 csv 文件。 Each csv file should be named as an id.
每个 csv 文件都应该命名为一个 id。 Here in my case, we should have three different csv files named 23, 24, and 25. I have the code in below but it gives me an error.
在我的例子中,我们应该有三个不同的 csv 文件,分别命名为 23、24 和 25。我有下面的代码,但它给了我一个错误。 Thanks.
谢谢。
import pandas as pd
path = "users/AR/csv files"
for (id), id in df.groupby(['id']):
group.to_csv(f'{id}.csv', directory=path, index=False)
NameError: name 'group' is not defined
id ![]() |
date![]() |
count![]() |
---|---|---|
23 ![]() |
2/2/2016 ![]() |
24 ![]() |
24 ![]() |
2/4/2016 ![]() |
56 ![]() |
25 ![]() |
2/3/2016 ![]() |
135 ![]() |
23 ![]() |
3/4/2016 ![]() |
46 ![]() |
24 ![]() |
3/8/2016 ![]() |
176 ![]() |
25 ![]() |
3/9/2016 ![]() |
23 ![]() |
23 ![]() |
3/16/2016 ![]() |
98 ![]() |
24 ![]() |
3/13/2016 ![]() |
114 ![]() |
25 ![]() |
3/17/2016 ![]() |
43 ![]() |
I am expecting three separated csv files in the directory.我期望目录中有三个单独的 csv 文件。
Just change:只是改变:
for (id), id in df.groupby(['id']):
with:和:
for id, group in df.groupby(['id']):
When iterating groupby object, you get separate grouping value (in id
, in your case), from particular group sub-dataframe (here: in group
).当迭代 groupby object 时,您会从特定的组子数据帧(此处:在
group
中)获得单独的分组值(在您的情况下为id
)。 id
is then used to name a csv file, while group
df is exported to csv.然后用
id
命名一个csv的文件,而group
df导出到csv。
Furthermore, there is no directory
parameter in to_csv
method.此外,
to_csv
方法中没有directory
参数。 The easiest method is to include path in the filename string, like f'users/AR/csv files/{id}.csv'
.最简单的方法是在文件名字符串中包含路径,例如
f'users/AR/csv files/{id}.csv'
。 If you need OS-agnostic solution, you can use os.path
method.如果您需要与操作系统无关的解决方案,您可以使用
os.path
方法。
This can be done with list comps:这可以通过 list comps 来完成:
dfs = [x.reset_index(drop=True) for _, x in df.groupby("id")]
[x.to_csv(f"users/AR/csv files/{x['id'][0]}.csv", index=False) for x in dfs]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.