[英]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 == Product
按RootProduct
分組時,如何添加第四列,重復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 indexing
與Series.eq
然后創建Series
的指數與Product
由DataFrame.set_index
,因此可能使用Series.map
柱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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.