如果“付款类别”列为Legal
,我尝试创建一个使用Expense
填充工具类型列的if语句。
但是,无论薪资类别如何,它都会将包含Legal
Legal
的所有内容展开。{/ p>
test={"Pay Category":["Indemnity","Indemnity","Indemnity","Indemnity","Expense","Expense","Expense","Medical"],"Description of Payment":["Legal","Legal","Legal","Legal","Legal","Legal","Frog","Legal",]}
test=pd.DataFrame(test)
test["Tool Type"]=""
if (test["Pay Category"]=="Medical") is not False:
test["Tool Type"][test["Description of Payment"].str.contains("Pharmacy|Prescription|RX",case=False)]="Pharmacy"
if (test["Pay Category"]=='Expense') is not False:
test["Tool Type"][test["Description of Payment"].str.contains("Legal|Attorney|Court|Defense",case=False)]="Legal"
我的理解是,if (test["Pay Category"]=='Expense') is not False:
是一个布尔值,它是True or False
,它只应该执行if语句,如果标准"不是假的#34;满足了。我错过了什么?
布兰登
答案 0 :(得分:3)
我认为您需要添加条件并将其与test["Tool Type"]=""
m1 = test["Description of Payment"].str.contains("Pharmacy|Prescription|RX",case=False)
m2 = test["Pay Category"]=="Medical"
m3 = test["Description of Payment"].str.contains("Legal|Attorney|Court|Defense",case=False)
m4 = test["Pay Category"]=="Expense"
test.loc[m1 & m2, "Tool Type"]="Pharmacy"
test.loc[m3 & m4, "Tool Type"]="Legal"
print (test)
Description of Payment Pay Category Tool Type
0 Legal Indemnity
1 Legal Indemnity
2 Legal Indemnity
3 Legal Indemnity
4 Legal Expense Legal
5 Legal Expense Legal
6 Frog Expense
7 Legal Medical
(test['Tool Type'] = np.where(m1 & m2, 'Pharmacy',
np.where(m3 & m4, 'Legal', ''))
print (test)
Description of Payment Pay Category Tool Type
0 Legal Indemnity
1 Legal Indemnity
2 Legal Indemnity
3 Legal Indemnity
4 Legal Expense Legal
5 Legal Expense Legal
6 Frog Expense
7 Legal Medical
)链接起来:
test['Tool Type'] = np.select([(m1 & m2), (m3 & m4)], ['Pharmacy', 'Legal'], default='')
print (test)
Description of Payment Pay Category Tool Type
0 Legal Indemnity
1 Legal Indemnity
2 Legal Indemnity
3 Legal Indemnity
4 Legal Expense Legal
5 Legal Expense Legal
6 Frog Expense
7 Legal Medical
另一个双Apple's Documentation的解决方案:
SelectedDates
编辑:numpy.where
评论的非常好的解决方案是使用unutbu
List