【发布时间】:2019-03-27 17:17:42
【问题描述】:
Adding a new row to a dataframe with correct mapping in pandas
与上述问题类似。
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
我需要选择多个列,比如说carrier_plan_identifier、wellthie_issuer_identifier 和hios_issuer_identifier。
使用这 3 列,我需要运行一个选择查询,例如,
select id from table_name where carrier_plan_identifier = 'something' and wellthie_issuer_identifier = 'something' and hios_issuer_identifier = 'something'
我需要将id 列添加回我现有的数据框
目前,我正在做这样的事情,
for index, frame in df_with_servicearea.iterrows():
if frame['service_area_id'] and frame['issuer_id']:
# reading from medical plans table
medical_plan_id = getmodeldata.get_medicalplans(sess, frame['issuer_id'], frame['hios_plan_identifier'], frame['plan_year'],
frame['group_or_individual_plan_type'])
frame['medical_plan_id'] = medical_plan_id
df_with_servicearea.append(frame)
当我这样做时,frame['medical_plan_id'] = medical_plan_id 没有添加任何内容。但是当我做df_with_servicearea['medical_plan_id'] = medical_plan_id 时,只有循环的最后一个值被添加到所有行中。我不确定这是否是正确的方法。
更新-:
使用后,我得到了 4 行,而不是应该存在的 2 行。
df_with_servicearea = df_with_servicearea.append(frame)
wellthie_issuer_identifier ... medical_plan_id
0 UHC99806 ... NaN
1 UHC99806 ... NaN
0 UHC99806 ... 879519.0
1 UHC99806 ... 879520.0
更新 2 - 根据 Mayank 的回答实施 - 嗨 Mayank,您是在建议这样的事情吗?
对于索引,df_with_servicearea.iterrows() 中的框架:
if frame['service_area_id'] and frame['issuer_id']:
# reading from medical plans table
df_new = getmodeldata.get_medicalplans(sess, frame['issuer_id'], frame['hios_plan_identifier'], frame['plan_year'],
frame['group_or_individual_plan_type'])
df_new.columns = ['medical_plan_id', 'issuer_id', 'hios_plan_identifier', 'plan_year',
'group_or_individual_plan_type']
new_df = pd.merge(df_with_servicearea, df_new, on=['issuer_id', 'hios_plan_identifier', 'plan_year', 'group_or_individual_plan_type'], how='left')
print new_df
我调用选择查询的 get_medicalplans 函数。
def get_medicalplans(self,sess, issuerid, hios_plan_identifier, plan_year, group_or_individual_plan_type):
try:
medical_plan = sess.query(MedicalPlan.id, MedicalPlan.issuer_id, MedicalPlan.hios_plan_identifier,
MedicalPlan.plan_year, MedicalPlan.group_or_individual_plan_type).filter(MedicalPlan.issuer_id == issuerid,
MedicalPlan.hios_plan_identifier == hios_plan_identifier,
MedicalPlan.plan_year == plan_year,
MedicalPlan.group_or_individual_plan_type == group_or_individual_plan_type)
sess.commit()
return pd.read_sql(medical_plan.statement, medical_plan.session.bind)
【问题讨论】:
-
您希望在什么条件下将
id添加回原始数据框?这些列carrier_plan_identifier, wellthie_issuer_identifier and hios_issuer_identifier是否也存在于您的数据框中?