![](/img/trans.png)
[英]How can I export and import a pandas dataframe with multiindex row and column index into/from a csv file?
[英]How can I export each row from a pandas (Python) DataFrame to separate .txt files?
我正在嘗試導出結構如下的pandas DataFrame:
2列,一列是客戶ID,另一列是文本字符串,其中包含上個月購買的所有商品。
每行代表一個客戶。
我想使用熊貓將每一行導出到單獨的文本文件中。
我對Python相當陌生,任何見解都將不勝感激。
您應該使用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.