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:
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