首页 > 解决方案 > 根据不同列的值对数据框执行查找

问题描述

有这样的数据框 -

df = {'Request': [0, 0, 1, 0, 1, 0, 0],
 'Time': ['16:00', '17:00', '18:00', '19:00', '20:00', '20:30', '24:00'],
 'grant': [3, 0, 0, 5, 0, 0, 5]}

pd.DataFrame(df).set_index('Time')

    Out[16]: 
       Request  grant
Time                 
16:00        0      3
17:00        0      0
18:00        1      0
19:00        0      5
20:00        1      0
20:30        0      0
24:00        0      5

“请求”列中的值是布尔值,表示是否提出了请求。1 = 请求 0 = 无请求。“授予”列中的值表示初始授予大小。

我想计算每个请求的请求和授权之间的时间。所以在这种情况下,他们将是 19:00 - 18:00 = 1 小时和 24:00-20:00 = 4 小时。有没有办法使用 pandas 轻松地对大型数据集执行此操作?

标签: pythonpandas

解决方案


我会这样做:

df = {'Request': [0, 0, 1, 0, 1, 0, 0],
     'Time': ['16:00', '17:00', '18:00', '19:00', '20:00', '20:30', '24:00'],
     'grant': [3, 0, 0, 5, 0, 0, 5]}

df = pd.DataFrame(df) #create DataFrame

#get rid of any rows have neither a grant nor request
df = df[(df[['grant', 'Request']].T != 0).any()] 

#change the time in HH:MM to number of minutes
df['Time'] = df['Time'].str.split(":").apply(lambda x: int(x[0])*60 + int(x[1]))

#get the difference between those times
df['timeElapsed'] = df['Time'].diff()

#filter out the requests to only get the grants and their times. 
#Also, drop the NA from the first line.
df = df[(df[['grant']].T != 0).any()].dropna()

#drop all columns except timeElapsed and Grant
df = df[['timeElapsed', 'grant']]

那么输出看起来像这样,timeElaped 以分钟为单位:

   timeElapsed  grant
3         60.0      5
6        240.0      5

推荐阅读