pandas - pandas 读取多索引数据帧(反向 to_string() )
问题描述
我有一个如下所示的文本文件:
测试2.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
它是通过保存多索引 pandas 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()
与test2.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
解决方案
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
推荐阅读
- python - 在 QTreeView 的 QSortFilterProxyModel 中显示来自 filterAcceptsRow() 的已接受子代但不显示父代
- javascript - 同一行上两种不同形式的按钮
- android - 如何在 Android Studio 中的 Navigation Graph 上切换片段方向
- javascript - 带有接受声明函数的 then 方法的打字稿编码样式
- firebase - 我将我的 Firebase 规则更改为所有经过身份验证的用户。我需要在请求中更改什么 (Flutter)
- java - 如何从列表中删除重复记录并用枚举标记它?
- javascript - 科尔多瓦 div 溢出滚动导致整个屏幕滚动
- owl - 在 Protege 5 中,什么最能减慢推理者的速度?
- java - 将 application.properties 与非 bean 类一起使用
- laravel - 预处理控制器方法的模型类型提示路由参数中的主键