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?
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.
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.
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.
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.
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)])]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With