Pandas错误"只能使用带字符串值的.str访问器"

时间:2015-11-13 12:13:59

标签: python string pandas casting dataframe

我有以下输入文件:

"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中不起作用。

3 个答案:

答案 0 :(得分:13)

这种情况正在发生,因为您的上一列是空的,因此转换为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的cols并运行代码(跳过第一个col,因为这是'Name'条目):

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

在这种情况下,我们必须在该系列上使用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)