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

Add column to display the value of each unique column value, repeated for all instances of that value in Pandas

In pandas, I would like to add a new column which displays the value for an elements type, repeated for all instances of that element (couldn’t figure out a better way to describe this).

For example, in the below, there is a Type called "La". I want to create a new column called "La". In the case of element "A", for each record, the value 9 should show under the LA column. For "B", it would be 2.

My Data:

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

Element     Type  Value
A           Ex     5
A           La     9
A           Bd     0
B           La     2 
B           Ex     7 
B           Ex     3

What I want:

Element     Type  Value  La
A           Ex     5     9
A           La     9     9
A           Bd     0     9
B           La     2     2
B           Ex     7     2
B           Ex     3     2

EDIT: For the value I’m looking at (La), there won’t ever be duplicates. Just one per element.

>Solution :

For only "La" and assuming there are no duplicates, filter and map:

df['La'] = df['Element'].map(df.loc[df['Type'].eq('La')]
                               .set_index('Element')['Value']
                             )

Output:

  Element Type  Value  La
0       A   Ex      5   9
1       A   La      9   9
2       A   Bd      0   9
3       B   La      2   2
4       B   Ex      7   2
5       B   Ex      3   2

If you want all Elements, use a pivot_table and merge (here keeping the max value in case of duplicates, but you can aggregate with any function):

df.merge(df.pivot_table(index='Element', columns='Type', values='Value',
                        aggfunc='max', fill_value=-1).reset_index(),
         on='Element', how='left')

Output:

  Element Type  Value  Bd  Ex  La
0       A   Ex      5   0   5   9
1       A   La      9   0   5   9
2       A   Bd      0   0   5   9
3       B   La      2  -1   7   2
4       B   Ex      7  -1   7   2
5       B   Ex      3  -1   7   2
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