Skip to content Skip to sidebar Skip to footer

Select Data Frame By Dict Passing In Parameters Or Comprehension List Python Pandas

I want to select rows in a dataframe passing a dict or a comprehension list. I have a data frame with millions rows, I want to create a function to select just a part of this data

Solution 1:

You can use dict for filtering with DataFrame.all for check all True values per row for mask and filter by boolean indexing.
Also is necessary convert all values of DataFrame to strings by astype, because all values of dict are strings too:

d = {'Brand':'FORD', 'Model':'MUSTANG', 'Bodycar':'Coupé', 'Liter':'3.7', 'Power':'317'}

print (df.astype(str)[list(d)] == pd.Series(d))
   Bodycar  Brand  Liter  Model  Power
0     True   True  False   True  False
1     True   True  False   True  False
2     True   True  False   True  False
3     True   True  False   True  False
4     True   True   True   True   True
6     True   True  False   True  False

mask = (df.astype(str)[list(d)] == pd.Series(d)).all(axis=1)
print (mask)
0    False
1    False
2    False
3    False
4     True
6    False
dtype: bool

df1 = df[mask]
print (df1)
    AGE       KM Brand    Model  Liter Bodycar  Power
4  16.0  20700.0  FORD  MUSTANG    3.7   Coupé    317

Post a Comment for "Select Data Frame By Dict Passing In Parameters Or Comprehension List Python Pandas"