Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the length of every element in one column

Tags:

python

pandas

In csv file, there is one column called "no_pun". There are some tokenized words in it. I want to get the length of every element in this column. This is easy in python. But I have an error.

My code:

for i in range(0,len(data['no_pun'])):
    data["len_desc"][i] = len(data["no_pun"][i])

The KeyError:

  KeyError Traceback (most recent call last)
/anaconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2655             try:
-> 2656                 return self._engine.get_loc(key)
   2657             except KeyError:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'len_desc'

During handling of the above exception, another exception occurred:

like image 864
Jieyu Zhang Avatar asked Nov 19 '25 02:11

Jieyu Zhang


1 Answers

This would add a new column to the existing dataframe that has the length of the string from no_pun column:

data['NewColumnName'] = [len(x) for x in data['no_pun']]

or

data['no_pun'].str.len()
like image 71
IM80554Coding Avatar answered Nov 21 '25 17:11

IM80554Coding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!