Python 按字典键值对筛选数据帧
是否有一种更优雅的方法可以按一列过滤数据帧,然后按另一列进一步过滤每个子集?结果数据是否在一个数据帧中?过滤信息在字典中。第一个过滤器使用dict键打开Python 按字典键值对筛选数据帧,python,pandas,Python,Pandas,是否有一种更优雅的方法可以按一列过滤数据帧,然后按另一列进一步过滤每个子集?结果数据是否在一个数据帧中?过滤信息在字典中。第一个过滤器使用dict键打开col1。第二个过滤器使用其相应的值打开col3 df=pd.DataFrame({'col1':[1,1,1,2,2],'col2':[2,2,2,2],'col3':[1,6,7,5,9]) df如下所示 | col1 | col2 | col3| |1 |2 |1 | |1 |2 |6 | |1 |2 |7
col1
。第二个过滤器使用其相应的值打开col3
df=pd.DataFrame({'col1':[1,1,1,2,2],'col2':[2,2,2,2],'col3':[1,6,7,5,9])
df
如下所示
| col1 | col2 | col3|
|1 |2 |1 |
|1 |2 |6 |
|1 |2 |7 |
|2 |2 |5 |
|2 |2 |9 |
筛选器_dict={1:5,2:7}
df_new=df.somefunction(filter_dict)
其中col1
为1,过滤器中col3
值大于5。当col1
为2时,按col3
值过滤大于7。这将导致:
df_新
|col1 | col2 | col3|
|1 |2 |6 |
|1 |2 |7 |
|2 |2 |9 |
使用concat列出理解和布尔索引
df_new = pd.concat([df[(df['col1'] == k) & (df['col3'] > v)] for k,v in filter_dict.items()])
col1 col2 col3
1 1 2 6
2 1 2 7
4 2 2 9
用concat实现列表理解和布尔索引
df_new = pd.concat([df[(df['col1'] == k) & (df['col3'] > v)] for k,v in filter_dict.items()])
col1 col2 col3
1 1 2 6
2 1 2 7
4 2 2 9