代码之家  ›  专栏  ›  技术社区  ›  LetzerWille

一个命令中的行选择、loc掩蔽和切片

  •  0
  • LetzerWille  · 技术社区  · 6 年前

    我希望能够在一个命令行选择,掩蔽和切片。
    目前我使用两个步骤。

    df
    Out[126]: 
                       A         B         C         D
    2018-06-24 -2.198394  0.224622  0.990230  0.390609
    2018-06-25  0.644388 -1.196015  1.859241  0.444789
    2018-06-26  0.708848  0.780761  1.599977 -0.489875
    2018-06-27 -0.465428 -1.540811 -2.384975  0.460398
    2018-06-28 -1.061571  1.781373 -1.934853  0.895916
    2018-06-29  0.613139  0.446043 -0.061014 -1.182526
    2018-06-30 -0.579179  0.630916  0.689561  0.124637
    2018-07-01  0.199385  1.230230 -2.075407  1.051498
    2018-07-02  0.377676  0.343647  1.226058  0.182071
    2018-07-03  0.478328 -0.791613 -2.247531 -1.213415
    
    df03 = df.iloc[0:3]
    
    df03.loc[(df.C > 0) & (df.B > 0), 'A':'C']
    Out[128]: 
                       A         B         C
    2018-06-24 -2.198394  0.224622  0.990230
    2018-06-26  0.708848  0.780761  1.599977
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   jezrael    6 年前

    不不可能,需要为检查索引值创建布尔掩码,如 cookbook 是的。

    我认为您的解决方案很好,但是如果需要一行解决方案,则需要新的条件来比较 arange :

    df = df.loc[(df.C > 0) & (df.B > 0) & (np.arange(len(df)) < 3), 'A':'C']
    

    细节 以下内容:

    print ((np.arange(len(df)) < 3))
    [ True  True  True False False False False False False False]
    

    备选方案:

    print ((df.reset_index().index < 3))
    [ True  True  True False False False False False False False]
    
    df = df.loc[(df.C > 0) & (df.B > 0) & (df.reset_index().index < 3), 'A':'C']