记录python在series中使用split()时犯的错误

在将dataframe的一列的所有数据使用string的内置方法时,我犯了一个错误

series.astype('str').split(" ")[0]

然后我得到的结果是这样的一个错误

AttributeError: 'Series' object has no attribute 'split'

在网上查了一下发现要这样用:

L.astype('str').str.split(" ").str[0]

但是一时想不通为什么,看了一下教程和源码,发现str是是一个对象

series.py

...
# ----------------------------------------------------------------------
# Accessor Methods
# ----------------------------------------------------------------------
str = CachedAccessor("str", StringMethods)
dt = CachedAccessor("dt", CombinedDatetimelikeProperties)
cat = CachedAccessor("cat", CategoricalAccessor)
plot = CachedAccessor("plot", pandas.plotting.PlotAccessor)
sparse = CachedAccessor("sparse", SparseAccessor)
...

将str转换成一个StringMethods对象,内置有string的处理方法,series对象不能用的string方法,在转换为str对象后就能使用了。

strings.py

...
class StringMethods(NoNewAttributesMixin):
"""
Vectorized string functions for Series and Index. NAs stay NA unless
handled otherwise by a particular method. Patterned after Python's string
methods, with some inspiration from R's stringr package.

Examples
--------
>>> s.str.split('_')
>>> s.str.replace('_', '')
"""
...

然而,series里面并没有split()方法,所以我直接调用就给我报错。

我之前想series可以直接+或-这样运算,然后每一个元素都会这样操作,就理所当然的把split()这样用上了。

错误记录一下。

发布了38 篇原创文章 · 获赞 3 · 访问量 3124

猜你喜欢

转载自blog.csdn.net/weixin_44941795/article/details/104367793
今日推荐