【问题标题】:String capture function giving unknown error字符串捕获函数给出未知错误
【发布时间】:2018-10-05 01:06:37
【问题描述】:

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

提前致谢。

【问题讨论】:

  • row['PIC_1]' 已经是一个字符串。你只需要row['PIC_1'].find
  • 下面的答案有帮助吗?随意接受答案(左侧的绿色勾号),或要求澄清。

标签: python string pandas dataframe


【解决方案1】:

row['PIC_1'] 已经是str。您正试图从已经 str 类型中获取属性 str,这就是它抱怨的原因。

改为row['PIC_1'].find('42)

以后如果您有不是str 的东西,您也不会尝试访问属性,而是通过str(112233445542) 将其转换为str。

【讨论】:

    【解决方案2】:

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

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

    因此,删除pic_mod 中所有str 属性实例:

    • 将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)]。

    【讨论】:

      猜你喜欢
      • 2015-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多