我有一个像这样的文本文件:
test2.dat:
col1 col2
idx1 idx2
a 0 0.256788 0.862771
1 0.409944 0.785159
2 0.822773 0.955309
b 0 0.159213 0.628662
1 0.463844 0.667742
2 0.292325 0.768051它是通过通过DataFrame file.write(df.to_sring)保存一只多索引熊猫而创建的。现在,我想逆转这个行动。但当我尝试
pandas.read_csv(data, sep=r'\s+', index_col=[0, 1])它抛出一个错误ParserError: Error tokenizing data. C error: Expected 2 fields in line 3, saw 4
这是一个小的MWE:
import pandas
import numpy as np
from itertools import product
df1 = pandas.DataFrame(product(['a', 'b'], range(3)), columns=['idx1', 'idx2'])
df2 = pandas.DataFrame(np.random.rand(6, 2), columns=['col1', 'col2'])
df = pandas.concat([df1, df2], axis=1)
df.set_index(['idx1','idx2'], inplace=True)
df.to_csv('test.dat', sep=' ')
with open('test2.dat', 'w') as file:
file.write(df.to_string())请注意,与test.dat相比,通过pandas.to_csv()保存的pandas.to_csv()几乎不能算作“人类可读性”。
test.dat:
idx1 idx2 col1 col2
a 0 0.2567883353169065 0.862770538437793
a 1 0.40994403619942743 0.7851591115509821
a 2 0.8227727216889246 0.9553088749178045
b 0 0.1592133339255788 0.6286622783546136
b 1 0.4638439474864856 0.6677423709343185
b 2 0.2923252978245071 0.7680513714069206发布于 2019-03-06 13:59:15
使用read_fwf并通过列表理解设置列名:
df = pd.read_fwf('file.csv', header=[0,1])
df.columns = [y for x in df.columns for y in x if not 'Unnamed' in y]
#replace missing values by first column
df.iloc[:, 0] = df.iloc[:, 0].ffill().astype(int)
#set first 2 columns to MultiIndex
df = df.set_index(df.columns[:2].tolist())
print (df)
col1 col2
idx1 idx2
1 1 0.1234 0.2345
2 0.4567 0.2345
3 0.1244 0.5332
2 1 0.4213 0.5233
2 0.5423 0.5423
3 0.5235 0.6233发布于 2019-03-07 18:23:01
我决定使用jezrael代码的细微变化,它会自动处理索引的数量。注意,df.columns具有最初的表单[(x1,y1), (x2,y2), ..., (xn, yn)],其中n是列数,xi是第一个标题行中的列i的标签,yi是第二个标题行中的一个。
df = pandas.read_fwf(f, header=[0,1])
cols = [x for x,_ in df.columns if 'Unnamed' not in x]
idxs = [y for _,y in df.columns if 'Unnamed' not in y]
df.columns = idxs + cols
df[idxs] = df[idxs].ffill()
df.set_index(idxs, inplace=True)https://stackoverflow.com/questions/55023981
复制相似问题