Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫:以其他列的长度作为值添加列_Python_Pandas - Fatal编程技术网

Python 熊猫:以其他列的长度作为值添加列

Python 熊猫:以其他列的长度作为值添加列,python,pandas,Python,Pandas,我想在现有数据框中添加一个附加列,该列的值为'seller_name'列的长度 输出应如下所示: seller_name name_length -------------|------------- Rick | 4 Hannah | 6 然而,我很难得到正确的代码 df['name_length'] = len(df['seller_name']) 只给我整列的长度(6845) 及 抛出一个键错误 有人知道实现我目标的正确命令吗 非

我想在现有数据框中添加一个附加列,该列的值为'seller_name'列的长度

输出应如下所示:

seller_name    name_length
-------------|-------------
Rick         |      4
Hannah       |      6
然而,我很难得到正确的代码

df['name_length']  = len(df['seller_name'])
只给我整列的长度(6845) 及

抛出一个键错误

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


非常感谢

使用
.str
字符串访问器对数据帧执行字符串操作。特别是,您需要:

结果输出:

  seller_name  name_length
0        Rick            4
1      Hannah            6

假设您有以下数据:

y_1980 = pd.read_csv('y_1980.csv', sep='\t')

     country  y_1980
0     afg     196
1     ago     125
2     alb      23
如果要计算任何列的长度,可以使用:

y_1980['length'] = y_1980['country'].apply(lambda x: len(x))
print(y_1980)

     country  y_1980  length
 0     afg     196       3
 1     ago     125       3
 2     alb      23       3

通过这种方式,您可以计算所需的任何列的长度。

熊猫内置方法比使用
apply
更可靠。例如,如果字符串列中存在NaN,则此方法将引发TypeError,但内置的
.str.len
将处理NaN。当列是列表时,这对我有帮助
y_1980 = pd.read_csv('y_1980.csv', sep='\t')

     country  y_1980
0     afg     196
1     ago     125
2     alb      23
y_1980['length'] = y_1980['country'].apply(lambda x: len(x))
print(y_1980)

     country  y_1980  length
 0     afg     196       3
 1     ago     125       3
 2     alb      23       3