Home > Mobile >  Remove zeros from Dataframe of lists
Remove zeros from Dataframe of lists

Time:05-07

I have such a DataFrame:

index B
0 [0,1,2,0,4]
1 [1,0,2,0,0,1,7]

I want to count the non zero values of each list for each row. Result

index B
0 3
1 4

Thank you!

CodePudding user response:

def count_nonzero_elements_of_list(x):
    return len([x if x != 0])

df['B'].apply(count_nonzero_elements_of_list)

CodePudding user response:

By using numpy's count_nonzero method:

import numpy as np

df['B'] = [np.count_nonzero(x) for x in df['B'].tolist()]

CodePudding user response:

using numpy :

df['C'] = df.B.apply(np.count_nonzero)

output:

>>>
                       B  C
0        [0, 1, 2, 0, 4]  3
1  [1, 0, 2, 0, 0, 1, 7]  4
  • Related