簡體   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