繁体   English   中英

如何将熊猫(Python)数据帧中的每一行导出到单独的.txt文件?

[英]How can I export each row from a pandas (Python) DataFrame to separate .txt files?

我正在尝试导出结构如下的pandas DataFrame:

  1. 2列,一列是客户ID,另一列是文本字符串,其中包含上个月购买的所有商品。

  2. 每行代表一个客户。

我想使用熊猫将每一行导出到单独的文本文件中。

我对Python相当陌生,任何见解都将不胜感激。

您可以尝试groupby您的数据,然后使用功能to_csv 我通过参数index=False省略了索引。

print df
#   id   item
#0   1  item1
#1   1  item1
#2   1  item1
#3   2  item2
#4   2  item2
#5   3  item3

for name, group in df.groupby('id'): 
    group.to_csv(str(name) + '.txt', index=False)

您应该使用iterrows遍历数据帧的每一行。 然后只需将其写入新文件即可。

示例代码如下所示:

d = your_pandas_dataframe
file = 'file{}.txt'

n = 0 # to number the files
for row in d.iterrows():
    with open(file.format(n), 'w') as f:
        f.write(str(row))
        n += 1

它将生成“ file0.txt”,“ file1.txt”等。每个文件都包含数据帧的一行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM