pandas 错误“只能使用带字符串值的.str访问器" [英] Pandas error "Can only use .str accessor with string values"

查看:722
本文介绍了 pandas 错误“只能使用带字符串值的.str访问器"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下输入文件:

"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

这在熊猫0.14中可以正常使用,但在熊猫0.17.0中则无效.

This worked OK in pandas 0.14 but does not work in pandas 0.17.0.

推荐答案

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

It's happening because your last column is empty so this becomes converted to 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  

如果将范围切成最后一行,它将起作用:

If you slice your range up to the last row then it works:

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并运行代码(跳过第一个cols,因为这是"Name"条目):

Alternatively you can just select the cols that are object dtype and run the code (skipping the first col as this is the 'Name' entry):

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

这篇关于 pandas 错误“只能使用带字符串值的.str访问器"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆