【问题标题】:How can I get index of rows in pandas?如何获取 pandas 中的行索引?
【发布时间】:2017-10-12 12:41:20
【问题描述】:

我有一个如下所示的数据框。

             customers       ...
Date                                             
2006-01-03          98       ...
2006-01-04         120       ...   
2006-01-05         103       ...  
2006-01-06          95       ... 
2006-01-09         103       ...

我想获取客户数量超过 100 的行并打印出来。

for x in range(len(df)):
    if df['customers'].iloc[x] > 100:
        print(df['customers'].iloc[x]) 

但我不知道如何打印出满足条件的行的日期(索引)。我的目标是像这样打印出来:

2006-01-04
120
2006-01-05
103
2006-01-09
103

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    考虑使用query()

    print(df)
             Date  customers
    0  2006-01-03         98
    1  2006-01-04        120
    2  2006-01-05        103
    3  2006-01-06         95
    4  2006-01-09        103
    
    df.query('customers > 100')
             Date  customers
    1  2006-01-04        120
    2  2006-01-05        103
    4  2006-01-09        103
    

    要获得您指定的确切输出格式,请遍历 query() 结果:

    for date, customer in df.query('customers > 100').values:
        print(date)
        print(customer)
    
    2006-01-04
    120
    2006-01-05
    103
    2006-01-09
    103
    

    【讨论】:

    • 日期列是这个数据框的索引。你是否知道如何获取每个 Date 满足条件的行的 customers 值?
    • 我不确定我是否理解您的要求。如果Date 是索引,则query() 函数的工作方式相同。如果您只想要符合您的条件的日期(这不是 OP 所需的输出显示的内容),那么只需提取 index:df.query('customers > 100').index.values
    【解决方案2】:

    df[df['customer'] > 100] 将完成这项工作... 虽然你可以在stackoverflow上找到很多类似的答案

    【讨论】:

      【解决方案3】:

      使用循环,您可以使用 df.index[x] 获取输出中的数据

      for x in range(len(df)):
          if df['customers'].iloc[x] > 100:
              print(df.index[x])
              print(df['customers'].iloc[x])
      
      2006-01-04
      120
      2006-01-05
      103
      2006-01-09
      103
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-03
        • 2022-06-11
        • 2013-05-17
        • 1970-01-01
        • 2013-12-10
        • 2023-03-03
        • 2014-06-06
        相关资源
        最近更新 更多