Leoli
Leoli

Reputation: 749

Select rows from a DataFrame based on list values in a column in pandas

I am new to pandas and I have a simple dataframe and want to extract certain rows based on a column. However, the type in this column is a list.

Example:

df = pd.DataFrame([['text1', [1,2,3]], ['text2', [2,3,4]]], columns=['text','list_value'])

The data frame looks like:

    text    list_value
0   text1   [1, 2, 3]
1   text2   [2, 3, 4]

I tried

df.loc[df['list_value'] == [1,2,3]]

And it returns an error :

ValueError: Arrays were different lengths: 2 vs 3

I wonder if there is any better solution than using for loop to iterate the dataframe.

Similar question but the solution is not work for me: Select rows from a DataFrame based on values in a column in pandas.

Upvotes: 3

Views: 2761

Answers (1)

BENY
BENY

Reputation: 323226

You can adding apply tuple, when there is list in a cell , pandas sometime return the wired result

df.loc[df['list_value'].apply(tuple) == tuple([1,2,3])]
Out[58]: 
    text list_value
0  text1  [1, 2, 3]

Upvotes: 3

Related Questions