[英]select rows in pandas DataFrame using comparisons against two columns
I have a pandas dataframe: 我有一个熊猫数据框:
df = pd.DataFrame({'one' : [1, 2, 3, 4] ,'two' : [5, 6, 7, 8]})
one two
0 1 5
1 2 6
2 3 7
3 4 8
Column "one" and column "two" together comprise (x,y) coordinates 列“一”和列“二”共同构成(x,y)坐标
Lets say I have a list of coordinates: c = [(1,5), (2,6), (20,5)]
可以说我有一个坐标列表:
c = [(1,5), (2,6), (20,5)]
Is there an elegant way of obtaining the rows in df
with matching coordinates? 是否有一种优雅的方法来获取
df
具有匹配坐标的行? In this case, given c
, the matching rows would be 0 and 1 在这种情况下,给定
c
,匹配的行将为0和1
Related question: Using pandas to select rows using two different columns from dataframe? 相关问题: 使用pandas从数据框中使用两个不同的列来选择行?
And: Selecting rows from pandas DataFrame using two columns 并且: 使用两列从pandas DataFrame中选择行
This approaching using pd.merge
should perform better than the iterative solutions. 这种使用
pd.merge
方法应比迭代解决方案更好。
import pandas as pd
df = pd.DataFrame({"one" : [1, 2, 3, 4] ,"two" : [5, 6, 7, 8]})
c = [(1, 5), (2, 6), (20, 5)]
df2 = pd.DataFrame(c, columns=["one", "two"])
pd.merge(df, df2, on=["one", "two"], how="inner")
one two
0 1 5
1 2 6
You can use 您可以使用
>>> set.union(*(set(df.index[(df.one == i) & (df.two == j)]) for i, j in c))
{0, 1}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.