使用字典灵活选择 pandas 数据框行 [英] Flexibly select pandas dataframe rows using dictionary
问题描述
假设我具有以下数据框:
Suppose I have the following dataframe:
df = pd.DataFrame({'color':['red', 'green', 'blue'], 'brand':['Ford','fiat', 'opel'], 'year':[2016,2016,2017]})
brand color year
0 Ford red 2016
1 fiat green 2016
2 opel blue 2017
我知道要使用多个列进行选择,我可以执行以下操作:
I know that to select using multiple columns I can do something like:
new_df = df[(df['color']=='red')&(df['year']==2016)]
现在我想做的是找到一种使用字典来选择我想要的行的方法,其中字典的键代表映射到允许值的列.例如,在df上应用以下字典{'color':'red', 'year':2016}
将产生与new_df相同的结果.
Now what I would like to do is find a way to use a dictionary to select the rows I want where the keys of the dictionary represent the columns mapping to the allowed values. For example applying the following dictionary {'color':'red', 'year':2016}
on df would yield the same result as new_df.
我已经可以使用for循环来做到这一点,但我想知道是否有任何更快和/或更多的 pythonic 方式!
I can already do it with a for loop, but I'd like to know if there are any faster and/or more 'pythonic' ways of doing it!
请附上方法花费的时间.
Please include time taken of method.
推荐答案
使用单个表达式:
In [728]: df = pd.DataFrame({'color':['red', 'green', 'blue'], 'brand':['Ford','fiat', 'opel'], 'year':[2016,2016,2017]})
In [729]: d = {'color':'red', 'year':2016}
In [730]: df.loc[np.all(df[list(d)] == pd.Series(d), axis=1)]
Out[730]:
brand color year
0 Ford red 2016
这篇关于使用字典灵活选择 pandas 数据框行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!