在python中读取以空格分隔的变量表

2024-10-01 05:00:07 发布

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

现在,我试图读取一个表,它有一个可变的空格分隔符,同时也有缺失的/空白的值。我想阅读python中的表并生成一个CSV文件。我尝试过NumPy、Pandas和CSV库,但不幸的是,变量空间和丢失的数据一起让我几乎无法阅读表。我试图阅读的文件附在这里: goo.gl/z7S2Mo型在

This is how the table looks like

如果有人能帮我用python解决方案,我将不胜感激


Tags: 文件csv数据numpypandas空间解决方案空白
2条回答

numpy模块有一个函数可以实现这一点(见最后一行):

import numpy as np

path = "<insert file path here>/infotable.txt"

# read off column locations from a text editor.
# I used Notepad++ to do that.
column_locations = np.array([1, 38, 52, 61, 70, 78, 98, 111, 120, 127, 132])

# My text editor starts counting at 1, while numpy starts at 0. Fixing that:
column_locations = column_locations - 1

# Get column widths
widths = column_locations[1:] - column_locations[:-1]

data = np.genfromtxt(path, dtype=None, delimiter=widths, autostrip=True)

根据具体的用例,您可以使用不同的方法来获得列宽,但是您得到了这个想法。dtype=None确保numpy为您确定数据类型;这与省略dtype参数非常不同。最后,autostrip=True去掉前导空格和尾随空格。在

输出(data)是structured array。在

您需要分隔符为两个或更多个空格(而不是一个或多个空格)。这里有一个解决方案:

import pandas as pd
df = pd.read_csv('infotable.txt',sep='\s{2,}',header=None,engine='python',thousands=',')

结果:

^{2}$

相关问题 更多 >