2017-03-17 38 views
2

如果我用「inplace = True」重置我的Pandas數據框的索引(在the documentation之後),它將返回一個類'NoneType'。如果我用「inplace = False」重置索引,它將返回帶有新索引的數據幀。爲什麼?熊貓數據框:set_index with inplace = True會返回一個NoneType,爲什麼?

print(type(testDataframe)) 
print(testDataframe.head()) 

回報:

<class 'pandas.core.frame.DataFrame'> 
    ALandbouwBosbouwEnVisserij AantalInkomensontvangers AantalInwoners \ 
0      73780.0      None  16979120 
1      290.0      None   25243 
2      20.0      None   3555 

Set_index返回一個新的指標:

testDataframe = testDataframe.set_index(['Codering']) 
    print(type(testDataframe)) 
    print(testDataframe.head()) 

回報

<class 'pandas.core.frame.DataFrame'> 
      ALandbouwBosbouwEnVisserij AantalInkomensontvangers \ 
Codering               
NL00       73780.0      None 
GM1680       290.0      None 
WK168000       20.0      None 
BU16800000      15.0      None 

但同樣set_index與 「就地=真」:

testDataframe = testDataframe.set_index(['Codering'], inplace=True) 
print(type(testDataframe)) 
print(testDataframe.head()) 

回報

<class 'NoneType'> 
--------------------------------------------------------------------------- 
AttributeError       Traceback (most recent call last) 
<ipython-input-50-0d6304ebaae1> in <module>() 

版本信息:

python: 3.4.4.final.0 
python-bits: 64 
pandas: 0.18.1 
numpy: 1.11.1 
IPython: 5.2.2 
+1

因爲它在原位以便對象被修改,爲什麼它應該返回新的修改對象?如果你傳遞了'inplace = False',那麼它返回新的修改對象,你檢查了[docs](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html) ?非常清楚:'inplace:boolean,默認爲False。修改DataFrame(不要創建一個新對象)' – EdChum

+1

爲什麼它應該返回一些東西?它進行** inplace **修改,這意味着當前的數據幀被更新。 –

回答

2

好了,現在我明白了,謝謝你的意見!

所以inplace = True應該返回無在原始對象中進行更改。似乎在再次列出數據框時,沒有發生變化。

但是,當然,我不應該分配的返回值數據框,即

testDataframe = testDataframe.set_index(['Codering'], inplace=True) 

應該只是

testDataframe.set_index(['Codering'], inplace=True) 

否則就地指數變化的返回值(無)是數據框的新內容當然不是這個意圖。

我相信這對許多人來說都是顯而易見的,現在對我來說也是如此,但並非沒有您的幫助,謝謝!