使用另一列值的len()添加DataFrame列

hal*_*cos 8 python string string-length dataframe pandas

我在尝试获取另一列中的字符串值的字符计数列时遇到问题,并且还没有想出如何有效地执行此操作.

for index in range(len(df)):
    df['char_length'][index] = len(df['string'][index]))
Run Code Online (Sandbox Code Playgroud)

这显然涉及首先创建一列空值然后重写它,并且我的数据集需要很长时间.那么获得类似东西最有效的方法是什么

'string'     'char_length'
abcd          4
abcde         5
Run Code Online (Sandbox Code Playgroud)

我已经检查了很多,但我还没弄清楚.

Ale*_*ley 13

Pandas有一个矢量化的字符串方法:str.len().要创建新列,您可以编写:

df['char_length'] = df['string'].str.len()
Run Code Online (Sandbox Code Playgroud)

例如:

>>> df
  string
0   abcd
1  abcde

>>> df['char_length'] = df['string'].str.len()
>>> df
  string  char_length
0   abcd            4
1  abcde            5
Run Code Online (Sandbox Code Playgroud)

这应该比使用Python for循环遍历DataFrame快得多.

许多其他熟悉的Python字符串方法已经引入了Pandas.例如,lower(用于转换为小写字母),count用于计算特定子字符串的出现次数,以及replace用于将一个子字符串与另一个子字符串进行交换.