【问题标题】:How can I export each row from a pandas (Python) DataFrame to separate .txt files?如何将 pandas (Python) DataFrame 中的每一行导出到单独的 .txt 文件中?
【发布时间】:2016-02-27 03:04:40
【问题描述】:

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

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

  2. 每一行代表一个客户。

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

我是 Python 的新手,非常感谢任何见解。

【问题讨论】:

  • 您能否展示您的努力,以便我们了解您遇到的问题所以不是代码编写服务

标签: python pandas


【解决方案1】:

您可以尝试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)

【讨论】:

    【解决方案2】:

    您应该使用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'、...等。每个文件包含一行数据框。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-06
      • 2018-03-31
      相关资源
      最近更新 更多