如何根据数据帧中的条件,为每个组添加一个重复值的新列?

2024-09-30 22:22:31 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个示例数据帧

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

RootProduct == ProductRootProduct分组时,如何添加第四列,重复Value列中的值

这将导致以下数据帧

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

Tags: 数据示例valueproductrootvaluerootproduct
1条回答
网友
1楼 · 发布于 2024-09-30 22:22:31

想法是通过^{}^{}比较两列,然后通过Product^{}索引创建Series,因此可以通过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

有关Series的详细信息:

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

相关问题 更多 >