【问题标题】:Pandas error "Can only use .str accessor with string values"Pandas 错误“只能将 .str 访问器与字符串值一起使用”
【发布时间】:2016-02-15 00:32:01
【问题描述】:

我有以下输入文件:

"Name",97.7,0A,0A,65M,0A,100M,5M,75M,100M,90M,90M,99M,90M,0#,0N#,

我正在阅读它:

#!/usr/bin/env python

import pandas as pd
import sys
import numpy as np

filename = sys.argv[1]
df = pd.read_csv(filename,header=None)
for col in df.columns[2:]:
    df[col] = df[col].str.extract(r'(\d+\.*\d*)').astype(np.float)

print df

但是,我得到了错误

    df[col] = df[col].str.extract(r'(\d+\.*\d*)').astype(np.float)
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/generic.py", line 2241, in __getattr__
    return object.__getattribute__(self, name)
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/base.py", line 188, in __get__
    return self.construct_accessor(instance)
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/base.py", line 528, in _make_str_accessor
    raise AttributeError("Can only use .str accessor with string "
AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas

这在 pandas 0.14 中工作正常,但在 pandas 0.17.0 中不起作用。

【问题讨论】:

    标签: python string pandas casting dataframe


    【解决方案1】:

    在这种情况下,我们必须在该系列上使用str.replace() 方法,但首先我们必须将其转换为str 类型:

    df1.Patient = 's125','s45',s588','s244','s125','s123'
    df1 = pd.read_csv("C:\\Users\\Gangwar\\Desktop\\competitions\\cancer prediction\\kaggle_to_students.csv")
    df1.Patient = df1.Patient.astype(str)
    df1['Patient'] = df1['Patient'].str.replace('s','').astype(int) 
    

    【讨论】:

      【解决方案2】:

      我在 Eclipse 中工作时遇到此错误。事实证明,项目解释器以某种方式(我相信在更新之后)重置为 Python 2.7。将其设置回 Python 3.6 解决了这个问题。这一切都导致了几次崩溃、重新启动和警告。经过几分钟的麻烦,现在似乎已解决。

      虽然我知道这不是这里提出的问题的解决方案,但我认为它可能对其他人有用,因为我在搜索此错误后来到此页面。

      【讨论】:

        【解决方案3】:

        发生这种情况是因为您的最后一列是空的,所以它被转换为NaN

        In [417]:
        t="""'Name',97.7,0A,0A,65M,0A,100M,5M,75M,100M,90M,90M,99M,90M,0#,0N#,"""
        df = pd.read_csv(io.StringIO(t), header=None)
        df
        
        Out[417]:
               0     1   2   3    4   5     6   7    8     9    10   11   12   13  14  \
        0  'Name'  97.7  0A  0A  65M  0A  100M  5M  75M  100M  90M  90M  99M  90M  0#   
        
            15  16  
        0  0N# NaN  
        

        如果您将范围分割到最后一行,那么它可以工作:

        In [421]:
        for col in df.columns[2:-1]:
            df[col] = df[col].str.extract(r'(\d+\.*\d*)').astype(np.float)
        df
        
        Out[421]:
               0     1   2   3   4   5    6   7   8    9   10  11  12  13  14  15  16
        0  'Name'  97.7   0   0  65   0  100   5  75  100  90  90  99  90   0   0 NaN
        

        或者,您可以只选择 object dtype 的列并运行代码(跳过第一个列,因为这是“名称”条目):

        In [428]:
        for col in df.select_dtypes([np.object]).columns[1:]:
            df[col] = df[col].str.extract(r'(\d+\.*\d*)').astype(np.float)
        df
        
        Out[428]:
               0     1   2   3   4   5    6   7   8    9   10  11  12  13  14  15  16
        0  'Name'  97.7   0   0  65   0  100   5  75  100  90  90  99  90   0   0 NaN
        

        【讨论】:

        • 谢谢!这是 0.17 中的新功能吗?
        • 0.14.1以来一直存在
        • 发出警告/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:2: FutureWarning: currently extract(expand=None) means expand=False (return Index/Series/DataFrame) but in a future version of pandas this will be changed to expand=True (return DataFrame)
        猜你喜欢
        • 2018-08-04
        • 2017-06-01
        • 2018-12-22
        • 2021-03-18
        • 1970-01-01
        • 2020-03-27
        • 1970-01-01
        • 2022-11-15
        • 2014-07-03
        相关资源
        最近更新 更多