字符串捕获功能给出未知错误

时间:2018-04-24 17:04:31

标签: python string pandas dataframe

df71等于:

                                            PIC_1  p_lgth  Wgt
                   420294189300189843900787520557      30  112
                   420951119300189843900787520618      30   64
**PARTIAL-DECODE***P / 42011721930018984390078...      53  112
                   420112289300189843900782713107      30  144
                   420212369300189843900787520397      30   70

下面是我使用apply()

应用于每行df71的函数
def pic_mod(row):
 if row['p_lgth'] !=30:
    n = row['PIC_1'].str.find('42')
    PIC_2 = row['PIC_1'].str[int(n):int(n+28)]
 elif row['p_lgth']==30:
    PIC_2=row['PIC_1']  
 return PIC_2


df71['PIC_1_master'] = df71.apply(pic_mod, axis=1)

当我运行上面的代码时,我得到:

File "<ipython-input-192-9d112a2f0924>", line 3, in pic_mod
  n = row['PIC_1'].str.find('42')

AttributeError: ("'str' object has no attribute 'str'", 'occurred at 
index   2')

为什么!!! ????以下是您想知道的数据类型。

df71.dtypes

PIC_1     object
p_lgth     int64
Wgt       object

提前致谢。

2 个答案:

答案 0 :(得分:1)

row['PIC_1']已经str。您正尝试从已str类型中获取属性str,这就是为什么它会抱怨。

而是将其更改为row['PIC_1'].find('42)

将来,如果您的某些内容不是str,您也不会尝试访问某个属性,而是str(112233445542)将其转换为str

答案 1 :(得分:0)

当您使用pd.DataFrame.apply时,会将类似系列的对象传递给函数,其中可以通过语法row['col']提取组件。

现在row['col']将代表您系列的元素,因此它可能是标量,例如strintfloat。如果是字符串,则它不会像str对象那样具有pd.Series访问者。

因此,请移除str中的所有pic_mod属性实例:

  • row['PIC_1'].str.find('42')替换为row['PIC_1'].find('42')
  • row['PIC_1'].str[int(n):int(n+28)]替换为row['PIC_1'][int(n):int(n+28)]