Sum the values of specific rows if the rows have same values in specific column

2024/11/15 13:43:05

I have a data frame like this:

    a   b   c
12456   11  123.1
12678   19  345.67
13278   19  1235.345

or in another format

<table><tr><td>12456</td><td>11</td><td>123.1</td></tr><tr><td>12678</td><td>19</td><td>345.67</td></tr><tr><td>13278</td><td>19</td><td>1235.345</td></tr>
</table>

The first column is the index.I need to add the rows of third column and make it one if second column has same value. Could you suggest me something to do this? Following is what I have tried but doesnt work

    a,b,c=df_addweight.iloc[:,0].values,df_addweight.iloc[:, 1].values,df_addweight.iloc[:, 3].values`for u,v,w, in zip(range(1,len(a)),range(1,len(b)),range(1,len(c))):if a[u]==a[u-1] and b[v]==b[v-1]:df_addweight['W']= c[w]+c[w-1]elif a[u]==a[u-1] and b[v]!=b[v-1]:df_addweight['W']=c[w]
Answer

Use pandas:

import pandas as pddf = pd.read_csv("data.csv", delim_whitespace=True)dfa   b         c
0  12456  11   123.100
1  12678  19   345.670
2  13278  19  1235.345df.groupby('b')['c'].sum()

Output:

b
11     123.100
19    1581.015
Name: c, dtype: float64
https://en.xdnf.cn/q/119306.html

Related Q&A

Plotting Interpolated 3D Data As A 2D Image using Matplotlib

The data set is made of a list dfList containing pandas DataFrames, each DataFrame consisting of the column Y and an identical index column. I am trying to plot all the DataFrames as a 2D plot with pix…

Plotting a flow duration curve for a range of several timeseries in Python

Flow duration curves are a common way in hydrology (and other fields) to visualize timeseries. They allow an easy assessment of the high and low values in a timeseries and how often certain values are …

HTML variable value is not changing in Flask

I have written this code in Flaskans = 999 @app.route(/, methods=[POST, GET]) def home():flag = 0global anssession["ans"] = 0if (request.method == "POST"):jsdata = request.form[data…

How to add two lists with the same amount of indexs in python

I am still new to coding so i apologize for the basic question. How do I add to elements of two seperate lists? listOne = [0, 1 , 7, 8] listTwo = [3, 4, 5, 6] listThree = []for i in listOne:listAdd = …

How to crawl thousands of pages using scrapy?

Im looking at crawling thousands of pages and need a solution. Every site has its own html code - they are all unique sites. No clean datafeed or API is available. Im hoping to load the captured data i…

Object Transmission in Python using Pickle [duplicate]

This question already has answers here:Send and receive objects through sockets in Python(3 answers)Closed last year.I have the following class, a Point objectclass Point:def __init__(self):passdef __i…

Google App Engine: Modifying 1000 entities

I have about 1000 user account entities like this:class UserAccount(ndb.Model):email = ndb.StringProperty()Some of these email values contain uppercase letters like [email protected]. I want to select …

more efficient method of dealing with large numbers in Python? [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

MLM downline distribution count

I make my first MLM software and I think I managed to code how to get the points from the downline even though it is a recursive problem I didnt use recursion and I might refactor to a recursive versio…

Can someone please explain to me the purpose of the asterisk in Python? [duplicate]

This question already has answers here:What does asterisk * mean in Python? [duplicate](5 answers)How are pythons unpacking operators * and ** used?(1 answer)Closed 5 years ago.For instance, can some…