繁体   English   中英

在熊猫中读取具有多个制表符和空格分隔值的txt文件

[英]read txt file with multiple tab & space separated values in pandas

我想使用这样的熊猫读取固定宽度的file.txt

option19971675181       ACHILLE BLA BLA BLA1                                 blabla    88   498
option19971675182       ACHILLE BLA BLA BLA1                                  blabla   176   498
option19971675183       ACHILLE BLA BLA BLA1                                  blabla   191   498
option19971675184       ACHILLE BLA BLA BLA1                                  blabla   521   498
option19971675185       ACHILLE BLA BLA BLA1                                  blabla   919   498
option19971675186       ACHILLE BLA BLA BLA134234531                          blabla    10    498
option19971675187       ACHILLE BLA BLA BLA134234531 7 65                     blabla     0     0
option19971675188       ACHILLE BLA BLA BLA1342 90345 31                      blabla     0     0
option19971675189      ACHILLE BLA BLA BLA 134 23N 094 87OP531                blabla     0     0
option19971675190       ACHILLE BLA BLA BLA 134 23N 094 87OP53                blabla     0     0

我试图将文件读入熊猫。 该文件具有由空格分隔的值

但我不知道如何将文本option199716751810分成 2 列。

我使用了它工作的答案中的代码,但不适用于第一行

 df = pd.read_csv("test.txt", delimiter ="\s\s+", header = None,error_bad_lines=False)
df[df.columns[0]] = df[df.columns[0]].str.replace("option199716","")

>>> df

我得到了这个输出

75181       ACHILLE BLA BLA BLA1                                 blabla    88   498
75182       ACHILLE BLA BLA BLA1                                  blabla   176   498
75183       ACHILLE BLA BLA BLA1                                  blabla   191   498
75184       ACHILLE BLA BLA BLA1                                  blabla   521   498
75185       ACHILLE BLA BLA BLA1                                  blabla   919   498
75186       ACHILLE BLA BLA BLA134234531                          blabla    10    498
75187       ACHILLE BLA BLA BLA134234531 7 65                     blabla     0     0
75188       ACHILLE BLA BLA BLA1342 90345 31                      blabla     0     0
75189      ACHILLE BLA BLA BLA 134 23N 094 87OP531                blabla     0     0
75190       ACHILLE BLA BLA BLA 134 23N 094 87OP53                blabla     0     0

但它仍然显示错误: Skipping line 16: Expected 5 fields in line 136, saw 6. Error could possibly be due to quotes being ignored when a multi-char delimiter is used. 有人可以帮忙得到这个吗?

假设您的文本文件与您的问题完全相同,请尝试以下操作:

df = pd.read_csv("test.txt", delimiter ="\s\s+")
df[df.columns[0]] = df[df.columns[0]].str.replace("option199716","")

>>> df
        0        1         2   3   4
0  751810   Pascal      Male  23  11
1  845087  Achille      Male  13  12
2  602183     Hera  Femelles   9  98
3  802183     Alma  Femelles  19  88

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM