
[英]Python - Pandas - Import Excel file, iterate through each row, add new value, and add to dataframe
[英]Iterate through row if statement and add to new columns [Pandas/Python]
我有一个3列的数据框
Hospital 2009-10 2010-11
Aberystwyth Mental Health Unit 19 19
Bro Ddyfi Community Hospital 16 10
Bronglais General Hospital 160 148
Caebryn Mental Health Unit 37 39
Carmarthen Mental Health Unit 38 31
我正在尝试创建一个函数来检查单词是否在医院列中,如果这样,它将单词放入新列中,如下所示:
Hospital 2009-10 2010-11 Hospital Type
Aberystwyth Mental Health Unit 19 19 Mental
Bro Ddyfi Community Hospital 16 10 Community
Bronglais General Hospital 160 148 General
Caebryn Mental Health Unit 37 39 Mental
Carmarthen Mental Health Unit 38 31 Mental
这是我尝试过的代码:
def find_type(x):
if df['Hospital'].str.contains("Mental").any():
return "Mental"
if df['Hospital'].str.contains("Community").any():
return "Community"
else:
return "Other"
df['Hospital Type'] = df.apply(find_type)
我得到的输出是这样的:
Hospital 2009-10 2010-11 Hospital Type
Aberystwyth Mental Health Unit 19 19 NaN
Bro Ddyfi Community Hospital 16 10 NaN
Bronglais General Hospital 160 148 NaN
Caebryn Mental Health Unit 37 39 NaN
Carmarthen Mental Health Unit 38 31 NaN
我怎样才能得到预期的输出呢?
谢谢!
pat = r"(Mental|Community)"
df['Hospital Type'] = df['Hospital'].str.extract(pat, expand=False).fillna('Other')
print (df)
Hospital 2009-10 2010-11 Hospital Type
0 Aberystwyth Mental Health Unit 19 19 Mental
1 Bro Ddyfi Community Hospital 16 10 Community
2 Bronglais General Hospital 160 148 Other
3 Caebryn Mental Health Unit 37 39 Mental
4 Carmarthen Mental Health Unit 38 31 Mental
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.