Python在数据框中的许多令人满意的行中找到特定行的索引

我有一个以日期时间为索引的大数据框:

df = 
                           vol     element
2019-10-20 14:24:22       99499     8157_S1
2019-10-20 15:04:23       99500     8157_S2
2019-10-20 15:47:04       99501     8157_S1
2019-10-20 16:27:20       99502     8157_S2
2019-10-21 07:44:59       99503     8157_S1
2019-10-21 08:24:49       99504     8157_S2
2019-10-21 09:04:58       99505     8157_S2

我想为特定的vol查找特定日期的element的日期时间索引和值

item = '8157_S2'  ### element I am searching for
day  = '2019-10-21' ### date I am searching for
ses  = 1  #### which session of the day I am searching for
vol  =   df['vol'][df['element'] == item].loc[day].iloc[ses]     
dt_idx = df['vol'][df['element'] == item].loc[day].iloc[ses].index 

当前输出:

print(vol)    >> 99505
print(dt_idx) >> AttributeError: 'list' object has no attribute 'loc' 

预期输出:

print(vol)    >> 99505    
print(dt_idx) >> 2019-10-21 09:04:58 

在许多令人满意的行中找到特定行的索引,这在我的代码中可能有什么问题?

gangan123321 回答:Python在数据框中的许多令人满意的行中找到特定行的索引

请注意,您发布的数据框未包含您正在搜索的所有元素。也就是说,这应该可行。

item = '8157_S2' 
day = '2019-10-21' 
ses = 1  
selected = df[(df.element == item)].loc[day]
vol = selected.iloc[ses]["vol"]
dt_idx = selected.index.values[ses]
print(vol,dt_idx) 

也许您应该考虑将索引转换为列,使用起来会更容易。

本文链接:https://www.f2er.com/3156351.html

大家都在问