【问题标题】:Print each n-th row of pandas dataframe打印熊猫数据帧的第 n 行
【发布时间】:2016-07-21 12:50:12
【问题描述】:

是否有一个优雅的解决方案只打印 pandas 数据帧的第 n 行?例如,我只想打印第二行。

这可以通过

i = 0
for index, row in df.iterrows():
    if ((i%2) == 0):
        print(row)
    i++

但是有没有更 Pythonic 的方式来做到这一点?

【问题讨论】:

    标签: python pandas printing


    【解决方案1】:

    使用带有iloc 的步骤参数对df 进行切片:

    print(df.iloc[::2])
    
    In [73]:
    df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
    df
    
    Out[73]:
              a         b         c
    0  0.613844 -0.167024 -1.287091
    1  0.473858 -0.456157  0.037850
    2  0.020583  0.368597 -0.147517
    3  0.152791 -1.231226 -0.570839
    4 -0.280074  0.806033 -1.610855
    
    In [77]:
    print(df.iloc[::2])
    
              a         b         c
    0  0.613844 -0.167024 -1.287091
    2  0.020583  0.368597 -0.147517
    4 -0.280074  0.806033 -1.610855
    

    【讨论】:

      猜你喜欢
      • 2018-02-28
      • 2018-07-27
      • 2019-02-23
      • 2013-12-20
      • 2017-10-02
      • 2020-05-12
      • 1970-01-01
      • 2013-09-02
      • 2019-08-25
      相关资源
      最近更新 更多