在 pandas 中以正确的映射向数据框添加新行 [英] Adding a new row to a dataframe with correct mapping in pandas

查看:58
本文介绍了在 pandas 中以正确的映射向数据框添加新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似下面的数据框-

I have a dataframe something like below-

      carrier_plan_identifier           ...            hios_issuer_identifier
1                        AUSK           ...                           99806.0
2                        AUSM           ...                           99806.0
3                        AUSN           ...                           99806.0
4                        AUSS           ...                           99806.0
5                        AUST           ...                           99806.0

我需要选择一个特定的列,让我们说 wellthie_issuer_identifier

I need to pick a particular column ,lets say wellthie_issuer_identifier.

我需要根据此列值查询数据库。我的选择查询看起来像。

I need to query the database based on this column value. My select query will look something like .

select id, wellthie_issuer_identifier from issuers where wellthie_issuer_identifier in(....)

我需要将 id 列添加到我现有的数据框中关于 wellthie_issuer_identifier

I need to add id column back to my existing dataframe with respect to the wellthie_issuer_identifier.

我进行了很多搜索,但不清楚如何实现。

I have searched a lot but not clear with how this can be done.

推荐答案

尝试一下:

1。) pick特定的列,让我们说 wellthie_issuer_identifier

1.) pick a particular column ,lets say wellthie_issuer_identifier

t = tuple(df .wellthie_issuer_identifier)
这将为您提供一个元组,如(1,0,1,1)

t = tuple(df.wellthie_issuer_identifier) This will give you a tuple like (1,0,1,1)

2。)根据此列值查询数据库

您需要用上述元组替换您的查询:

You need to substitute the above tuple in your query:

query = """select id, wellthie_issuer_identifier from issuers 
where wellthie_issuer_identifier in{} """

为数据库创建游标并执行此查询并创建结果的数据框。

Create a Cursor to the database and execute this query and Create a Dataframe of the result.

cur.execute(query.format(t))
df_new = pd.DataFrame(cur.fetchall())
df_new.columns = ['id','wellthie_issuer_identifier']

现在您的 df_new 将具有列 id,wellthie_issuer_identifier 。您需要将此 id 列添加回现有df。

Now your df_new will have columns id, wellthie_issuer_identifier. You need to add this id column back to existing df.

执行此操作:
df = pd.merge(df,df_new,on ='wellthie_issuer_identifier',how ='left')

它将添加 df id 列,如果在 wellthie_issuer_identifier上找到匹配项,该列将具有值code>,否则会放入 NaN

It will add an id column to df which will have values if a match is found on wellthie_issuer_identifier, otherwise it will put NaN.

让我知道是否有帮助。

这篇关于在 pandas 中以正确的映射向数据框添加新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆