2017-03-17 39 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) 

否则就地指数变化的返回值(无)是数据框的新内容当然不是这个意图。

我相信这对许多人来说都是显而易见的,现在对我来说也是如此,但并非没有您的帮助,谢谢!