gpt4 book ai didi

python - 在python中将文本文件转换为.xlsx

转载 作者:太空宇宙 更新时间:2023-11-03 20:25:13 24 4
gpt4 key购买 nike

10 4

0 0 0 0

0 0 1 0

1 0 2 0

2 2 0 1

0 0 1 1

0 1 2 1

1 1 1 1

1 2 2 0

0 0 1 0

2 0 1 0

我想读取上面的文本文件,并将其存储为 xlsx 格式。但使用我的代码,整行存储在同一个单元格中。但我希望他们在不同的牢房里。每个项目都以空格分隔。

import pandas as pd

df=pd.read_csv('input.txt')

df.to_excel('test2.xls',index=False)

预期结果:每个项目存储在不同的单元格中。

请注意,第一行只有 2 个元素。

最佳答案

您需要将分隔符指定为空格而不是逗号。

import pandas as pd

df = pd.read_csv("input.txt", header=None, delim_whitespace=True, names=['a','b','c','d'])

df.to_excel('test2.xls',index=False, header=None)

请注意,我使用 delim_whitespace=True 告诉 pandas 使用空格而不是逗号。另外,由于第一行中只有 2 个元素,因此我将这些列命名为让 pandas 知道您需要 4 列。

关于python - 在python中将文本文件转换为.xlsx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57878375/

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