'Remove zeros from Dataframe of lists
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 |
Solution 1:[1]
def count_nonzero_elements_of_list(x):
return len([x if x != 0])
df['B'].apply(count_nonzero_elements_of_list)
Solution 2:[2]
By using numpy's count_nonzero method:
import numpy as np
df['B'] = [np.count_nonzero(x) for x in df['B'].tolist()]
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mose Wintner |
| Solution 2 | AlI |
| Solution 3 | eshirvana |
