mardi 13 octobre 2020

COUNTIFS in Python Pandas

I am trying to workout a countifs function in Python pandas using the following data frame.


import pandas as pd

df = pd.DataFrame({'var_1': ['B 1','B 2','B 3','B 4','B 5','B 6','B 7','B 4','B 8','B 1','B 3','B 9','B 7','B 6','B 4','B 2','B 4','B 4','B 3','B 7','B 7','B 7','B 9','B 4','B 3','B 1','B 2','B 4','B 4','B 2','B 1','B 3','B 9','B 4','B 2','B 4','B 9','B 1','B 10','B 4','B 3','B 8','B 4','B 3','B 2','B 1','B 4','B 7','B 4','B 3','B 1','B 2','B 8','B 11','B 4','B 2','B 7','B 4','B 7','B 3','B 1','B 4','B 9','B 1','B 3','B 4','B 2','B 4','B 2','B 3','B 1','B 4','B 4','B 7','B 4','B 2','B 8','B 1','B 3','B 6','B 2','B 4','B 5','B 1','B 4','B 7','B 4','B 2','B 1','B 4','B 2','B 8','B 9','B 4','B 2','B 3','B 1','B 4','B 12','B 1'],'var_2': ['B 1','B 2','B 3','B 4','B 5','B 6','B 7','B 4','B 8','B 1','B 3','B 9','B 7','B 6','B 4','B 2','B 4','B 4','B 3','B 7','B 7','B 7','B 9','B 4','B 3','B 1','B 2','B 4','B 4','B 2','B 1','B 3','B 9','B 4','B 2','B 4','B 9','B 1','B 10','B 4','B 3','B 8','B 4','B 3','B 2','B 1','B 4','B 7','B 4','B 3','B 1','B 2','B 8','B 11','B 4','B 2','B 7','B 4','B 7','B 3','B 6','B 4','B 9','B 6','B 3','B 4','B 2','B 4','B 2','B 3','B 6','B 4','B 4','B 7','B 4','B 2','B 8','B 1','B 3','B 6','B 2','B 4','B 5','B 1','B 4','B 7','B 4','B 2','B 1','B 4','B 2','B 8','B 9','B 4','B 2','B 3','B 1','B 4','B 12','B 1']})

  • Lets assume I have got two variables with 100 responses of different brands
  • I have got un-duplicated list of var 1 and var 2
  • I am creating following new columns,
  • Column 1 - in how many rows this brand is there is var 1 BUT NOT IN var 2
  • Column 2 - in how many rows this brand is there is var 2 BUT NOT IN var 1
  • Column 3 - in how many rows this brand is there is var 1 AND ALSO var 2
  • Column 4 - Total rows - Column 1 + Column 2 + Column 3

Format of the Output i required is:

(First two rows are conditions only. Required the output from row 3)

enter image description here

Aucun commentaire:

Enregistrer un commentaire