读取检测为一列的文件

2024-04-19 01:11:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个表格中的数字文件

010101228522 0 31010 3 7 7 43 0 2 4 2 2 3 20.00 89165.30

01010222852313 0 0 7 31027 63 5 2 0 3 2 4 12 40.10 94170.20

010103228524233723237 710153 9 22 9 9 3 4 80.52 88164.20

0101042285252313302330302323197 9 5 15 9 15 9 110.63 98168.80

01010522852617 7 3 7 31330 87 6 3 2 3 2 5 15 50.211110 170.50

我正在尝试读取这个文件,但是我不知道如何使用它,当我使用NoMPY中的内置函数打开和Load Txt时,我甚至尝试转换为大熊猫,但是该文件被读取为一列,即它的形状是(364×1),但我希望它将数字分隔为列,空白空间用0代替,任何帮助都将不胜感激。注意,有些地方有两个空格紧随其后


Tags: 文件函数txt地方空间load数字内置
2条回答

如果列内容类型是字符串,您是否尝试使用str.split()这会将字符串转换为数组,然后将每个数字按每个间隙分割。然后,您可以使用for循环来计算所提到的数组中的对象数量,从而从中创建一个表,但不太确定这是否回答了问题,如果没有,很抱歉

str.split():

因此,我最终解决了我的问题,我实际上必须剥离行,然后读取行中的每个“字母”,在我的例子中,我从剥离行中选取单个数字,然后将它们附加到一个数组中。这是我的解决方案的代码

arr = [] 
with open('Kp2001', 'r') as f:
    for ii, line in enumerate(f):  
         arr.append([])     #Creates an n-d array
         cnt = line.strip() #Strip the lines
         for letter in cnt:  #Get each 'letter' from the line, in my case it's the individual numbers
              arr[ii].append(letter)   #Append them individually so python does not read them as one string

df = pd.DataFrame(arr)    #Then converting to DataFrame gives proper columns and actually keeps the spaces to their respectful columns
df2 = df.replace(' ', 0)      #Replace the spaces with what you will

相关问题 更多 >