Reputation: 941
I need help with adding 2 rows together for a specific match. Given df:
ID Name1 Name2 Value
1 xy a 1
1 yz b 2
1 zz c 3
2 xy a 4
2 yz b 5
3 zz c 6
Result: Value of (Name1 =yz,Name2=b) = Value of (Name1 =yz,Name2=b) + Value of (Name1 =xy,Name2=a)
ID Name1 Name2 Value
1 xy a 1
1 yz b 3 (2+1)
1 zz c 3
2 xy a 4
2 yz b 9 (5+4)
3 zz c 6
I believe we need to group them by id first then do the addition. I usually use np.where to operate on columns but not sure how it works for rows in this case.
Many thanks!
Upvotes: 0
Views: 60
Reputation: 311
I suggest you add a new column:
df["new_column"] = np.where(df["Name1"] == "yz", df["Value"] + df["Value"].shift(-1),0)
If you want the current value in df["Value"] if the condition isn't met, then just do the following:
df["new_column"] = np.where(df["Name1"] == "yz", df["Value"] + df["Value"].shift(-1),df["Value"])
Upvotes: 1