Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas set_levels, how to avoid sorting of labels?

I came across a problem using set_levels of multi index

from io import StringIO

txt = '''Name,Height,Age
"",Metres,""
A,-1,25
B,95,-1'''

df = pd.read_csv(StringIO(txt),header=[0,1],na_values=['-1',''])

df.columns = df.columns.set_levels(df.columns.get_level_values(level=1).str.replace('Un.*',''),level=1)

     Name Height   Age
   Metres             
0      A    NaN  25.0
1      B   95.0   NaN

If I run the same command again

df.columns = df.columns.set_levels(df.columns.get_level_values(level=1).str.replace('Un.*',''),level=1)

  Name Height   Age
       Metres      
0    A    NaN  25.0
1    B   95.0   NaN

Now this is yielding the expected result. Why is this behaviour so? Is it possible to keep the labels unsorted at the first try itself ?

like image 482
Bharath Avatar asked Oct 27 '25 07:10

Bharath


1 Answers

Sounds like you need , This will modify base on your original structure

df.rename(columns=lambda x : '' if 'Unnamed' in x else x , level=1)
Out[106]: 
  Name Height   Age
       Metres      
0    A    NaN  25.0
1    B   95.0   NaN
like image 100
BENY Avatar answered Oct 28 '25 20:10

BENY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!