2

I have a dataframe with column names: df1

A_01 A_02 B_03 C_04
 0    0    0    1
 1    2    1    0
 0    1    0    3

also, df2:

no. value
01  1103
02  1105
03  1210
04  1306

How to rename df1 columns with the value on df2 like as:

1103 1105 1210 1306
 0    0    0    1
 1    2    1    0
 0    1    0    3
harvpan
  • 8,571
  • 2
  • 18
  • 36
  • `df1.columns = df2['value'].values` – Michael Gardner Sep 30 '19 at 17:36
  • Have you searched how to rename columns in pandas? There is a DataFrame.rename specific function you can check out [here](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename.html?highlight=rename#pandas.DataFrame.rename). Have you checked documentation on how to slice or get values of a pandas data frame? There is also available documentation on that [here](https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html) – MikeMajara Sep 30 '19 at 17:36
  • Possible duplicate of [Renaming columns in pandas](https://stackoverflow.com/questions/11346283/renaming-columns-in-pandas) – MikeMajara Sep 30 '19 at 17:37

1 Answers1

2

You need:

df1.columns = df1.columns.str.split('_').str[1].map(df2.set_index('no.')['value'])

Output:

    1103    1105    1210    1306
0   0         0      0         1
1   1         2      1         0
2   0         1      0         3
harvpan
  • 8,571
  • 2
  • 18
  • 36
  • Thanks,, it's working now, but if I change the value as like, `110325`. So, I got the error: AttributeError: Can only use .str accessor with string values (i.e. inferred_type is 'string', 'unicode' or 'mixed') – naura tsalits Oct 01 '19 at 07:02
  • You have to make them string. – harvpan Oct 01 '19 at 14:13