Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: compare list objects in Series

Tags:

python

pandas

In my dataframe a column is made up of lists, for example:

df = pd.DataFrame({'A':[[1,2],[2,4],[3,1]]})

I need to find out the location of list [1,2] in this dataframe. I tried:

df.loc[df['A'] == [1,2]]

and

df.loc[df['A'] == [[1,2]]]

but failed totally. The comparison seems very simple but that just doesn't work. Am I missing something here?

like image 292
Shiang Hoo Avatar asked Nov 01 '18 13:11

Shiang Hoo


People also ask

How do I compare Series values in Pandas?

Algorithm. Step 1: Define two Pandas series, s1 and s2. Step 2: Compare the series using compare() function in the Pandas series. Step 3: Print their difference.

How would you compare the elements of two panda Series?

Compare two Series objects of the same length and return a Series where each element is True if the element in each Series is equal, False otherwise. Compare two DataFrame objects of the same shape and return a DataFrame where each element is True if the respective element in each DataFrame is equal, False otherwise.

How do I compare objects in Pandas?

Pandas DataFrame: equals() function The equals() function is used to test whether two objects contain the same elements. This function allows two Series or DataFrames to be compared against each other to see if they have the same shape and elements. NaNs in the same location are considered equal.

How do you compare elements in a list?

Using sum() ,zip() and len() This method first compares each element of the two lists and store those as summation of 1, which is then compared with the length of the other list. For this method, we have to first check if the lengths of both the lists are equal before performing this computation.


1 Answers

Do not use list in cell, it creates a lot of problem for pandas. If you do need an object column, using tuple:

df.A.map(tuple).isin([(1,2)])
Out[293]: 
0     True
1    False
2    False
Name: A, dtype: bool
#df[df.A.map(tuple).isin([(1,2)])]
like image 67
BENY Avatar answered Sep 20 '22 06:09

BENY