Removing Duplicate Dataframes In A List
Solution 1:
I am doing with numpy.unique
_,idx=np.unique(np.array([x.values for x in all_df_list]),axis=0,return_index=True)
desired_list=[all_df_list[x] for x in idx ]
desired_list
Out[829]:
[ ID Year Score
0120177713201762, ID Year Score
0120188012201870]
Solution 2:
We can use pandas DataFrame.equals
with list comprehension
in combination with enumerate
to compare the items in the list between each other:
desired_list= [all_df_list[x] forx, _inenumerate(all_df_list)ifall_df_list[x].equals(all_df_list[x-1])isFalse]
print(desired_list)
[ IDYearScore012018 80122018 70, IDYearScore012017 77132017 62]
DataFrame.equals
returns True
if the compared dataframes are equal:
df1.equals(df1)
True
df1.equals(df2)
False
Note
As Wen-Ben noted in the comments. Your list should be sorted like [df1, df1, df1, df2, df2, df2]
. Or with more df's: [df1, df1, df2, df2, df3, df3]
Solution 3:
My first thought was to use a set, but dataframes are mutable and thus not hashable. Do you still need individual dataframes in your list, or is it useful to merge all of these into a single dataframe with all unique values?
You can pd.merge()
them all into a single dataframe with unique values using reduce
from functools
:
from functools import reduce
reduced_df = reduce(lambda left, right: pd.merge(left, right, on=None, how='outer'),
all_df_list)
print(reduced_df)
# ID Year Score# 0 1 2018 80# 1 2 2018 70# 2 1 2017 77# 3 3 2017 62
Solution 4:
There's a new Python library pyoccur
to do this easily.
from pyoccur import pyoccur
pyoccur.remove_dup(all_df_list)
Output:
012018 80122018 70,IDYearScore012017 77132017 62]
Solution 5:
You just need to pass the list of duplicate df's
to pd.Series
and drop duplicate and convert it back to list
In [229]: desired_list = pd.Series(all_df_list).drop_duplicates().tolist()
In [230]: desired_list
Out[230]:
[ ID Year Score
0120188012201870, ID Year Score
0120177713201762]
The final desired_list
hold 2 dataframe equal to df1
, df2
In [231]: desired_list[0] == df1
Out[231]:
ID Year Score
0TrueTrueTrue1TrueTrueTrueIn [232]: desired_list[1] == df2
Out[232]:
ID Year Score
0TrueTrueTrue1TrueTrueTrue
Post a Comment for "Removing Duplicate Dataframes In A List"