count occurrence of value over a range in Pandas

Viewed 116

I have a dataframe that looks like this:

simple = pd.DataFrame([
    (80,100 ),
    (100,90 ),
    (80, 90 ),
], columns=['content_x', 'content_y'])

    content_x   content_y
0   80          100
1   100         90
2   80          90

I'd want to count the occurrences of values in content_x over the content_y column. (In Excel, I use a countif)

The final output would look like this:

enter image description here

5 Answers

You can try via isin():

simple['count of X in Y']=simple['content_y'].isin(simple['content_x']).astype(int)
#OR(via view())
simple['count of X in Y']=simple['content_y'].isin(simple['content_x']).view('i1')

output of simple:

  content_x     content_y   count of X in Y
0   80          100             1
1   100         90              0
2   80          90              0

IIUC, here's one way ->

Just do the value_count() and map the result:

simple['count'] = simple.content_x.map(simple.content_y.value_counts()).fillna(0, downcast= 'infer')

OUTPUT FOR YOUR SAMPLE INPUT:

   content_x  content_y  count
0         80        100      0
1        100         90      1
2         80         90      0

Another sample INPUT:

   content_x  content_y
0         80        100
1        100         90
2         80        100

OUTPUT:

   content_x  content_y  count
0         80        100      0
1        100         90      2
2         80        100      0

Similar to Anurag's answer, but I think you are looking for grand total per number per row? You use groupby and transform to get that:

import pandas as pd
simple = pd.DataFrame([
    (80,100 ),
    (100,90 ),
    (80, 90 ),
], columns=['content_x', 'content_y'])
simple['count'] = simple['content_y'].isin(simple['content_x'])
simple['count'] = simple.groupby('content_y')['count'].transform('sum')
simple
Out[1]: 
   content_x  content_y  count
0         80        100      1
1        100         90      0
2         80         90      0

Lets use

np.in1d to intersect the column arrays

simple['count of X in Y']=np.in1d(simple['content_y'].values,simple['content_x'].values).astype(int)



     content_x  content_y  count of X in Y
0         80        100                1
1        100         90                0
2         80         90                0

For each row in content_x sum all the occurrences in content_y. This is easy to do, because you can just sum a boolean filter. Then just add that to a list, and make it all a new dataframe column after the loop. I'm sure there are other methods, but this one is fairly straight forward.

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'x' : [80, 100, 80],
    'y' : [100, 90, 90],
})

x_in_y = []
for i in range(len(df)):
    x_in_y.append( sum(df.y == df.x[i]) )

df['x_in_y'] = x_in_y

enter image description here

Related