Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas - Counting quantity of commas in character field

Tags:

python

pandas

I have a pandas dataframe with a column filled with strings as is shown below:

   string_column
0  t,d,t,d,v,d
1  s,v,y,d
2  d,u,f

I would like to create a new column with the count of commas in the string column. My intended outcome is below:

   string_column  comma_count
0  t,d,t,d,v,d    5
1  s,v,y,d        3
2  d,u,f          2

Is there a string reading method to pandas that will accomplish this task?

Thanks

like image 466
Jeff Saltfist Avatar asked Feb 10 '17 06:02

Jeff Saltfist


2 Answers

Use str.count:

df['comma_count'] = df.string_column.str.count(',')
print (df)
  string_column  comma_count
0   t,d,t,d,v,d            5
1       s,v,y,d            3
2         d,u,f            2
like image 184
jezrael Avatar answered Oct 17 '22 13:10

jezrael


use str.count

df.assign(comma_count=df.string_column.str.count(','))

  string_column  comma_count
0   t,d,t,d,v,d            5
1       s,v,y,d            3
2         d,u,f            2
like image 27
piRSquared Avatar answered Oct 17 '22 13:10

piRSquared