如何检查两个列的值组合是否在pandas数据框中存在

1 投票
1 回答
5087 浏览
提问于 2025-04-18 08:23

我有两个数据框,其中有两个列是标题和章节。我要检查一个数据框中的特定标题和章节组合是否在另一个数据框中存在。

比如,数据框 torange 有标题、s_low、s_high 以及其他列;而 usc 有标题和章节这两列。

如果在 torange 中有以下一行:

title   s_low   s_high
  1        1      17

那么代码需要在 usc 中检查是否有一行:

title   section
 1        1

以及另一行:

title   section
 1          17

存在;并且创建一个新表格,把标题、章节和 torange 中的其他列写进去,同时在 usc 中扩展 s_low 和 s_high 之间的范围。

我写了下面的代码,但不知怎么的,它在运行几次后就不工作了/停止了。我怀疑可能是计数器 'i' 有问题,可能是语法错误。另外,也可能和 any() 的语法有关。

import MySQLdb as db
from pandas import DataFrame
from pandas.io.sql import frame_query
cnxn = db.connect('127.0.0.1','xxxxx','xxxxx','xxxxxxx', charset='utf8', use_unicode=True )
torange = frame_query("SELECT title, s_low, s_high, post, pre, noy, rnum from torange", cnxn)
usc = frame_query("SELECT title, section from usc", cnxn)

i=0
for row in torange:
    t =  torange.title[i]
    s_low = torange.s_low[i]
    s_high = torange.s_high[i]
    for row in usc:
        if (any(usc.title == t) & any(usc.section == s_low)):
            print 't', t, 's_low' , s_low,'i', i
            if (any(usc.title == t) & any(usc.section == s_high)):
                print 't', t, 's_high', s_high, 'i',i
                print i, '*******************match************************'
    i=i+1

(请忽略打印语句。这是我正在做的一个更大任务的一部分,打印只是用来检查发生了什么。)

如果能在这方面提供帮助,我将非常感激。

1 个回答

1

你的检查和循环逻辑有点混乱。你在 usc 中循环 row,但是你的 any() 条件却是在检查 usc,而不是 row。而且,row 是你两个循环的迭代器。下面是一个更清晰的起点:

for index, row in torange.iterrows(): 
    t = row['title']
    s_low = row['s_low']
    s_high = row['s_high']
    uscrow = usc[(usc.title == t) & (usc.section == slow)]
    # uscrow now contains all the rows in usc that fulfill your condition.

撰写回答