简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM