-1

This is my initial dataframe dfA :

idA data
1 row
2 data
3 data

dataframe dfB

idC idA
1 1
2 1
3 3
4 3
5 3
6 3

I am trying to count every id existence of dfA in dfB , and add to new column like this:

idA data count
1 row 2
2 data 0
3 data 4

how can i do this plz

Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52
4212
  • 111
  • 7

1 Answers1

2

Use groupby then count to get the count of idC in each group idA. At last, map the count Series to idA column of df1.

df1['count'] = df1['idA'].map(df2.groupby('idA')['idC'].count()).fillna(0).astype(int)
print(df1)

   idA  data  count
0    1   row    2
1    2  data    0
2    3  data    4
Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52