Adding a DataFrame column with len() of another column's values

混江龙づ霸主 提交于 2019-11-28 01:04:57

Pandas has a vectorised string method for this: str.len(). To create the new column you can write:

df['char_length'] = df['string'].str.len()

For example:

>>> df
  string
0   abcd
1  abcde

>>> df['char_length'] = df['string'].str.len()
>>> df
  string  char_length
0   abcd            4
1  abcde            5

This should be considerably faster than looping over the DataFrame with a Python for loop.

Many other familiar string methods from Python have been introduced to Pandas. For example, lower (for converting to lowercase letters), count for counting occurrences of a particular substring, and replace for swapping one substring with another.

Here's one way to do it.

In [3]: df
Out[3]:
  string
0   abcd
1  abcde

In [4]: df['len'] = df['string'].str.len()

In [5]: df
Out[5]:
  string  len
0   abcd    4
1  abcde    5
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!