【问题标题】:Assigning many values to one variable将多个值分配给一个变量
【发布时间】:2020-04-30 10:33:52
【问题描述】:

我正在尝试根据用户的选择获取电话号码

#the dict that contains the data I need
x={"contact": 
{
    "facility_message": "testing testing testing", 
    "facilitydigits":101,
    "name": "", 
    "urn": "tel:+1234567891011", 
    "uuid": "60409852-a2089-43d5-bd4c-4b89a6191793",
    "selection_anc_pnc":"C"
    }
}

#extracting data from the dict
facility_number=str(x['contact']['facilitydigits'])
group=(x['contact']['selection_anc_pnc']).upper()
facility_message=(x['contact']['facility_message'])

#checking user selection 
if group =='A':
    group="MIMBA"
elif group =='B':
    group='MAMA'    
elif group=='C':
    group='MAMA' and "MIMBA"

我的 df 看起来是这样的

phone       group   County  PNC/ANC Facility Name   Optedout    Facility Code
25470000040 MIMBA   Orange  PNC     Centre            FALSE      101
25470000030 MAMA    Orange  PNC     Centre            FALSE      101
25470000010 MIMBA   Orange  PNC     Centre            FALSE      101
25470000020 MAMA    Orange  PNC     Centre            FALSE      101
25470000050 MAMA    Orange  PNC     Main Centre       FALSE      112

从我的 df 中提取电话号码

phone_numbers =merged_df.loc[(merged_df['Facility Code'] ==facility_number) & (merged_df['group'] == group) & (merged_df['Opted out'] == optout)]['phone']
print(phone_numbers)

由于 if 语句当前正在发生什么

[25470000010,25470000040]

想要的输出

[25470000040,25470000030,25470000010,25470000020]

【问题讨论】:

  • 变量optout的值是多少

标签: python pandas if-statement variables


【解决方案1】:

您使用group = 'MAMA' and "MIMBA" 错误地分配了组值,执行后将值"MIMBA" 分配给作为最后一个真实值的组,而不是您想要做的是分配组可以使用的值列表group = ['MAMA', "MIMBA"]。然后,您可以使用Series.isin 方法过滤数据框中属于group 变量中存在的组的组。

用途:

if group =='A':
    group=["MIMBA"]
elif group =='B':
    group=['MAMA']    
elif group=='C':
    group=['MAMA', "MIMBA"]

m = (
    merged_df['Facility Code'].astype(str).eq(facility_number) 
    & merged_df['group'].isin(group) 
    & merged_df['Optedout'].eq(optout)
)

phone_numbers = merged_df.loc[m, "phone"]
print(phone_numbers.values)

打印出来:

[25470000040 25470000030 25470000010 25470000020] # assuming variable optout is False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    相关资源
    最近更新 更多