Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count nunique from another dataframe

My goal is to add a column which counts the number of unique instances of a primary key in dfB using the keys in dfA. dfA has the primary key only show up once while dfB would have the primary key multiple times.

Example.

dfA

Agreement Date_1
146108493 1/31/2019
142527722 1/9/2019

dfB

Agreement Date_2
146108493 2/4/2019
146108493 2/15/2019
146108493 2/20/2019
142527722 2/28/2019
142527722 3/15/2019

Goal Outcome- adjusted dfA

Agreement Date_1 Count
146108493 1/31/2019 3
142527722 1/9/2019 2
like image 848
Ethan Avatar asked Jul 26 '26 19:07

Ethan


2 Answers

You can group dataframe dfB on Agreement and aggregate using count then map the values to dfA based on primary key Agreement:

dfA['Count'] = dfA['Agreement'].map(dfB.groupby('Agreement')['Date_2'].count())

Or use value_counts with map as suggested by @Pygirl in comments:

dfA['Count'] = dfA['Agreement'].map(dfB['Agreement'].value_counts())

   Agreement     Date_1  Count
0  146108493  1/31/2019      3
1  142527722   1/9/2019      2
like image 140
Shubham Sharma Avatar answered Jul 28 '26 08:07

Shubham Sharma


Use df.merge:

In [1161]: x = dfA.merge(dfB, indicator='Count').query('Count == "both"').groupby('Agreement').size().reset_index(name='Count')

In [1165]: dfA = dfA.merge(x)

In [1166]: dfA
Out[1166]: 
   Agreement     Date_1  Count
0  146108493  1/31/2019      3
1  142527722   1/9/2019      2
like image 35
Mayank Porwal Avatar answered Jul 28 '26 09:07

Mayank Porwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!