如何将pandas(Python)数据帧中的每一行导出到单独的.txt文件中?
我正在尝试导出熊猫数据帧,其结构如下:如何将pandas(Python)数据帧中的每一行导出到单独的.txt文件中?,python,pandas,Python,Pandas,我正在尝试导出熊猫数据帧,其结构如下: 两列,一列是客户ID,另一列是包含上个月购买的所有项目的文本字符串 每行代表一个客户 我想使用pandas将每一行导出到一个单独的文本文件中 我是Python新手,非常感谢您的见解。您可以尝试使用数据,然后使用函数。我通过参数index=False忽略索引 print df # id item #0 1 item1 #1 1 item1 #2 1 item1 #3 2 item2 #4 2 item2 #5 3
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)
您可以尝试您的数据,然后使用函数。我通过参数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)
您应该使用来迭代数据帧的每一行。然后简单地将其写入一个新文件中
示例代码如下所示:
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'、。。。等。每个文件包含数据框的一行。您应该使用来迭代数据框的每一行。然后简单地将其写入一个新文件中
示例代码如下所示:
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'、。。。等等。每个文件都包含一行数据框。您能否展示您的努力,以便我们能够了解您在哪里卡住了,因此不是代码编写服务您能否展示您的努力,以便我们能够了解您在哪里卡住了,因此不是代码编写服务