gpt4 book ai didi

python - Pandas:如何将 col1 的每一行保存到单独的文件中,并将 col2 的行作为文件名?

转载 作者:行者123 更新时间:2023-12-05 06:36:21 25 4
gpt4 key购买 nike

我有一个数据框 data,它有两列:一列用于“内容”,一列用于“标题”。我正在尝试将“内容”列的每一行导出到一个单独的 .txt 文件,我希望“标题”的相应行成为此 .txt 文件的文件名。

到目前为止,我已经有了这个,它适用于标题部分(每个文件都有不同的文件名),但不适用于内容部分:每个 .txt 文件都具有相同的内容 - 最后一行的内容。如何更改它以便每个 .txt 文件都具有正确的内容?

file = 'C:/mallet/mydata/thesisarticles/{}.txt'

for row2 in data['Title']:
for row in data['Content']:
with open(file.format(row2), 'w') as f:
f.write(str(row))

最佳答案

使用iterrows :

file = 'C:/mallet/mydata/thesisarticles/{}.txt'
for i, row in data.iterrows():
with open(file.format(row['Title']), 'w') as f:
f.write(str(row['Content']))

备选方案:

def f1(row):
with open(file.format(row['Title']), 'w') as f:
f.write(row['Content'])

data.apply(f1, axis=1)

关于python - Pandas:如何将 col1 的每一行保存到单独的文件中,并将 col2 的行作为文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49152922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com