2017-07-14 96 views
0

如果我有一個數據框並重命名該列,我無法通過其新名稱訪問該列。重命名後爲什麼我不能訪問熊貓列?

爲了說明參見示例:

import pandas as pd 
df = pd.DataFrame({'a':[1,2], 'b': [10,20]}) 
df 
    a b 
0 1 10 
1 2 20 
df['a'] 
0 1 
1 2 

現在,如果我重命名的列 'A' 爲以建議here

df.columns.values[0] = 'newname' 
df 
    newname b 
0  1 10 
1  2 20 

現在,讓我們嘗試訪問使用「NEWNAME」

df['newname'] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/gpfs0/export/opt/anaconda-2.3.0/lib/python2.7/site-packages/pandas/core/frame.py", line 1797, in __getitem__ 
    return self._getitem_column(key) 
    File "/gpfs0/export/opt/anaconda-2.3.0/lib/python2.7/site-packages/pandas/core/frame.py", line 1804, in _getitem_column 
    return self._get_item_cache(key) 
    File "/gpfs0/export/opt/anaconda-2.3.0/lib/python2.7/site-packages/pandas/core/generic.py", line 1084, in _get_item_cache 
    values = self._data.get(item) 
    File "/gpfs0/export/opt/anaconda-2.3.0/lib/python2.7/site-packages/pandas/core/internals.py", line 2851, in get 
    loc = self.items.get_loc(item) 
    File "/gpfs0/export/opt/anaconda-2.3.0/lib/python2.7/site-packages/pandas/core/index.py", line 1572, in get_loc 
    return self._engine.get_loc(_values_from_object(key)) 
    File "pandas/index.pyx", line 134, in pandas.index.IndexEngine.get_loc (pandas/index.c:3824) 
    File "pandas/index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas/index.c:3704) 
    File "pandas/hashtable.pyx", line 686, in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12280) 
    File "pandas/hashtable.pyx", line 694, in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12231) 
KeyError: 'newname' 

列然而,我仍然可以通過舊名稱訪問列。

df['a'] 
0 1 
1 2 
Name: a, dtype: int64 

看來,我已經改變了列的名義名字,但這種變化並沒有通過傳播到用來尊重的數據幀結構柱的字典。

問題:爲什麼會發生這種情況,我該如何解決?

回答

1

您可以使用此方法:

In [131]: df.columns = ['newname'] + df.columns.tolist()[1:] 

In [132]: df 
Out[132]: 
    newname b 
0  1 10 
1  2 20 

或:

In [136]: df = df.rename(columns={df.columns.tolist()[0]:'newname'}) 

In [137]: df 
Out[137]: 
    newname b 
0  1 10 
1  2 20