Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of characters in a string, create a data frame column out of it? [duplicate]

A quick question for the universe of programmers.

DATA. Data frame column consisting of names.

g['NAME']=['John', 'Michael', 'Jezus', 'Donald', 'Suzy']

DESIRED RESULT. Another, parallel data frame column consisting of number of characters in for each name in g['NAME'].

g['NAME_count'] = [4,7,5,6,4]

Thank you in advance!

like image 925
Gediminas Sadaunykas Avatar asked Dec 20 '16 13:12

Gediminas Sadaunykas


People also ask

How do you count occurrences in a DataFrame column?

We can count by using the value_counts() method. This function is used to count the values present in the entire dataframe and also count values in a particular column.

How do I count the number of characters in a data frame?

To calculate the numbers of characters we use Series. str. len(). This function returns the count of the characters in each word in a series.

How do you count duplicates in a DataFrame column?

You can count the number of duplicate rows by counting True in pandas. Series obtained with duplicated() . The number of True can be counted with sum() method.


1 Answers

You can use vectorised str.len to achieve this:

In [106]:
df['NAME_Count'] = df['NAME'].str.len()
df

Out[106]:
      NAME  NAME_Count
0     John           4
1  Michael           7
2    Jezus           5
3   Donald           6
4     Suzy           4
like image 70
EdChum Avatar answered Sep 22 '22 02:09

EdChum