Kspr
Kspr

Reputation: 685

How do I add a new column with a repeated value per group based on condition in a Pandas DataFrame?

This is an example DataFrame.

RootProduct | Product | Value
    A           A        1  
    A           B        2   
    A           C        3
    D           D        4
    D           E        5  

How can I add a fourth column, repeating the value present in the Value column when RootProduct == Product grouped by RootProduct?

This would result in the following DataFrame

RootProduct | Product | Value  | RootValue
    A           A        1          1
    A           B        2          1
    A           C        3          1 
    D           D        4          4 
    D           E        5          4

Upvotes: 2

Views: 60

Answers (1)

jezrael
jezrael

Reputation: 863331

Idea is compare both columns by boolean indexing with Series.eq and then create Series by index with Product by DataFrame.set_index, so possible use Series.map by column RootProduct:

s = df[df['RootProduct'].eq(df['Product'])].set_index('Product')['Value']
df['RootValue'] = df['RootProduct'].map(s)
print (df)
  RootProduct Product  Value  RootValue
0           A       A      1          1
1           A       B      2          1
2           A       C      3          1
3           D       D      4          4
4           D       E      5          4

Detail of Series:

print (s)
Product
A    1
D    4
Name: Value, dtype: int64

Upvotes: 4

Related Questions