gpt4 book ai didi

python - 使用 Pandas 读取文本文件时格式化列

转载 作者:行者123 更新时间:2023-12-04 07:21:39 25 4
gpt4 key购买 nike

我要读固定宽度文件.txt 像这样使用 Pandas :

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
我试图将文件读入 Pandas 。该文件具有由空格分隔的值
但我不知道如何分隔文本 选项199716751810 分成 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.有人可以帮助得到这个plz

最佳答案

我建议你使用 str.slice()方法(假设 df 是您的数据框,而 option_column 包含您的选项字符串):

df['col A'] = df['option_column'].str.slice(stop=12)
df['col B'] = df['option_column'].str.slice(start=12)

关于python - 使用 Pandas 读取文本文件时格式化列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68453104/

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