Pandas:添加具有其他列长度的列作为值 [英] Pandas: adding column with the length of other column as value

查看:52
本文介绍了Pandas:添加具有其他列长度的列作为值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向现有数据框添加一个附加列,该列的值是seller_name"列的长度.

I want to add an additional column to an existing dataframe that has the length of the 'seller_name' column as its value.

输出应该是这样的:

seller_name    name_length
-------------|-------------
Rick         |      4
Hannah       |      6

但是,我很难获得正确的代码.

However, I'm having difficulty getting the code right.

df['name_length']  = len(df['seller_name'])

只给我整列的长度 (6845)和

just gives me the length of the entire column (6845) And

df['nl']  = df[len('seller_name')]

抛出一个 KeyError.

Throws a KeyError.

有人知道实现我的目标的正确命令吗?

Does anyone know the correct command to achieve my goal?

非常感谢!

推荐答案

使用 .str 字符串访问器对 DataFrame 执行字符串操作.特别是,您需要 .str.len:

Use the .str string accessor to perform string operations on DataFrames. In particular, you want .str.len:

df['name_length']  = df['seller_name'].str.len()

结果输出:

  seller_name  name_length
0        Rick            4
1      Hannah            6

这篇关于Pandas:添加具有其他列长度的列作为值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆