Python 通过使用 python 在 2 个 DataFrame 中设置条件(范围)来合并键

标签 python pandas merge

我想合并(使用 how = 'left'),而 dataframe_A 位于左侧,data_frame_B 位于右侧。要加入的列/索引级别名称为“名称”、“重量”和“金钱”。高度和重量差异最多允许 2 厘米。
我没有使用 for 循环,因为我的数据集太大,需要 2 天才能完成


例如

INPUT

dataframe_A name:John, height: 170, weight :70
dataframe_B name:John, height 172, weight :69

输出

output_dataframe : name:John,height: 170, weight :70, money:100, grade :1

我有两个数据框:

dataframe_A = pd.DataFrame({'name': ['John', 'May', 'Jane', 'Sally'],
                            'height': [170, 180, 160, 155],
                            'weight': [70, 88, 60, 65],
                            'money': [100, 1120, 2000, 3000]})

dataframe_B = pd.DataFrame({'name': ['John', 'May', 'Jane', 'Sally'],
                            'height': [172, 180, 160, 155],
                            'weight': [69, 88, 60, 65],
                            'grade': [1, 2, 3, 4]})

在选择语句时应该是,

    SELECT * FROM dataframe_A LEFT JOIN dataframe_B 
ON dataframe_A.name= dataframe_B.name and 
dataframe_A.height => dataframe_B.height+2 or
dataframe_A.height <= dataframe_B.height-2 and
dataframe_A.weight=> dataframe_B.weight+2 or
dataframe_A.weight<= dataframe_B.weight-2 
;

但是我不确定如何将它放入 python 中,因为我还在学习

output_dataframe =pd.merge(dataframe_A,dataframe_B,how='left',on=['name','height','weight'] + ***the range condition***

最佳答案

使用merge首先,然后按boolean indexing过滤与 Series.between :

df = pd.merge(dataframe_A, dataframe_B, on='name', how='left', suffixes=('','_'))
m1 = df['height'].between(df['height_'] - 2, df['height_'] + 2)
m2 = df['weight'].between(df['weight_'] - 2, df['weight_'] + 2)

df = df.loc[m1 & m2, dataframe_A.columns.tolist() + ['grade']]
print (df)
    name  height  weight  money  grade
0   John     170      70    100      1
1    May     180      88   1120      2
2   Jane     160      60   2000      3
3  Sally     155      65   3000      4

关于Python 通过使用 python 在 2 个 DataFrame 中设置条件(范围)来合并键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58639870/

相关文章:

python - 转换数组列表

python - Wand Python 多尺寸图标

python - 改进具有多行的交互式 Altair 折线图的选项

python - 如何在pandas中groupby之后压缩行

merge - 如何在开发服务器上动态插入控制台日志

python - 属性错误: 'Action' object has no attribute 'text1'

python - 如何重命名 Tensorflow 中操作的输入张量名称?

Python pandas - 使用应用函数并在数据框中创建新列

sorting - Lua中的合并函数

android - list 合并因多个错误而失败,请参阅日志(unity3d、Android Studio 3.2)