kms
kms

Reputation: 2024

Remove 0 from a pandas series containing lists

I have a pandas DataFrame with a series that stores data as lists.

import pandas as pd

df = pd.DataFrame({
                   'id': [0, 1],
                   'vl': [ [1, 0, 2], [0, 1, 5] ]
                 })

For lists containing 0, I'd like to remove 0s from the lists.

Expected output:

id   vl 

0    [1, 2]
1    [1, 5]

Upvotes: 0

Views: 43

Answers (1)

Corralien
Corralien

Reputation: 120519

Explode your column then filter your values:

df['vl'] = df['vl'].explode().loc[lambda x: x != 0].groupby(level=0).agg(list)
print(df)

# Output
   id      vl
0   0  [1, 2]
1   1  [1, 5]

Alternative:

df['vl'] = df['vl'].apply(lambda x: [i for i in x if i != 0])
print(df)

# Output
   id      vl
0   0  [1, 2]
1   1  [1, 5]

Upvotes: 3

Related Questions