Python 如何在panda表的一列中计算逗号分隔的值?

Python 如何在panda表的一列中计算逗号分隔的值?,python,pandas,Python,Pandas,我有以下代码: 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

我有以下代码:

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]
它读取我的文件并创建一个我可以使用的熊猫表。 我需要的是计算“Category”变量的每行中有多少个类别,并将这个数字存储在名为“#categories”的新列中。以下是目标列示例:

Category                                         
French                                               
Adult Entertainment , Lounges , Music Venues         
American (New) , Steakhouses                        
American (New) , Beer, Wine & Spirits , Gastropubs 
Chicken Wings , Sports Bars , American (New)         
Japanese
期望输出:

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:


我放弃了。谢谢您的帮助,但我还得想些别的办法。

使用pd.read\u csv使输入更容易:

business = pd.read_csv('FL_Yelp_Data_v2.csv')

创建后,您可以创建一个函数,将“类别”列按“,”拆分,并计算结果列表的长度。使用lambda并应用。

此功能:

business['# Categories'] = business['Category'].apply(lambda x: len(x.split(',')))

如果需要处理NA等,可以传递一个更复杂的函数,而不是lambda。

假设类别实际上是一个列表,可以使用
apply
(根据@EdChum的建议):

如果没有,您首先需要解析它并将其转换为列表

df['Category'] = df.Category.map(lambda x: [i.strip() for i in x.split(",")])
您是否可以显示此列的一些输出示例(包括正确的引用)

p.S.@EdChum谢谢你的建议。我很感激他们。我相信列表理解方法可能更快,根据我用30k+行数据测试的一些文本数据样本:

%%timeit
df.Category.str.strip().str.split(',').apply(len)
10 loops, best of 3: 44.8 ms per loop

%%timeit
df.Category.map(lambda x: [i.strip() for i in x.split(",")])
10 loops, best of 3: 28.4 ms per loop
即使考虑到
len
函数调用:

%%timeit
df.Category.map(lambda x: len([i.strip() for i in x.split(",")]))
10 loops, best of 3: 30.3 ms per loop
你可以这样做

for i in business['Category'].tolist():
    business.loc[i, '#Categories'] = len(i.split(","))

我也有类似的疑问。我计算了每行中逗号分隔的单词数。我通过以下方式解决了这个问题:

数据['Number_of_Categories']=数据['Categories'].apply(lambda x:len(str(x).split(','))


基本上,我首先将每一行转换为字符串,因为Python将其识别为浮点,然后执行'len'函数。希望这有帮助

这可能是一个拼凑而成的解决方案,但我遇到了一个类似的问题,并使用类似的方法修复了它:

df['column_name'].apply(lambda n: \len(n.split(',')))
#Create an empty list to store your count in
numCategories=[]
#Create a loop to split each cell separately, then append to a list
i=0
while i <len(df):
#Switch out CategoriesColumnNumber in the below code for the correct column number
    temp_count = len(df.iloc[i,CategoriesColumnNumber].split(";"))
    numCategories.append(temp_count)
    i += 1
#Attach your newly generated list as a new column in your dataframe
df['#Categories'] = numCategories
#创建一个空列表来存储您的计数
numCategories=[]
#创建一个循环,分别拆分每个单元格,然后附加到列表中
i=0

虽然我是我们的类别数据存储为列表或显示的字符串?请发布原始输入数据和用于加载此数据的代码,因为您可以看到您已收到许多答案,其中一些可能会回答您的问题。到目前为止,问题仍然没有解决。我在帖子中添加了一些信息。我试着做
print type(business['Category'])是[all types of var]
,但我总是得到False作为回报。最好使用向量化的str split方法:
business['Category'].str.split(',')。apply(len)
这就是我从你的建议中得到的:
29 business=pd.read_csv('FL Yelp_Data_v2.csv')30#business['#Category']=business.Category.map(lambda x:[i.strip()表示x.split中的i(“,”)-->31个business['#Categories']=business['Category'].apply(lambda x:len(x.split(“,”))32 33打印类型(business['Category']))is float AttributeError:“float”对象没有属性“split”
显然,我在写答案时没有您的数据集。我假设“Category”列中的值是逗号分隔的字符串。您应该使用向量化str方法:
df.Category.str.strip().str.split(“,”).apply(len)
很抱歉我缺乏知识,但是这个“df”会是什么呢是?一个通用的熊猫数据帧,例如你的“业务”。我不能使用这些方法中的任何一种…我一直得到
“float”对象没有属性“split”
@audionic77你介意用你的示例数据和预期输出问一个新问题吗?你可以将它链接到这个。Thx。我怎么做这个函数vk1011?你可以在tw中做o方法:(1)使用内联拆分和计数:
business['number of categories']=business['categories'].apply(lambda x:len(x.split(','))
(2)定义一个函数并调用:
def split_和_count(string_to_split_和_count):split_up=string_to_split_和_count.split(','))num_categories=len(split_-up)return num_categories
在脚本中,您可以这样使用它:
business['number of categories']=business['categories']。apply(lambda x:split_and_count(x))
这是一个“仅代码”回答。如果你能用一个关于发生了什么的解释来围绕你的代码,提问者将更好地了解你想要完成什么,以及它如何帮助他们解决问题。虽然这段代码可能会解决问题,但如何解决问题以及为什么解决问题将真正有助于提高你的帖子的质量,并且可能会解决问题请记住,你是在回答未来读者的问题,而不仅仅是现在提问的人。请在回答中添加解释,并说明适用的限制和假设。
business['Categories'] = business.Category.str.count(',')+1
#Create an empty list to store your count in
numCategories=[]
#Create a loop to split each cell separately, then append to a list
i=0
while i <len(df):
#Switch out CategoriesColumnNumber in the below code for the correct column number
    temp_count = len(df.iloc[i,CategoriesColumnNumber].split(";"))
    numCategories.append(temp_count)
    i += 1
#Attach your newly generated list as a new column in your dataframe
df['#Categories'] = numCategories