簡體   English   中英

如何根據 Pandas DataFrame 中的條件添加每組具有重復值的新列?

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

這是一個示例數據幀。

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

RootProduct == ProductRootProduct分組時,如何添加第四列,重復Value列中的Value

這將導致以下 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

想法是通過兩列比較boolean indexingSeries.eq然后創建Series的指數與ProductDataFrame.set_index ,因此可能使用Series.mapRootProduct

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM