我有以下代码:
businessdata = ['Name of Location','Address','City','Zip Code','Website','Yelp',
'# Reviews', 'Yelp Rating Stars','BarRestStore','Category',
'Price Range','Alcohol','Ambience','Latitude','Longitude']
business = pd.read_table('FL_Yelp_Data_v2.csv', sep=',', header=1, names=businessdata)
print '\n\nBusiness\n'
print business[:6]
它读取我的文件并创建一个Panda表供我使用。 我需要计算“Category”变量的每行中有多少个类别,并将这个数字存储在名为“categories”的新列中。以下是目标列示例:
^{pr2}$期望输出:
Category # Categories
French 1
Adult Entertainment , Lounges , Music Venues 3
American (New) , Steakhouses 2
American (New) , Beer, Wine & Spirits , Gastropubs 4
Chicken Wings , Sports Bars , American (New) 3
Japanese 1
编辑1:
原始输入=CSV文件。目标列:“类别” 我还不能发布截图。我不认为要计算的值是列表。在
这是我的代码:
business = pd.read_table('FL_Yelp_Data_v2.csv', sep=',', header=1, names=businessdata, skip_blank_lines=True)
#business = pd.read_csv('FL_Yelp_Data_v2.csv')
business['Category'].str.split(',').apply(len)
#not sure where to declare the df part in the suggestions that use it.
print business[:6]
但我一直收到以下错误:
TypeError: object of type 'float' has no len()
编辑2:
我放弃了。谢谢你的帮助,但我得想别的办法。在
假设Category实际上是一个列表,那么可以使用
apply
(根据@EdChum的建议):如果没有,首先需要解析它并将其转换为一个列表。在
^{pr2}$你能展示一下这个专栏的输出示例吗(包括正确的引文)?在
p.S.@EdChum谢谢你的建议。我很感激他们。我相信列表理解方法可能更快,根据我用30k+行数据测试的一些文本数据样本:
即使考虑到
len
函数调用:使用pd.read_csv文件要使输入更容易:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html
创建后,您可以创建一个函数,以“,”分隔categories列,并计算结果列表的长度。使用lambda并涂抹。在
这是有效的:
如果需要处理NA等,可以传递一个更精细的函数,而不是lambda。在
相关问题 更多 >
编程相关推荐