Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering a column of lists of strings in a Pandas DataFrame

df=pd.DataFrame({'sym':['A', 'B', 'C', 'D'],'event':[['1','2', '3'], ['1'], ['2', '3'],['2']]} )

df

    sym event
0   A   [1, 2, 3]
1   B   [1]
2   C   [2, 3]
3   D   [2]

Event column is made up of lists of strings. I am trying to filter the event column for any rows that contain '3' so I am looking for index 0 and 2.

I know to use

["3" in df.event[0]]

for each row and I think a lambda function would push me over the finish line.

like image 377
wlbsr Avatar asked Nov 24 '25 15:11

wlbsr


1 Answers

Please try:

print(df[df.event.astype(str).str.contains(r'\b3\b')])



sym      event
0   A  [1, 2, 3]
2   C     [2, 3]
like image 195
wwnde Avatar answered Nov 27 '25 04:11

wwnde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!