将新行添加到数据帧中,并在中正确映射

2024-05-14 16:10:23 发布

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

我有一个如下的数据帧-

      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。你知道吗

我需要基于此列值查询数据库。我的select查询将类似于。你知道吗

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

我需要将id列添加回与wellthie_issuer_identifier相关的现有数据帧。你知道吗

我已经搜索了很多,但不清楚如何才能做到这一点。你知道吗


Tags: 数据idselectidentifierissuerplancarrier查询数据库
3条回答

试试这个:

1.)选择一个特定的列,比如说wellthie_issuer_identifier

t = tuple(df.wellthie_issuer_identifier) 这会给你一个tuple式的(1,0,1,1)

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

您需要在查询中替换上述元组:

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

创建一个指向数据库的游标,执行这个查询并创建结果的数据帧。你知道吗

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。你知道吗

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

它将向df添加一个id列,如果在wellthie_issuer_identifier上找到匹配项,该列将有值,否则它将放入NaN。你知道吗

如果这有帮助,请告诉我。你知道吗

这将不接受wellthie_issuer_identifier的值,但正如您所说的,它将是它们的所有值,那么下面应该适合您:

df1 = df.assign(id=(df['wellthie_issuer_identifier']).astype('category').cat.codes)

如果列不太长,可以使用pandas将另一列添加到数据帧,例如:

import pandas as pd

df = pd.read_csv('just.csv')
df

   id  user_id  name
0   1        1  tolu
1   2        5    jb
2   3        6   jbu
3   4        7   jab
4   5        9   jbb

#to add new column to the data above

df['new_column']=['jdb','biwe','iuwfb','ibeu','igu']#new values
df

   id  user_id  name new_column
0   1        1  tolu        jdb
1   2        5    jb       biwe
2   3        6   jbu      iuwfb
3   4        7   jab       ibeu
4   5        9   jbb        igu

#this should help if the dataset is not too much 

然后您可以继续查询您的数据库

相关问题 更多 >

    热门问题