使用现有列作为多索引重新索引数据框

时间:2016-04-20 17:56:28

标签: python pandas dataframe data-manipulation

我目前在此配置中有一个pandas数据框

some-file-2.54.jar

我想在此配置中有一个数据框

    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
.   ...      ...     ...     ...

我查看了the pandas website处的文档,我得出的结论是我需要使用pd.MultiIndex构造函数。

但是,无论我尝试使用 col_3 col_4 fish 50g 3 £5 100g 2 £20 200g 2 £25 cheese 50g 4 £6 bread 50g 15 £50 ... ... ... ... 的哪种变体,我都不会得到pd.MultiIndex.constructor(df[["col_1","col_2"]])对象,当我尝试将其用作m_index

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我认为您可以使用set_index然后使用sort_index,但为了正确排序,必须从g列删除最后一个字符col_2并按astype投弃到int(或float)。最后,您可以添加g并创建新的MultiIndex from_tuples

df['col_2'] = df['col_2'].str[:-1].astype(int)

print df.set_index(['col_1','col_2'])
              col_3  col_4
col_1  col_2              
fish   50         3      5
cheese 50         4      6
fish   100        2     20
       200        2     25
bread  50        15     50

print df.set_index(['col_1','col_2'])
        .sort_index(level=['col_1','col_2'], ascending=[False,True])

              col_3  col_4
col_1  col_2              
fish   50         3      5
       100        2     20
       200        2     25
cheese 50         4      6
bread  50        15     50
df1 = df.set_index(['col_1','col_2'])
        .sort_index(level=['col_1','col_2'], ascending=[False,True])

              col_3  col_4
col_1  col_2              
fish   50         3      5
cheese 50         4      6
fish   100        2     20
       200        2     25
bread  50        15     50

#change multiindex
new_index = zip(df1.index.get_level_values('col_1'),
                df1.index.get_level_values('col_2').astype(str) + 'g')
df1.index = pd.MultiIndex.from_tuples(new_index, names = df1.index.names)
print df1
              col_3  col_4
col_1  col_2              
fish   50g        3      5
       100g       2     20
       200g       2     25
cheese 50g        4      6
bread  50g       15     50
相关问题