Hiwot
Hiwot

Reputation: 588

Filtering IDS which has the same elements in a list pandas

I have grouped columns and got the following sample dataframe. After this I would like to filter IDs which has identical elements in a list.

df

ID     Value
1      [0,0,50,0,0]
2      [0,0,0,0,0,0,0]
3      [0,100,0,0,50]
4      [0,0,0,0,0]

I would like to filter IDs which has same elements in a list under Value columns and those elements must be only 0s.

The expected output is just IDs and it should be 2 and 4.

Can anyone help on this?

Upvotes: 1

Views: 34

Answers (1)

jezrael
jezrael

Reputation: 862691

You can compare sets by set([0]):

df1 = df[df['Value'].map(set).eq(set([0]))]
print (df1)
   ID                  Value
1   2  [0, 0, 0, 0, 0, 0, 0]
3   4        [0, 0, 0, 0, 0]

If need filter only same values per list compare lengths in Series.str.len:

df2 = df[df['Value'].map(set).str.len().eq(1)]

Upvotes: 1

Related Questions