如何获取pandas中的行索引?

2024-04-23 14:52:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个如下所示的数据帧。你知道吗

             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

Tags: 数据in目标dffordate客户len
3条回答

使用循环,可以通过测向指数[十]

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

df[df['customer']>;100]将完成此工作。。。 尽管你可以在stackoverflow上找到许多类似的答案

考虑使用^{}

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

相关问题 更多 >