如何在值上比较两个数据帧?

2024-09-28 03:18:03 发布

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

我有两个带有纬度和经度的Pandas数据帧(A&;B)。你知道吗

我需要比较它们,如果来自DF A的纬度和经度出现在DF B中,那么就添加一个1else 0。你知道吗

DF A

 LatLong
-37.3794288,175.6697856
-37.0334148,174.8680204
-41.173852,174.981931

DF B
KBATMLongLat
-37.0334148,174.8680204
-37.5575605,175.1584622
-37.0334148,174.8680204

如何实现预期的输出(见下文)?你知道吗

 Long lat               | Result
--------------------------------
-37.3794288,175.6697856 | False
-37.0334148,174.8680204 | True
-41.173852,174.981931   | False

Tags: 数据falsetruepandasdfresultlongamp
2条回答

这是一种方法:

import pandas as pd

df1 = pd.DataFrame([[-37.3794288,175.6697856],
                    [-37.0334148,174.8680204],
                    [-41.173852,174.981931]],
                   columns=['Long', 'Lat'])

df2 = pd.DataFrame([[-37.0334148,174.8680204],
                    [-37.5575605,175.1584622],
                    [-37.0334148,174.8680204]],
                   columns=['Long', 'Lat'])


df1['Result'] = [tuple(i) in set(map(tuple, df2.values)) for i in df1.values]

#         Long         Lat  Result
# 0 -37.379429  175.669786   False
# 1 -37.033415  174.868020    True
# 2 -41.173852  174.981931   False

或者,更泛化:

df = pd.merge(df1, df2, indicator=True, how='left').\
              drop_duplicates().rename(columns={'_merge': 'Result'})

df['Result'] = df['Result'].map({'left_only': False, 'both': True})

我不确定这有多有效,但你可以使用多索引

df1 = df1.set_index(["Long","Lat"])
df2 = df2.set_index(["Long","Lat"])
df1["Result"] = df1.index.isin(df2.index)
df1 = df1.reset_index()
df1


    Long        Lat         Result
0   -37.379429  175.669786  False
1   -37.033415  174.868020  True
2   -41.173852  174.981931  False

相关问题 更多 >

    热门问题