Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas new column based on value from another column

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading