比较2个数据帧值

2024-05-14 13:44:46 发布

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

如何比较第一个数据帧和第二个数据帧中列名称的黑名单值?你知道吗

我想从df2返回与黑名单值匹配的行。你知道吗



df1

column_name blacklist_value
  test90.v_6           931
  test90.v_7           912

以及

df2
test90.sno test90.v_1 test90.v_2 test90.v_3 test90.v_4 test90.v_5  \
0          0    7.52785        100       22.2       47.8         13   
1          1    7.43006        100       22.2       47.8       12.9   
2          2    7.40669        100       22.2       47.8         13   
3          3    7.52365        100       22.2       47.9         13   
4          4    7.43734        100       22.3       47.6       13.3   

 test90.v_6 test90.v_7 test90.v_8 test90.v_9 test90.label  
0        925        951        938        954            0  
1        931        953        935        950            0  
2        932        952        937        950            0  
3        923        950        942        950            0  
4        920        952        945        954            0  

我希望结果返回与df1的黑名单值匹配的df2数据帧。你知道吗


Tags: 数据name名称valuecolumnlabeldf1df2
1条回答
网友
1楼 · 发布于 2024-05-14 13:44:46

如果要将黑名单应用于某个特定列,它将如下所示:

df2[df2['V_1'].isin(list(df1['Blacklist']))]

如果要将其应用于所有列,它将如下所示:

df2[df2.isin(list(df1['Blacklist'])).any(axis='columns')]

您可以使用以下数据进行测试:

df1 = pd.DataFrame({
'Blacklist': [931, 912, 950]
})

df2 = pd.DataFrame({
'V_1': [925, 931, 932, 923, 920],
'V_7': [951, 953, 952, 950, 952]
})

如果您只需要将其应用于其中一列,还可以使用merge或join with how='left',并从黑名单df中选择您的联接列不为na的行(df[~df[join\u column].isna()),但我认为这样更容易。你知道吗

相关问题 更多 >

    热门问题