Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

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

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]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use pandas:

import pandas as pd

df = pd.read_csv("data.csv", delim_whitespace=True)

df
       a   b         c
0  12456  11   123.100
1  12678  19   345.670
2  13278  19  1235.345


df.groupby('b')['c'].sum()

Output:

b
11     123.100
19    1581.015
Name: c, dtype: float64

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...