2017-08-10 141 views
1
選擇數據框的一部分

比方說,我有這樣的數據幀(DF):蟒蛇大熊貓 - 通過兩個軸

  A   B   C   D 
2013-01-05 0.785969 1.381685 -0.547796 -1.155653 
2013-01-03 1.322663 0.343046 0.634790 -1.037137 
2013-01-02 -0.132650 -0.030817 0.613637 -1.088943 
2013-01-01 1.261990 -0.078801 0.425255 0.105730 
2013-01-06 0.012660 -0.259059 -0.729147 0.122075 
2013-01-04 -0.638154 -0.952552 0.895817 -0.749750 

我知道如何讓列A和B的橫截面和所有行:

df.loc[:,["A", "B"]] 

但是,如何獲得某些列的橫截面和某些行

我試過的東西一樣

df.loc[[2:], ["A", "B"]] 

但只是返回一個錯誤。

回答

1

您可以使用iloc

df.iloc[2:, [0, 1]] 

您可以找到的文檔here

+0

非常好,謝謝! –

2

因爲ix is deprecated,你有2個可能的解決方案,如果需要通過標籤與選擇位置(.iloc)選擇(的.loc):

轉換位置索引名由seelcting指數[] - 因此選擇索引和值由標籤,然後使用DataFrame.loc

print (df.index[2]) 
2013-01-02 00:00:00 

df = df.loc[df.index[2]:, ["A", "B"]] 
print (df) 
        A   B 
2013-01-02 -0.132650 -0.030817 
2013-01-01 1.261990 -0.078801 
2013-01-06 0.012660 -0.259059 
2013-01-04 -0.638154 -0.952552 

2.

CONVER列名由iloc和位置由get_indexer然後通過DataFrame.iloc seelct:

print (df.columns.get_indexer(["A", "B"])) 
[0 1] 

df = df.iloc[2:, df.columns.get_indexer(["A", "B"])] 
print (df) 
        A   B 
2013-01-02 -0.132650 -0.030817 
2013-01-01 1.261990 -0.078801 
2013-01-06 0.012660 -0.259059 
2013-01-04 -0.638154 -0.952552 
+0

對不起,我以前的評論,是我不好。它工作完美,謝謝! –

+0

超級,高興能幫助! – jezrael

1

你可以嘗試使用ILOC()方法

多列和行可以使用.iloc索引選擇在一起。

多行和列的選擇,使用和ILOC數據框

data.iloc[0:5] # first five rows of dataframe 
data.iloc[:, 0:2] # first two columns of data frame with all rows 
data.iloc[[2:], ["A","B"]] # 1st, 4th, 7th, 25th row + 1st 6th 7th columns. 
data.iloc[0:5, 5:8] # first 5 rows and 5th, 6th, 7th columns of data frame (county -> phone1).