Pandas Dataframe循环并从数据库更新

时间:2019-01-28 09:39:45

标签: python database pandas dataframe sqlalchemy

给出一个熊猫数据框 df ,如下所示:

p_id | sales | salesperson | year
1    | 10,000| None        | 2017
2    | 15,000| None        | 2016
5    | 7,000 | None        | 2014
5    | 3,000 | None        | 2015

存在一个SQL表,,如下所示:

p_id | p_name        | from_year | to_year
1    | Brian Griffin | 2017      | Null
2    | Quagmire      | 2016      | Null
5    | Cleveland     | 2014      | 2015
5    | Lois Griffin  | 2015      | Null

我正在尝试从SQL表填充数据框中的缺失数据。 只要一个人一次使用一个p_id,就可以重复使用。

我要做的是以下事情:

for index, row in df.iterrows():
     df.at[index, 'salesperson'] = fetch_name(row['p_id'], row['year'])

def fetch_name(pid, year):
     meta = sqlalchemy.MetaData()
     persons = sqlalchemy.Table('persons', meta, autoload=True, autoload_with=data_engine)

     stmt = sqlalchemy.select([persons.c.p_name]).where(
            and_(persons.c.p_id == pid, and_(year >= persons.c.from_year, 
            or_(year < persons.c.to_year, persons.c.to_year.is_(None))))

     name = data_engine.execute(stmt).scalar()

     return name

这很好,但是非常慢。对于30,000行的数据框,大约需要20分钟才能映射和填充丢失的数据。

是否会有更好的方法来达到相同的结果?

0 个答案:

没有答案