How to select value for certain condition with pandas Series containing dtype list?

Viewed 525

I actually know many ways to do this in Pandas Dataframe and Series with dtype like float, But how can I make it work with Series containing dtype list?

For example, I want to :

series = pd.Series([[1,2],[2,3,4],[4,6]])

series is like:

0    [1, 2]
1    [2, 3, 4]
2    [4, 6]
dtype: object

I want to have rows with it's length longer than 2, which is actually row 1. I tried:

series[len(series) > 2]

and

series[series.apply(lambda x : len(x) > 1)]

Both are not working.

2 Answers

List columns support .str accessor methods since they are essentially objects. Try

series[series.str.len() > 2]
 
1    [2, 3, 4]
dtype: object

If index values of rows that satisfy the condition are needed, we filter on the index instead:

series.index[series.str.len() > 2]
# Int64Index([1], dtype='int64')

Alternatively, if you want to remove rows that are greater than 2 in length, you can use boolean indexing to filter:

series[series.str.len() <= 2]

0    [1, 2]
2    [4, 6]
dtype: object

Note that your first solution didn't make sense since the condition is scalar, but your apply code would've worked with len(x) > 2 unless your column also has NaNs, which the .str solution handles gracefully.

enter image description here Series are mostly used in str because accessor methods. That is the reason str are using in Series

series[series.apply(lambda x :len(x) > 2)][enter image description here][1]
Related