csv AttributeError - 'numpy.ndarray'对象没有属性'drop'

uurity8g  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(79)

我计划在包含数值数据的CSV集上运行scikit-learn Stochastic Graduent Booster算法。
当调用脚本的X = Germany.drop('Status', axis='columns')时,我收到的是AttributeError: 'numpy.ndarray' object has no attribute 'drop'
我假设这个错误可能与我正在转换CSV数据pd.to_numeric的事实有关,这可能也转换了字符串头。有没有任何智能调整可以使此运行?
CSV数据具有以下结构:
x1c 0d1x的数据
相应的代码如下所示:

Germany = pd.read_csv('./Germany_filtered.csv', index_col=0)
Germany = Germany.fillna("")
Germany = pd.to_numeric(Germany.columns.str, errors='coerce')
Germany.head()

X = Germany.drop('Status', axis='columns')
y = Germany['Status']

字符串

ryevplcw

ryevplcw1#

In [167]: df = pd.DataFrame(np.arange(12).reshape(3,4),columns=['a','b','c','d'])

字符串
drop在一个嵌套框架上工作正常:

In [168]: df.drop('c',axis='columns')
Out[168]: 
   a  b   d
0  0  1   3
1  4  5   7
2  8  9  11


to_numeric生成一个numpy数组:

In [169]: x = pd.to_numeric(df.columns.str,errors='coerce')
In [170]: x
Out[170]: 
array(<pandas.core.strings.StringMethods object at 0x7fef602862b0>,
      dtype=object)
In [171]: type(x)
Out[171]: numpy.ndarray


在进入drop之前,它应该抱怨head

In [172]: x.head()
Traceback (most recent call last):
  File "<ipython-input-172-830ed5e65d76>", line 1, in <module>
    x.head()
AttributeError: 'numpy.ndarray' object has no attribute 'head'

In [173]: x.drop()
Traceback (most recent call last):
  File "<ipython-input-173-6d3a33341569>", line 1, in <module>
    x.drop()
AttributeError: 'numpy.ndarray' object has no attribute 'drop'


to_numeric docs是怎么说的?我没有使用过,但显然你不想传递df.columns.str对象。我没有使用过这个函数,但让我们尝试传递它的结构:

In [176]: x = pd.to_numeric(df,errors='coerce')
Traceback (most recent call last):
  File "<ipython-input-176-d095b0166b8f>", line 1, in <module>
    x = pd.to_numeric(df,errors='coerce')
  File "/usr/local/lib/python3.6/dist-packages/pandas/core/tools/numeric.py", line 139, in to_numeric
    raise TypeError("arg must be a list, tuple, 1-d array, or Series")
TypeError: arg must be a list, tuple, 1-d array, or Series


所以让我们传递一个列/系列:

In [177]: x = pd.to_numeric(df['a'],errors='coerce')
In [178]: x
Out[178]: 
0    0
1    4
2    8
Name: a, dtype: int64

得到的Series可以在同一列或新的列中被分配回该矩阵:

In [179]: df['a'] = x
In [180]: df
Out[180]: 
   a  b   c   d
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11


现在在我的例子框架中,没有必要做这种转换,但它应该给你给予一些东西。
让我们尝试一个真实的字符串转换:

In [195]: df['a'] = ['00','04','LS']
In [196]: df
Out[196]: 
    a  b   c   d
0  00  1   2   3
1  04  5   6   7
2  LS  9  10  11

链接的答案没有帮助:

In [197]: pd.to_numeric(df.columns.str, errors='coerce')
Out[197]: 
array(<pandas.core.strings.StringMethods object at 0x7fef602862b0>,
      dtype=object)

但我的版本确实产生了一个数字序列:

In [198]: pd.to_numeric(df['a'], errors='coerce')
Out[198]: 
0    0.0
1    4.0
2    NaN
Name: a, dtype: float64

相关问题