简体   繁体   中英

Pandas how to add the counters for matching rows between two dataframe columns

I have two dataframes, where I would like to add the another counter column for matching rows between these dataframes rows.

df1:

Id   val1  val2   val3
0     ab     ba     sx
1     bc     dc     xy
2.    ab     ba     ux

df2:

Id   val1  val2   val3
0     ab     ba      zx
1     bc     dc      vy

Expected result: df3:

Id   val1  val2   val3  counter
0     ab     ba     sx       1
1     bc     dc     xy      1
2.    ab     ba     ux      2

I want here to match the val1 and val2 column and add the counter in df3 for matched rows between these dataframes df1 and df2 .

Any help will be much appreciated.

不清楚您要输出什么,但这可能会帮助您:

dfa = df1.groupby(['val1', 'val2'], as_index = false).size().rename(columns{0,'counter'}

First find the matched rows via an inner merge, then use groupby + cumcount to add a counter:

res = df1.merge(df2.drop(['Id', 'val3'], 1), on=['val1', 'val2'], how='inner')\
         .sort_values('Id').reset_index(drop=True)

res['Counter'] = res.groupby(['val1', 'val2']).cumcount() + 1

print(res)

   Id val1 val2 val3  Counter
0   0   ab   ba   sx        1
1   1   bc   dc   xy        1
2   2   ab   ba   ux        2

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