I have pandas df where I need to replace column name with value from row based on condition only for some columns.
parameter.1.value| parameter.1.name | parameter.2.value |parameter.2.name ....
1 | abc | 4 |xyz
2 | abc | 3 |xyz
3 | abc | 6 |xyz
Goal
abc | xyz
1 | 4
2 | 3
3 | 6
Note:
There are other columns as well in df, also the number and location of the parameter value-name columns pair are not always same in each df
Another example with 3 pairs
parameter.1.value| parameter.1.name | parameter.2.value |parameter.2.name| parameter.3.value |parameter.3.name ....
1 | abc | 4 |xyz |2 | ttt
2 | abc | 3 |xyz |8 | ttt
3 | abc | 6 |xyz |7 | ttt
CodePudding user response:
You can select all even columns by positions and then set new columns names by odd values in first row of DataFrame:
df1 = df.iloc[:, ::2]
df1.columns = df.iloc[0, 1::2]
print (df1)
0 abc xyz
0 1 4
1 2 3
2 3 6
EDIT: If need select by names:
df1 = df.filter(like='parameter.value1')
df1.columns = df.filter(like='parameter.name1').iloc[0]
print (df1)
0 abc xyz
0 1 4
1 2 3
2 3 6
EDIT1: If is possible select value and name columns use:
df1 = df.filter(like='value')
df1.columns = df.filter(like='name').iloc[0]
