【发布时间】:2021-08-22 11:56:39
【问题描述】:
我有一个文本文件,其中有很多行,每行有 6 列,但在每第四列和每 6 列之后都有一个 \n,类似于:
第 1 行 ---> 1 2 3 4\n 5 6\n
第 2 行 ---> 7 8 9 10\n 11 12\n
我正在使用命令从文件中创建数据框:
df = pd.read_csv('info.txt', header=None, delimiter=r"\s+", names = cols, lineterminator='\n')
但是,即使我在 read_csv 的 names 属性中明确提供了 6 列的名称,pandas read_csv 也会将上述数据读取为 4 行:
col1 col2 col3 col4 col5 col6
0 1 2 3 4 NaN NaN
1 5 6 NaN NaN NaN NaN
2 7 8 9 10 NaN NaN
3 11 12 NaN NaN NaN NaN
如何读取数据:
col1 col2 col3 col4 col5 col6
0 1 2 3 4 5 6
1 7 8 9 10 11 12
【问题讨论】:
-
文件中的行终止符是什么?我的意思是
1 2 3 4\n 5 6\n末尾的符号?你有一个 windows/mac 行尾(\r,\r\n)吗? -
我在文本文件上做了一个 open('info.txt','r+b').read() ,我可以看到数字数据和模式中写入的 \n 字符,例如: 61 4 2 242\n 392 4\n ,所以行终止符应该是 \n 但它连续出现两次因此产生了问题。第二个 \n 之后没有其他区别符号,新行值以相同模式从第二个 \n 之后开始。
-
你可能有一个非 unix 行尾(不是
\n)。否则你会得到61 4 2 242和392 4作为单独的行。您可以尝试使用 stackoverflow.com/questions/3569997/… 找到行尾 -
我跑了
file info.txt,它给出了info.txt: ASCII text的响应,当我查看文件时,它显示61 4 2 242和392 4作为单独的行。所以看起来 \n 只是行分隔符,但它没有与数据对齐。 -
你在用macos吗?对我来说,只有一行
1 2 3 4\n 5 6\n听起来是不可能的,而您的编辑器将其显示为单独的行,而 open() 将其显示为单独的行。您可以执行以下操作:在二进制查看器中检查换行符,例如cat info.txt | od -c | less。我相信你有一个macos换行符(\r),你可以试试pd.read_csv(..., lineterminator='\r')