0

I have two dataframe as below:

df1 = DataFrame({'a': np.random.randint(10, size=2)})
df2 = DataFrame({'a': np.random.randint(10, size=100)})

There is two numbers in df1, and I want to count the two numbers' amount in df2. The answer is in the right of df1['a'].

I use for in, but there is a error:Length of values does not match length of ' 'index.

Anyone can tell me how to slove this question?

I use df2['a'].isin(df1['a']).sum(), but it give me the result that the amount of two numbers together.

I want the result like:

No  Amount
8   3
1   2

instead of :

No  Amount
8   5
1   5
yuchen huang
  • 257
  • 1
  • 2
  • 10

2 Answers2

2
df2.a.value_counts().reindex(df1.a)
Out[369]: 
a
4    11
5     5
Name: a, dtype: int64

Add sum

df2.a.value_counts().reindex(df1.a).sum()
Out[370]: 16
BENY
  • 317,841
  • 20
  • 164
  • 234
1

If I understand correctly:

In [22]: df2['a'].isin(df1['a']).sum()
Out[22]: 18
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419
  • Thanks for your answer. I use your method, but the result is not correct. The problem is that two amount is same, one is correct but another is not correct and the number is same. – yuchen huang Nov 22 '17 at 00:25