Python——如何在没有意外串联的情况下对列表值的列使用sum函数



我正在处理一个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')

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

数据集中的条目示例

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

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

all_labels = df.categories.sum()

请告诉我这个代码是否是次优的,并希望能提出更好的建议。

无论如何,当我打印(all_labels(时,我遇到了一个问题。这就是前两行的聚合情况:

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

正如您所看到的,串联发生在第一个值结束、下一个值开始的地方(第一个列表的最后一项与第二个列表的第一项合并(。当我通过另一个函数运行每个类别时,这完全打乱了我的代码——特别是为了找出每个类别包含多少行。

有人能提供一个解决方案来防止这种单词串接吗

提前感谢!

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

试试怎么样?

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

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

我们需要更多的代码来了解您试图加入的变量类型,但如果df.cacategories是由字符串组成的,那么上面的代码行可能会帮助您朝着正确的方向前进。

最新更新