Python 使用现有列作为多索引重新索引数据帧
我目前在这个配置中有一个数据帧Python 使用现有列作为多索引重新索引数据帧,python,pandas,dataframe,data-manipulation,Python,Pandas,Dataframe,Data Manipulation,我目前在这个配置中有一个数据帧 col_1 col_2 col_3 col_4 0 fish 50g 3 £5 1 cheese 50g 4 £6 2 fish 100g 2 £20 3 fish 200g 2 £25 4 bread 50g 15 £50 . ... ... ... ...
col_1 col_2 col_3 col_4
0 fish 50g 3 £5
1 cheese 50g 4 £6
2 fish 100g 2 £20
3 fish 200g 2 £25
4 bread 50g 15 £50
. ... ... ... ...
col_3 col_4
fish 50g 3 £5
100g 2 £20
200g 2 £25
cheese 50g 4 £6
bread 50g 15 £50
... ... ... ...
我希望在此配置中有一个数据帧
col_1 col_2 col_3 col_4
0 fish 50g 3 £5
1 cheese 50g 4 £6
2 fish 100g 2 £20
3 fish 200g 2 £25
4 bread 50g 15 £50
. ... ... ... ...
col_3 col_4
fish 50g 3 £5
100g 2 £20
200g 2 £25
cheese 50g 4 £6
bread 50g 15 £50
... ... ... ...
我查看了上的文档,得出了需要使用pd.MultiIndex构造函数的结论
然而,无论我尝试使用什么样的pd.MultiIndex.constructor(df[[“col_1”,“col_2”]])
m_index对象作为pd.DataFrame(df,index=m_index)
我做错了什么?我想您可以使用and then,但为了正确排序,需要从列列2
中删除最后一个字符g
,并转换为int
(或float
)。最后,您可以添加g
并创建新的:
您正在查找
df.set\u索引(['col\u 1','col\u 2'])
?