我花了很多时间试图找到这个问题的答案,我觉得应该直截了当。
什么是相当于SELECT * FROM [TABLE] WHERE [COL1] IN (LIST)
的Pandas?
基本上,我有一个很大的ID号数据集,我想从这些客户中选择一个子集。我想要整个数据帧的值。我尝试使用.isin()
,但我不想要布尔值。有没有一种简单的方法可以使用另一个Dataframe列/系列/列表/元组(随便什么(来选择另一个数据帧中的行?
例如,我有两个表/DataFrames:
让我们调用第一个表cust_info:
cust_id | 元数据1 |
---|---|
1234 | y |
5678 | x |
4321 | x |
2468 | y |
9513 | x |
1473 | y |
列出客户ID,其中cust_info['metadata1'] == 'y'
:
valids = cust_info.loc[cust_info['metadata1'] == 'y', 'cust_id']
然后询问ID是否在有效ID列表中:
cust_orders[cust_orders['custid'].isin(valids)]
尝试:
x = cust_info[cust_info["metadata1"].eq("y")].merge(cust_orders, on="cust_id")
print(x)
打印:
cust_id metadata1 order_date order_total
0 1234 y 2021-07-10 15.10
1 2468 y 2021-07-12 50.96
2 1473 y 2021-07-13 75.58
如果只需要cust_orders
:中的列
x = cust_info[cust_info["metadata1"].eq("y")].merge(cust_orders, on="cust_id")
print(x[cust_orders.columns])
cust_id order_date order_total
0 1234 2021-07-10 15.10
1 2468 2021-07-12 50.96
2 1473 2021-07-13 75.58