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

2024-10-02 12:30:39 发布

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

我有两个数据帧。Title和section是另外两列。 我需要检查第二个数据帧中特定标题和节的组合是否存在。在

例如,数据帧torange具有列标题、s_低、s_高和其他列;usc具有列标题和节。在

如果torange中有以下行

title   s_low   s_high
  1        1      17

如果是行,代码需要签入usc

^{pr2}$

还有一场争吵

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

(请忽略那些有价值的陈述。这是我正在做的一项更大任务的一部分,打印只是用来检查发生了什么。)在

如能在这方面提供任何帮助,我们将不胜感激。在


Tags: 数据fromimport标题titleanysectionquery
1条回答
网友
1楼 · 发布于 2024-10-02 12:30:39

你的整个检查和迭代都搞砸了。您在usc中迭代row,但是您的any()条件检查usc,而不是{}。而且,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.

相关问题 更多 >

    热门问题