1

i would like to ask how can i can iterate through the dataframe and check where the ID is the same value, then sum the prices for these rows.

i tried it with the following code:

d = {'ID': [126, 126, 148, 148, 137, 137], 'price': [100, 50, 120, 40, 160, 30]}

df = pd.DataFrame(data=d)

so the Dataframe looks like this

  ID  price
0 126 100
1 126 50
2 148 120
3 148 40
4 137 160
5 137 30





for index in df.index():
if df.iloc[index, "ID"] == df.iloc[index+1, "ID"]:
    df.at[index, "price"] = df.iloc[index, "price"] + df.iloc[index+1, "price"]
    df.at[index+1, "price"] = df.iloc[index, "price"] + df.iloc[index+1, "price"]

i would like to have a resulst like this:

  ID   price
0 126  150
1 126  150
2 148  160
3 148  160
4 137  190
5 137  190

Please help if you someone knows how to do it. :)

1 Answers1

0

TRY Groupby-Transform:

df['price'] = df.groupby('ID')['price'].transform('sum')

OUTPUT:

    ID  price
0  126    150
1  126    150
2  148    160
3  148    160
4  137    190
5  137    190
Nk03
  • 14,699
  • 2
  • 8
  • 22