當使用負向索引時,DataFrame.ix()似乎無法分割我想要的DataFrame。使用負向索引和ix()方法切片熊貓DataFrame
我有一個DataFrame對象,並希望切片的最後2行。
In [90]: df = pd.DataFrame(np.random.randn(10, 4))
In [91]: df
Out[91]:
0 1 2 3
0 1.985922 0.664665 -2.800102 1.695480
1 0.580509 0.782473 1.032970 1.559917
2 0.584387 1.798743 0.095950 0.071999
3 1.956221 0.075530 -0.391008 1.692585
4 -0.644979 -1.959265 0.749394 -0.437995
5 -1.204964 0.653912 -1.426602 2.409855
6 1.178886 2.177259 -0.165106 1.145952
7 1.410595 -0.761426 -1.280866 0.609122
8 0.110534 -0.234781 -0.819976 0.252080
9 1.798894 0.553394 -1.358335 1.278704
一種方式做到這一點:
In [92]: df[-2:]
Out[92]:
0 1 2 3
8 0.110534 -0.234781 -0.819976 0.252080
9 1.798894 0.553394 -1.358335 1.278704
花葯的方式來做到這一點:
In [93]: df.ix[len(df)-2:, :]
Out[93]:
0 1 2 3
8 0.110534 -0.234781 -0.819976 0.252080
9 1.798894 0.553394 -1.358335 1.278704
現在我想用負索引,但有問題:
In [94]: df.ix[-2:, :]
Out[94]:
0 1 2 3
0 1.985922 0.664665 -2.800102 1.695480
1 0.580509 0.782473 1.032970 1.559917
2 0.584387 1.798743 0.095950 0.071999
3 1.956221 0.075530 -0.391008 1.692585
4 -0.644979 -1.959265 0.749394 -0.437995
5 -1.204964 0.653912 -1.426602 2.409855
6 1.178886 2.177259 -0.165106 1.145952
7 1.410595 -0.761426 -1.280866 0.609122
8 0.110534 -0.234781 -0.819976 0.252080
9 1.798894 0.553394 -1.358335 1.278704
如何在DataFrame.i中使用負向索引x()正確嗎?謝謝。
感謝您的幫助。 –