简体   繁体   中英

How to merge two rows and divide values of chosen columns into new column

I have a such a problem I'm not even sure what to type in google - if you have any suggestions or perhaps problem is trivial, sorry about that, I'm still getting there.

I have pandas dataframe of dtypes:

id    | string
title | string
a     | int
b     | int

Example values:

id    |title    |a     |b
id1   |title1   |0     |2
id1   |title1   |1     |0
id1   |title1   |0     |1

What I wish to do is to merge those two rows for id1 in such a way that I will have new column c where c=a/b, so

id    |title    |c  
id1   |title1   |1/3

First aggregate sum by GroupBy.sum and then divide columns:

df = df.groupby(['id','title'], as_index=False).sum()
df['c'] = df.a / df.b
print (df)
    id   title  a  b      c
0  id1  title1  1  3  0.333

With remove a and b columns use DataFrame.pop :

df = df.groupby(['id','title'], as_index=False).sum()
df['c'] = df.pop('a') / df.pop('b')
print (df)
    id   title      c
0  id1  title1  0.333
df=pd.DataFrame([['id','title',1,2],['id1','title1',3,4]], columns=['id', 'title','a','b'])

df
_______________________
    id   title  a  b
0   id   title  1  2
1  id1  title1  3  4


df['c']=df['a'].values/df['b'].values

df
__________________________
    id   title  a  b     c
0   id   title  1  2  0.50
1  id1  title1  3  4  0.75


df.drop(['a','b'], axis=1, inplace=True)

df
_________________________
    id   title       c
0   id   title    0.50
1  id1  title1    0.75

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM