在 pandas 对象列上调用`str.len`时遇到问题 [英] Trouble calling `str.len` on a pandas object column

查看:58
本文介绍了在 pandas 对象列上调用`str.len`时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为title的字符串列的Pandas DataFrame,我想将每一行的条目转换为该字符串的长度.因此,"abcd"将被转换为4,依此类推.

I have a Pandas DataFrame with a string column called title and I want to convert each row's entry to that string's length. So "abcd" would be converted to 4, etc.

我正在这样做:

result_df['title'] = result_df['title'].str.len()

但是不幸的是,我得到了这个错误:

But unfortunately, I get this error:

AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas

这似乎暗示我的列中实际上没有字符串...

which seems to imply that I don't actually have strings in my column...

我应该怎么做?

谢谢!

推荐答案

您正在尝试将整个列转换为str而不是值,或者将列转换为混合类型.试试:

You're either trying to convert the whole column to str and not the values or have mixed types in the column. Try:

result_df['title'] = result_df['title'].apply(lambda x: len(str(x)))

这篇关于在 pandas 对象列上调用`str.len`时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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