繁体   English   中英

检查一对值是否在 pandas 中的一对列中

[英]check if pair of values is in pair of columns in pandas

基本上,我在两个不同的列中有纬度和经度(在网格上)。 我收到了一个新坐标集的双元素列表(可能是 numpy 数组),我想在添加之前检查它是否重复。

比如我的数据:

df = pd.DataFrame([[4,8, 'wolf', 'Predator', 10],
              [5,6,'cow', 'Prey', 10],
              [8, 2, 'rabbit', 'Prey', 10],
              [5, 3, 'rabbit', 'Prey', 10],
              [3, 2, 'cow', 'Prey', 10],
              [7, 5, 'rabbit', 'Prey', 10]],
              columns = ['lat', 'long', 'name', 'kingdom', 'energy'])

newcoords1 = [4,4]
newcoords2 = [7,5]

是否可以写一个if语句来告诉我是否已经有具有该纬度和经度的行。 在伪代码中:

if newcoords1 in df['lat', 'long']:
    print('yes! ' + str(newcoords1))

(在这个例子中, newcoords1应该是falsenewcoords2应该是true

旁注: (newcoords1[0] in df['lat']) & (newcoords1[1] in df['long'])不起作用,因为它会独立检查它们,但我需要知道该组合是否出现在单行。

先感谢您!

你可以这样做:

In [140]: df.query('@newcoords2[0] == lat and @newcoords2[1] == long')
Out[140]:
   lat  long    name kingdom  energy
5    7     5  rabbit    Prey      10

In [146]: df.query('@newcoords2[0] == lat and @newcoords2[1] == long').empty
Out[146]: False

以下行将返回一些找到的行:

In [147]: df.query('@newcoords2[0] == lat and @newcoords2[1] == long').shape[0]
Out[147]: 1

或使用 NumPy 方法:

In [103]: df[(df[['lat','long']].values == newcoords2).all(axis=1)]
Out[103]:
   lat  long    name kingdom  energy
5    7     5  rabbit    Prey      10

这将显示是否至少找到一行:

In [113]: (df[['lat','long']].values == newcoords2).all(axis=1).any()
Out[113]: True

In [114]: (df[['lat','long']].values == newcoords1).all(axis=1).any()
Out[114]: False

说明:

In [104]: df[['lat','long']].values == newcoords2
Out[104]:
array([[False, False],
       [False, False],
       [False, False],
       [False, False],
       [False, False],
       [ True,  True]], dtype=bool)

In [105]: (df[['lat','long']].values == newcoords2).all(axis=1)
Out[105]: array([False, False, False, False, False,  True], dtype=bool)
x, y = newcoords1

>>> df[(df.lat == x) & (df.long == y)].empty
True  # Coordinates are not in the dataframe, so you can add it.

x, y = newcoords2

>>> df[(df.lat == x) & (df.long == y)].empty
False  # Coordinates already exist.

对于像我这样通过搜索如何检查大数据框中的一对列中是否有几对值来这里的人,这里有一个答案。

让一个列表newscoord = [newscoord1, newscoord2, ...]并且您想提取与此列表元素匹配的df行。 那么对于上面的例子:

v = pd.Series( [ str(i) + str(j) for i,j in df[['lat', 'long']].values ] )
w = [ str(i) + str(j) for i,j in newscoord ]

df[ v.isin(w) ]

它提供与@MaxU 相同的输出,但它允许一次提取多行。

在我的电脑上,对于 10,000 行的df ,运行需要 0.04 秒。

当然,如果您的元素已经是字符串,那么使用join而不是串联会更简单。

此外,如果对中元素的顺序无关紧要,则必须先排序:

v = pd.Series( [ str(i) + str(j) for i,j in np.sort( df[['lat','long']] ) ] )
w = [ str(i) + str(j) for i,j in np.sort( newscoord ) ]

需要注意的是,如果v没有被转换成一个系列并且使用np.isin(v,w) ,或者 i w被转换成一个系列,那么当newscoord达到数千个元素时,它将需要更多的运行时间。

希望它有帮助。

如果您尝试一次检查多对,您可以将 DataFrame 的列和值放入 MultiIndexes 并使用Index.isin 我相信这比将它们连接成字符串更干净:

df = pd.DataFrame([[4,8, 'wolf', 'Predator', 10],
          [5,6,'cow', 'Prey', 10],
          [8, 2, 'rabbit', 'Prey', 10],
          [5, 3, 'rabbit', 'Prey', 10],
          [3, 2, 'cow', 'Prey', 10],
          [7, 5, 'rabbit', 'Prey', 10]],
          columns = ['lat', 'long', 'name', 'kingdom', 'energy'])

new_coords = pd.MultiIndex.from_tuples([(4,4), (7,5)])
existing_coords = pd.MultiIndex.from_frame(df[["lat", "long"]])
~new_coords.isin(existing_coords)
>>> array([ True, False])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM