如何根据列条件重命名熊猫DataFrame索引

时间:2021-06-03 10:32:24

I have a DataFrame like this:

我有一个这样的DataFrame:

import pandas as pd
df = pd.DataFrame(data= {"x": [1,2,3,4],"y":[5,6,7,8],"i":["a.0","a.1","a.0","a.1"]}).set_index("i")
df

Out:

:

     x  y
i        
a.0  1  5
a.1  2  6
a.0  3  7
a.1  4  8

and I want to rename the index based on a column condition:

我想根据列条件重命名索引:

df.loc[df["y"]>6].rename(index=lambda x: x+ ">6" )

what gives me:

给我什么:

       x  y
i    
a.0>6  3  7
a.1>6  4  8

I tried it with inplace=True, but it does not work

我用inplace=True试过了,但是没用

df.loc[df["y"]>6].rename(index=lambda x: x+ ">6" , inplace=True )

I only could get it done by resetting the index, changing the i-column-values via apply and set the index again:

我只能通过重新设置索引、通过apply更改I -column值并再次设置索引来完成:

df1 = df.reset_index()
df1.loc[df1["y"]>6, "i"] = df1.loc[df1["y"]>6, "i"].apply(lambda x: x+ ">6" )
df1.set_index("i", inplace=True)
df1

Out:

:

       x  y
i    
a.0    1  5
a.1    2  6
a.0>6  3  7
a.1>6  4  8

But this is so complicated. Do you know if there is an easier way?

但这太复杂了。你知道有没有更简单的方法吗?

1 个解决方案

#1


3  

How about trying this?

在这个怎么样?

import numpy as np
df.index=np.where(df['y']>6, df.index+'>6', df.index)

#1


3  

How about trying this?

在这个怎么样?

import numpy as np
df.index=np.where(df['y']>6, df.index+'>6', df.index)