How can I add a new column to dataframe that has the same name as values in another column?
My dataframe is:
import pandas as pd
df = pd.DataFrame({
'Col1': [2, 74, 37, 36, 95],
'Col2': [36, 80, 9, 26, 16],
'Col3': [20, 4, 7, 55, 91],
'Col4': ['Col2','Col2','Col2','Col2','Col2']
})
So I need to add new column ‘Col0’ with values from column ‘Col2’ because it’s name is the same as values in Col4.
The result I want is:
df = pd.DataFrame({
'Col1': [2, 74, 37, 36, 95],
'Col2': [36, 80, 9, 26, 16],
'Col3': [20, 4, 7, 55, 91],
'Col4': ['Col2','Col2','Col2','Col2','Col2'],
'Col0': [36, 80, 9, 26, 16]
})
>Solution :
Try:
df["Col0"] = df.apply(lambda row: row[row["Col4"]], axis=1)
print(df)
Prints:
Col1 Col2 Col3 Col4 Col0
0 2 36 20 Col2 36
1 74 80 4 Col2 80
2 37 9 7 Col2 9
3 36 26 55 Col2 26
4 95 16 91 Col2 16