使用apply lambda和str从python列中获取子字符串 [英] Getting substring from column in python using apply lambda and str
问题描述
我有一个带有Fib列的数据框,我试图从中获取一个子字符串:
I have a dataframe with a column Fib, I am trying to grab a substring from it:
任何人都可以告诉我为什么此代码不起作用:
Could anyone please tell me why this code does not work:
df['new'] = df['Fib'].apply(lambda x:x.str[2:10])
AttributeError:'str'对象没有属性'str'
AttributeError: 'str' object has no attribute 'str'
但是,如果我这样做,它将起作用:
But if i do this, it will work:
df['new_col'] = df['Fib'].astype(str).str[2:10]
我正在尝试使用apply + lambda解决上述问题,只是为了获得一些经验. 谢谢
I am trying to solve the above problem with apply+lambda just to get some experience with it. Thank you
推荐答案
您的代码中的问题是,您apply
沿系列行的lambda
函数将收到显示的字符串.这是一个说明这一点的示例:
The problem in your code is that the lambda
function you apply
along the rows of your series will be receiving a string as it appears. Here's an example to illustrate this:
df = pd.DataFrame({'num':[1,4,2], 'alpha':['apple','orange','peach']})
df['alpha'].apply(lambda x:type(x))
<class 'str'>
<class 'str'>
<class 'str'>
请注意, Series.str
方法仅适用于Series
,如文档中明确指出的那样:
Note that Series.str
methods are only for Series
, as clearly stated in the documentation:
系列和索引的向量化字符串函数
Vectorized string functions for Series and Index
因此对于您的示例,应避免使用Apply.而是:
So for your example you should avoid using apply. Instead do:
df['alpha'].str[2:10]
0 ple
1 ange
2 ach
Name: alpha, dtype: object
如果您要使用的是apply
而不是您提到的那样,则只需将lambda x: x[2:10]
直接切成字符串即可:
If what you want is to use apply
instead as you mention, you simply need lambda x: x[2:10]
as you are directly slicing the string:
df['alpha'].apply(lambda x: x[2:10])
0 ple
1 ange
2 ach
Name: alpha, dtype: object
这篇关于使用apply lambda和str从python列中获取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!