2015-12-17 43 views
2

我創建了一個數據幀:冒號(:)如何在python&pandas中工作?

import pandas as pd 
data = pd.DataFrame({'a':range(1,11),'b':['m','f','m','m','m','f','m','f','f','f'],'c':np.random.randn(10)}) 

它看起來像:

a b   c 
0 1 m 0.495439 
1 2 f 1.444694 
2 3 m 0.150637 
3 4 m -1.078252 
4 5 m 0.618045 
5 6 f -0.525368 
6 7 m 0.188912 
7 8 f 0.159014 
8 9 f 0.536495 
9 10 f 0.874598 

當我想選擇一些行,我跑

data[:2] or data.ix[2] 

但是當我嘗試:

se = range(2) 
data[se] 

有一個錯誤:

KeyError: 'No column(s) named: [0 1]' 

我知道數據框中選擇一個山坳作爲default.What發生了,當我運行data[se]? 冒號(:)如何在Python中工作?

+1

提供一個列表嘗試從列中選擇(並且沒有名稱爲0或1的列),同時提供像':2'的切片行 – joris

回答

4

我從來沒有用過,你用range(2)大熊貓但是從我在manual

With DataFrame, slicing inside of [] slices the rows. This is provided largely as a convenience since it is such a common operation.

In [32]: df[:3] 
Out[32]: 
        A   B   C   D 
2000-01-01 -0.282863 0.469112 -1.509059 -1.135632 
2000-01-02 -0.173215 1.212112 0.119209 -1.044236 
2000-01-03 -2.104569 -0.861849 -0.494929 1.071804 

In [33]: df[::-1] 
Out[33]: 
        A   B   C   D 
2000-01-08 -1.157892 -0.370647 -1.344312 0.844885 
2000-01-07 0.577046 0.404705 -1.715002 -1.039268 
2000-01-06 0.113648 -0.673690 -1.478427 0.524988 
2000-01-05 0.567020 -0.424972 0.276232 -1.087401 
2000-01-04 -0.706771 0.721555 -1.039575 0.271860 
2000-01-03 -2.104569 -0.861849 -0.494929 1.071804 
2000-01-02 -0.173215 1.212112 0.119209 -1.044236 
2000-01-01 -0.282863 0.469112 -1.509059 -1.135632 

閱讀在你的榜樣切片(在Python [::]符號可以發現here的一個很好的解釋。現在,讓你[0, 1]列表。我想你需要的是data[0:1]DataFrame並獲得行0和1這是一樣的data[:1]省略爲零。如果你想例如行3,4和5這將是data[3:5]

此外,看着手冊中的一些例子,你可以使用一步,所以:

  • data[::2]給你的每2行
  • data[::-1]回報以相反的順序
  • 合併範圍內的所有行和步驟:data[0:10:2]將導致行0,2,4,6,8和10

希望它hel PS

+0

謝謝。如果我想選擇這些行[2,4,3,5 ,1],我運行df [slice([2,4,3,5,1])],這是一個錯誤。我剛剛使用了df.ix [2,4,3,5,1]。一個不同的方式來做到這一點? –

+0

你需要它們嗎?你只能用'[]'做一個單一的範圍,不能改變跳過行或反向的順序(據我所知)。做'df [1:5]'應該給你你需要的行,但不是按你想要的順序...... – urban

1

[開始:限制:步驟]語法被稱爲切片。 您可以使用slice()功能很容易地創建一個切片的一個實例:

class slice(stop)

class slice(start, stop[, step])

Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default). They have no other explicit functionality; however they are used by Numerical Python and other third party extensions. Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.

在你的情況,你可以寫這樣的事返回前兩排

se = slice(None, 2) 
data[se] 
1
>>> data.ix[range(2)] 
    a b   c 
0 1 m -0.323834 
1 2 f 0.159787