hemant c naik
hemant c naik

Reputation: 93

Change column name with matching string from list

Hello i have one pandas datafrmae and a list

my data frame

xy_123        ba_322         ab_321      zx_223

  1            1                1           1 

  s2           f32             r32          s223

list= [ "xy_123_8.4", "ba_322_9.5", "ab_321_8.4", "zx_223_9.5"]

output i am looking at

xy_123_8.4        ba_322_9.5        ab_321_8.4     zx_223_9.5

       1            1                1           1 

       s2           f32             r32          s223

I have large dataframe want to change column name is there any posibility do from python pandas

Upvotes: 1

Views: 337

Answers (2)

jezrael
jezrael

Reputation: 863216

Use rename by dictionary:

L =  [ "xy_123_8.4", "ba_322_9.5", "ab_321_8.4", "zx_223_9.5"]

d = {x.rsplit('_', 1)[0]:x for x in L}

df = df.rename(columns=d)
print (df)
  xy_123_8.4 ba_322_9.5 ab_321_8.4 zx_223_9.5
0          1          1          1          1
1         s2        f32        r32       s223

Upvotes: 1

Aravinth
Aravinth

Reputation: 18

I recommend not to use list as a variable name. in your case

df.columns = list

Upvotes: 0

Related Questions