'Swap column names with row values in a pandas DataFrame
I am kind of stucked in a pretty simple task - at least what I thought.
Suppose you have a DataFrame with following shape (So the data frame is given)
df = pd.DataFrame({"col a": [0, 1, 2, 3, "name a"],
"col b": [0, 1, 2, 3, "name b"],
"col c": [0, 1, 2, 3, "name c"]})
col a col b col c
0 0 0 0
1 1 1 1
2 2 2 2
3 3 3 3
4 name a name b name c
If I use the following command
df.columns=df.iloc[4]
the original header disappears. Any suggestion how to achieve my goal. Of course if it would be one sheet I could do it manually, however I have multiple sheets and this need to automatize it
Any kind of support is really appreciated The result should be that way
name name name
0 0 0 0
1 1 1 1
2 2 2 2
3 3 3 3
4 col a col b col c
Solution 1:[1]
Like in any case where you want to swap 2 values in a program, you need to use an intermediate variable.
You can let python do that for you by taking advantage of the A, B = B, A syntax:
df.columns, df.iloc[4] = df.iloc[4].to_list(), df.columns
output:
name a name b name c
0 0 0 0
1 1 1 1
2 2 2 2
3 3 3 3
4 col a col b col c
ignoring first columns in the swap:
df = df.set_index(['col a', 'col b'])
df.columns, df.iloc[4] = df.iloc[4].to_list(), df.columns
df = df.reset_index()
output:
col a col b name c
0 0 0 0
1 1 1 1
2 2 2 2
3 3 3 3
4 name a name b col c
Solution 2:[2]
It's important to use the .rename method from Pandas instead of just assigning new column names
df = pd.DataFrame({"col a": [0, 1, 2, 3, "name"]})
col_name = df.columns.to_list()[0]
var_name = df.iloc[4].values[0]
df = df.rename(columns={col_name: var_name})
df.iloc[4, :] = col_name
result:
name
0 0
1 1
2 2
3 3
4 col a
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | igrolvr |
