简体   繁体   English

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

[英]How to rename a pandas DataFrame index based on a column condition

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-values并再次设置索引来完成它:

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? 你知道是否有更简单的方法吗?

How about trying this? 试试这个怎么样?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM