python - 根据不同列的值对数据框执行查找
问题描述
有这样的数据框 -
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 轻松地对大型数据集执行此操作?
解决方案
我会这样做:
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
推荐阅读
- laravel - Supervisord & Laravel - has been attempted too many times or run too long
- python - 我的代码有什么问题?添加“不”后失败。采取的步骤'到代码中
- spring-boot - 如何将 Spring log4j 与 messages.properties 集成?
- selenium - Heroku 脚本托管
- ios - 使用 iCloud PHAsset 请求 AVAsset 返回一个没有 VideoTracks 的 AVAsset
- r - Windows 10 中 R 中的 TensorFlow 安装
- python - Multi-Index - Not able to sort multiple indexes in a single line
- c# - 在 Identity.UI/3.1.8 中登录 Facebook 和 google
- python - Pipreqs 生成 requirements.txt 不起作用
- python - 如何在 WTForms 中使用 SelectField 的函数参数空白?