python pandas - 通过两个轴选择DataFrame的一部分

时间:2017-08-10 09:25:21

标签: python pandas dataframe

我们说我有这个DataFrame(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"]]

但这只会返回一个错误。

3 个答案:

答案 0 :(得分:2)

因为ix is deprecated,如果需要按位置选择(.iloc)并选择标签(.loc),则有2种可能的解决方案:

<强> 1

通过索引索引[]将位置转换为索引名称 - 因此请按标签选择索引和值,然后使用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列按ilocget_indexer列出位置,然后按DataFrame.iloc选择:

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

答案 1 :(得分:1)

您可以使用iloc

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

您可以找到文档here

答案 2 :(得分:1)

您可以尝试使用iloc()方法

可以使用.iloc索引器一起选择多个列和行。

使用iloc和DataFrame

进行多行和列选择
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).