![](/img/trans.png)
[英]Truly a beginner, assigning the multiple values to one variable in Python
[英]Assigning many values to one variable
我正在嘗試根據用戶的選擇獲取電話號碼
#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]
所需 output
[25470000040,25470000030,25470000010,25470000020]
您使用group = 'MAMA' and "MIMBA"
錯誤地分配了組值,執行后將值"MIMBA"
分配給作為最后一個真實值的組,而不是您想要做的是分配該組的值列表可以使用group = ['MAMA', "MIMBA"]
。 然后,您可以使用Series.isin
方法過濾 dataframe 中屬於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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.