2017-08-02 189 views
0

我面對錯誤重命名大熊貓數據框柱之後:類型錯誤

B=pd.DataFrame(data=[[1,1,1],[2,2,2]],columns={'A','B','C'}) 
print(B.loc[0,'B']) 
B = B.rename(index=str,columns={'B':'B_B'}) 
print(B.loc[0,'B_B']) 

此代碼將導致如下因素輸出:

> 1 

>Traceback (most recent call last): 
    File "C:\Users\FreieL01\AppData\Local\Continuum\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code 
    exec(code_obj, self.user_global_ns, self.user_ns) 
    File "<ipython-input-29-6df9197203b9>", line 4, in <module> 
    print(B.loc[0,'B_B']) 
    File "C:\Users\FreieL01\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 1310, in __getitem__ 
    return self._getitem_tuple(key) 
    File "C:\Users\FreieL01\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 796, in _getitem_tuple 
    return self._getitem_lowerdim(tup) 
    File "C:\Users\FreieL01\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 922, in _getitem_lowerdim 
    section = self._getitem_axis(key, axis=i) 
    File "C:\Users\FreieL01\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 1482, in _getitem_axis 
    self._has_valid_type(key, axis) 
    File "C:\Users\FreieL01\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 1409, in _has_valid_type 
    key = self._convert_scalar_indexer(key, axis) 
    File "C:\Users\FreieL01\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 196, in _convert_scalar_indexer 
    return ax._convert_scalar_indexer(key, kind=self.name) 
    File "C:\Users\FreieL01\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\indexes\base.py", line 1171, in _convert_scalar_indexer 
    return self._invalid_indexer('label', key) 
    File "C:\Users\FreieL01\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\indexes\base.py", line 1284, in _invalid_indexer 
    kind=type(key))) 
TypeError: cannot do label indexing on <class 'pandas.indexes.base.Index'> with these indexers [0] of <class 'int'>} 

看來,重命名更改我的數據幀對象的類型...

回答

2

運行df.rename(index=str, ...)會導致您的數據幀索引被類型化爲字符串類型,因此它們將是字符串。你可以通過打印出來確認。

In [19]: B.index 
Out[19]: Index(['0', '1'], dtype='object') 

因此,這個工程:

In [18]: print(B.loc['0', 'B_B']) 
1 

如果你不想這樣,只是不重命名你的B列時傳遞一個index屬性,像這樣:

B = B.rename(columns={'B':'B_B'}) 
+0

正確。 @LazlooXp,你的預期結果是什麼? – Alexander

+1

@亞歷山大投注是OP在google上發現了這個代碼,並在沒有完全理解其含義的情況下運行它... –

+0

THX。說得通! –