Search code examples
pythonarrayspreprocessor

getting value count of a an array element respective to each row with python


input data this is my input data from each array i need its respective count ,if it is not present then 0 will be

   ID                     array
0  20  [1, 2, 1, 1, 2, 3, 4, 5]
1  34     [1, 2, 2, 3, 4, 6, 7]
2  55        [6, 8, 9, 2, 1, 6]
3  66        [3, 4, 7, 7, 8, 1]

output

    ID        array              1  2   3   4   5   6   7   8  9
0   20  [1, 2, 1, 1, 2, 3, 4, 5] 3  2   1   1   1   0   0   0  0
1   34  [1, 2, 2, 3, 4, 6, 7]    1  2   1   1   0   1   1   0  0
2   55  [6, 8, 9, 2, 1, 6]  1    1  1   0   0   0   1   0   1  1 
3   66  [3, 4, 7, 7, 8, 1]  1    0  0   1   1   0   0   2   1  0

Solution

  • IIUC, here's one way via pandas:

    df1 = df.explode('array')
    df = pd.crosstab(df1['ID'], df1['array'])