2 回答
TA贡献1773条经验 获得超3个赞
如果存在矢量化解决方案,在 Pandas 中最好避免循环(应用是引擎盖下的循环),因为循环很慢。
我尝试重写您的代码 - 创建带有输出和值列表的字典,用值交换键并调用map,最后为不匹配的值添加fillna:
d = {'Residential' :['Multifamily Housing', 'Residence Hall/Dormitory'],
'Commercial' : ['Bank Branch', 'Hotel' , 'Financial Office' , 'Retail Store', 'Distribution Center',
'Non-Refrigerated Warehouse', 'Fitness Center/Health Club/Gym', 'Mixed Use Property',
'Self-Storage Facility', 'Wholesale Club/Supercenter', 'Supermarket/Grocery Store'],
'Institutional':['Senior Care Community', 'K-12 School', 'College/University', 'Worship Facility',
'Medical Office', 'Hospital (General Medical & Surgical)'],
'Industrial': ['Manufacturing/Industrial Plant'] }
d1 = {k: oldk for oldk, oldv in d.items() for k in oldv}
print (d1)
{
'Multifamily Housing': 'Residential',
'Residence Hall/Dormitory': 'Residential',
'Bank Branch': 'Commercial',
'Hotel': 'Commercial',
'Financial Office': 'Commercial',
'Retail Store': 'Commercial',
'Distribution Center': 'Commercial',
'Non-Refrigerated Warehouse': 'Commercial',
'Fitness Center/Health Club/Gym': 'Commercial',
'Mixed Use Property': 'Commercial',
'Self-Storage Facility': 'Commercial',
'Wholesale Club/Supercenter': 'Commercial',
'Supermarket/Grocery Store': 'Commercial',
'Senior Care Community': 'Institutional',
'K-12 School': 'Institutional',
'College/University': 'Institutional',
'Worship Facility': 'Institutional',
'Medical Office': 'Institutional',
'Hospital (General Medical & Surgical)': 'Institutional',
'Manufacturing/Industrial Plant': 'Industrial'
}
datav3 = pd.DataFrame({'Program':['Medical Office','Hotel',
'Residence Hall/Dormitory',
'Manufacturing/Industrial Plant','House']})
datav3['Program Type'] = datav3['Program'].map(d1).fillna('Other')
print (datav3)
Program Program Type
0 Medical Office Institutional
1 Hotel Commercial
2 Residence Hall/Dormitory Residential
3 Manufacturing/Industrial Plant Industrial
4 House Other
TA贡献1827条经验 获得超9个赞
问题在于您的 if 循环。您之后比较的方式or
不正确。
写作or 'Residence Hall/Dormitory'
将永远是true
,因此,if
每次只评估第一个,并且您进入Residential
所有行。
取而代之的是:
if c['Primary Property Type - Self Selected'] == 'Multifamily Housing' or 'Residence Hall/Dormitory':
做这个:
if c['Primary Property Type - Self Selected'] == 'Multifamily Housing' or c['Primary Property Type - Self Selected'] == 'Residence Hall/Dormitory':
或者
if any([c['Primary Property Type - Self Selected'] == 'Multifamily Housing', c['Primary Property Type - Self Selected'] == 'Residence Hall/Dormitory']):
只需进行上述更改,您的代码就应该符合预期。希望这很清楚。
添加回答
举报