【问题标题】:Python -- how to use sum function on column of list values without unintentional concatenationPython - 如何在列表值的列上使用 sum 函数而不会无意连接
【发布时间】:2019-11-19 20:14:51
【问题描述】:

我正在做一个 python 任务,我需要分析一个 yelp 数据集。以下是数据集的列:

Index(['business_id', 'name', 'address', 'city', 'state', 'postal_code',
   'latitude', 'longitude', 'stars', 'review_count', 'is_open',
   'categories', 'hours', 'attributes.RestaurantsTakeOut',
   'attributes.BusinessParking', 'attributes.Ambience',
   'attributes.RestaurantsDelivery', 'attributes.RestaurantsReservations',
   'attributes.BusinessAcceptsCreditCards',
   'attributes.RestaurantsPriceRange2',
   'attributes.RestaurantsGoodForGroups', 'attributes.DriveThru',
   'attributes.GoodForKids', 'attributes.GoodForMeal', 'attributes.HasTV',
   'attributes.OutdoorSeating', 'attributes.CoatCheck',
   'attributes.HappyHour', 'attributes.Smoking', 'attributes.WiFi',
   'attributes.RestaurantsTableService', 'attributes.Alcohol',
   'attributes.Caters', 'attributes.Music', 'attributes.BestNights',
   'attributes.WheelchairAccessible', 'attributes.BusinessAcceptsBitcoin',
   'attributes.GoodForDancing', 'attributes.BikeParking',
   'attributes.RestaurantsAttire', 'attributes.NoiseLevel',
   'hours.Wednesday', 'hours.Thursday', 'hours.Friday', 'hours.Saturday',
   'hours.Sunday', 'hours.Monday', 'hours.Tuesday',
   'attributes.DogsAllowed', 'attributes.BYOBCorkage',
   'attributes.Corkage', 'attributes.BYOB', 'attributes.ByAppointmentOnly',
   'attributes.AgesAllowed', 'attributes.Open24Hours',
   'attributes.AcceptsInsurance'],
  dtype='object')

以下是数据集中的一个条目示例:

example of entry in dataset

我对类别列感兴趣。每个类别值都由一个列表组成。在示例条目中,该值为“三明治、沙拉、餐厅、汉堡、舒适食品”。 “类别”列中的下一个值是“夜生活、酒吧、波兰语、现代欧洲、餐厅、素食主义者”。我想将所有行的类别列中的所有值聚合到一个巨大的列表中。因此,理想情况下,该列表将是一个不间断的存储库。那么,对于前两行,它看起来像这样: “三明治、沙拉、餐厅、汉堡、舒适食品、夜生活、酒吧、波兰、现代欧洲、餐厅、素食主义者”。

我想对所有行都这样做。我使用了以下代码:

all_labels = df.categories.sum()

如果这段代码不是最理想的,请告诉我,并希望能提出更好的建议。

无论如何,当我打印(all_labels)时,我遇到了问题。这是前两行聚合的样子:

Sandwiches, Salad, Restaurants, Burgers, Comfort FoodNightlife, Bars, Polish, Modern European, Restaurants, Vegan

如您所见,在第一个值结束和下一个值开始的地方发生了连接(第一个列表的最后一项与第二个列表的第一项合并)。当我通过另一个函数运行每个类别时,这完全弄乱了我的代码——特别是要找出每个类别包含多少行。

有人可以提供解决方案来防止这种单词连接吗?

提前致谢!

【问题讨论】:

    标签: python


    【解决方案1】:

    我认为您的意思是使用join() 而不是sum(),因为您正在连接代表用逗号分隔的列表的字符串,但每个列表都不以逗号结尾。

    试试怎么样?

    all_labels = ', '.join(df.categories)
    

    这会在您要加入的字符串之间插入逗号(而sum() 会在字符串出现时将它们连接起来)。

    我们需要更多代码来查看您尝试加入的变量类型,但如果 df.categories 由字符串组成,那么上面的代码行可能会帮助您找到正确的方向。

    【讨论】:

      猜你喜欢
      • 2012-04-02
      • 1970-01-01
      • 2014-07-04
      • 1970-01-01
      • 1970-01-01
      • 2020-06-27
      • 2013-09-14
      • 1970-01-01
      • 2020-06-10
      相关资源
      最近更新 更多