【问题标题】:Create new column in pandas df and assign string values conditionally在 pandas df 中创建新列并有条件地分配字符串值
【发布时间】:2018-12-04 20:12:22
【问题描述】:

我是 pandas 的新手,试图在 Pandas Dataframe 中创建一个新列,并基于函数分配一个字符串值,但结果仅向所有 5,000 列输出 1 个值(“住宅”)。知道我的代码有什么问题吗?谢谢

def programType(c):
if c['Primary Property Type - Self Selected'] == 'Multifamily Housing' or 'Residence Hall/Dormitory':
    return 'Residential'

elif c['Primary Property Type - Self Selected'] == 'Bank Branch' or 'Hotel' or 'Financial Office' \
or 'Retail Store' or 'Distribution Center' or 'Non-Refrigerated Warehouse' or 'Fitness Center/Health Club/Gym' \
or 'Mixed Use Property' or 'Self-Storage Facility' or 'Wholesale Club/Supercenter' or 'Supermarket/Grocery Store':
    return 'Commercial'  

elif c['Primary Property Type - Self Selected'] == 'Senior Care Community' or 'K-12 School' or 'College/University' \
or 'Worship Facility' or 'Medical Office' or 'Hospital (General Medical & Surgical)':
    return 'Institutional'

elif c['Primary Property Type - Self Selected'] == 'Manufacturing/Industrial Plant': 
    return 'Industrial'

else:
    return 'Other'

新列名为“程序类型”

datav3['Program Type'] = datav3.apply(programType, axis=1)

【问题讨论】:

  • 我有点好奇——出于某种原因你需要循环(应用)吗?
  • 不,如果有更好的语法我很乐意使用它。我也刚刚看了你的回答,现在明白了。谢谢。

标签: python pandas


【解决方案1】:

如果存在矢量化解决方案,在 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

【讨论】:

  • 如果您不介意,能否请您稍微解释一下,我是这个语法的新手:d1 = {k: oldk for oldk, oldv in d.items() for k在 oldv} 谢谢!
  • @SchratchieMe 你可以查看this
  • @SchratchieMe 和 this
【解决方案2】:

问题在于您的 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']):

只需进行上述更改,您的代码就会按照预期进行。希望这很清楚。

【讨论】:

    猜你喜欢
    • 2021-01-04
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    相关资源
    最近更新 更多