【发布时间】:2014-06-03 08:57:09
【问题描述】:
我有 2 个数据框。标题和部分是其中的两列。 我需要检查一个数据框中的特定标题和部分的组合是否存在于第二个数据框中。
例如数据框torange有列title、s_low、s_high等; usc 具有列标题和部分。
如果torange中有下面一行
title s_low s_high
1 1 17
如果一行代码需要签入usc
title section
1 1
还有一行
title section
1 17
存在;并创建一个新表,通过扩展usc 中的 s_low 和 s_high 之间的范围,在 torange 中写入标题、部分和其余列。
我编写了以下代码,但不知何故,它在几次迭代后就无法工作/停止。我怀疑“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
(请忽略打印语句。这是我正在做的一项更大任务的一部分,打印只是用来检查正在发生的事情。)
在这方面的任何帮助将不胜感激。
【问题讨论】:
标签: python sql pandas dataframe