python - Merging two DataFrame with different number of rows -


how can merge below 2 dataframes different number of rows have 1 common column in pandas?

dataframe1:

cname   pname   col1    col2 a1      xx1     34      22 a2      xx2     23      44 a1      xx3     11      12 a2      xx4     23      43 a1      xx5     42      76 a3      xx6     15      56 a4      xx7     33      45 a5      xx8     223     87 a5      xx9     12      56 a5      xx10    87      34 a5      xx11    6       23 a4      xx12    55      33 

dataframe2:

cname   read    unread a1      12      43 a2      24      78 a3      1       65 a4      2       16 a5      5       6 

so resultant dataframe must below:

cname   pname   col1    col2    sumofreadandunread a1      xx1     34      22      55 a2      xx2     23      44      102 a1      xx3     11      12      55 a2      xx4     23      43      102 a1      xx5     42      76      55 a3      xx6     15      56      66 a4      xx7     33      45      18 a5      xx8     223     87      11 a5      xx9     12      56      11 a5      xx10    87      34      11 a5      xx11    6       23      11 a4      xx12    55      33      18 

sum read , unread columns in df2, join df1.

>>> df1.join(df2.set_index('cname').sum(axis=1).to_frame('sumofreadandunread'), on='cname')    cname pname  col1  col2  sumofreadandunread 0     a1   xx1    34    22   55 1     a2   xx2    23    44  102 2     a1   xx3    11    12   55 3     a2   xx4    23    43  102 4     a1   xx5    42    76   55 5     a3   xx6    15    56   66 6     a4   xx7    33    45   18 7     a5   xx8   223    87   11 8     a5   xx9    12    56   11 9     a5  xx10    87    34   11 10    a5  xx11     6    23   11 11    a4  xx12    55    33   18 

Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -