【发布时间】:2021-08-17 13:51:59
【问题描述】:
我在 pandas DF 中有以下一组行:
| idx | col1 | col2 | col3 | col4 |
|---|---|---|---|---|
| 0 | A | B | C | D |
| 1 | E | F | G | H |
| 1 | I | J | K | L |
| 2 | M | M | O | P |
| 2 | Q | R | S | T |
我想将每组索引行转换为 CSV 并打印到文件。
所以我最终得到一个文件,其中一行 idx 0,两行 idx 1,两行 idx 2。
像这样:
文件1
col1,col2,col3,col4
A,B,C,D
文件2
col1,col2,col3,col4
E,F,G,H
I,J,K,L
文件3
col1,col2,col3,col4
M,N,O,P
Q,R,S,T
我有这段代码,但它只给了我每个索引集的第一行:
for i, dfr in Template.TEMPLATE_DF.iterrows():
fpath = path + '\\' + dfr['tmpl.title'].lower().replace(' ', '_') + '_' + str(dfr['tmpl.id']) + '.csv'
dfr=pd.DataFrame(data=dfr).transpose()
dfr.to_csv(fpath, sep=',', encoding='utf-8', na_rep='NULL', index=False)
我在这里错过了什么?
【问题讨论】:
-
dfs = [x for _, x in df.groupby('idx')]在dfs中写出每个df。 -
添加代码以初始化数据框 - 使其成为一个完全运行的程序。然后我们可以复制/更改/粘贴一个可行的解决方案。
-
@Henry Ecker:感谢您的回复。但我仍然只得到一排。我肯定有多行应该在那里。这就是我所做的:
dfs = [x for _, x in dfr.groupby('idx')] for df in dfs: df.to_csv(...) -
不,您应该对源 DF 进行分组。
dfs = [x for _, x in Template.TEMPLATE_DF.groupby('idx')]