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

2024-10-01 11:27:30 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,我在两个不同的列中有纬度和经度。我得到一个新的坐标集的两个元素列表(可能是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语句来告诉我是否已经存在具有该纬度和经度的行。在伪代码中:

^{pr2}$

{{cd2>应该是

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

提前谢谢你!在


Tags: 数据innumpy元素df列表数组long
2条回答

你可以这样做:

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

以下行将返回找到的行数:

^{pr2}$

或者使用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.

相关问题 更多 >