代码之家  ›  专栏  ›  技术社区  ›  P. Prunesquallor

python pandas-通过两个轴选择数据帧的一部分

  •  1
  • P. Prunesquallor  · 技术社区  · 9 年前

                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
    

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

    但是如何得到一些柱的横截面呢 ?

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

    3 回复  |  直到 9 年前
        1
  •  2
  •   jezrael    9 年前

    因为 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.

    将列名称转换为位置 iloc 通过 get_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
    
        2
  •  1
  •   Mohamed Ali JAMAOUI    9 年前

    您可以使用 iloc

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

    您可以找到文档 here .

        3
  •  1
  •   R Palanivel-Tamilnadu India    9 年前

    您可以尝试使用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).