![](/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.