python - Python - 通过匹配/比较来自多个数据帧的变量来计算两个日期之间发生的记录数
问题描述
我有两个数据框:一个包含社交媒体 (SM) 帖子,另一个包含用于完成调查的时间戳响应和调查完成前 60 天的时间(对于示例数据框而言不准确,不要认为它会影响方法--timedelta(days=60)
使用pd.datetime
) 计算。
social_media
:
邮政 | 发布时间 | FIPS |
---|---|---|
'啊' | 2019-02-09 20:28:26 | 01010 |
'bbb' | 2019-01-11 14:11:30 | 01010 |
“抄送” | 2017-11-23 09:10:11 | 99999 |
survey
:
比赛时间 | 60天前 | FIPS |
---|---|---|
2019-01-08 11:28:26 | 2018-12-09 20:28:26 | 01010 |
2019-01-04 07:30:21 | 2018-11-11 14:11:30 | 01010 |
2017-07-14 07:30:21 | 2017-09-23 09:10:11 | 88888 |
2019-06-21 11:43:17 | 2019-04-23 09:10:11 | 77777 |
每行包含受访者所在县的 FIPS 代码,以及他们的调查回复的时间戳。每个 FIPS 可能与一个或多个调查对象相关联。数据被去识别化,因此没有响应者 ID,只有 FIPS 和时间戳。因此,我假设如果一个县有多个受访者在同一时间范围内完成调查,则会出现重复计算——这不是一个大问题。
我的目标是计算每个受访者的调查完成时间在每个调查完成日期的过去 60 天内创建的 SM 帖子的数量。我有以下代码似乎可以工作,但由于数据集非常大,需要很长时间。
import pandas as pd
import datetime
import itertools
full_count = []
for i, surveyrow in survey.iterrows():
count = 0
for j, SMrow in social_media.iterrows():
if surveyrow['FIPS'] == SMrow['FIPS']:
if surveyrow['completionTime']>=SMrow['postedTime']:
if surveyrow['60daysprior']<=SMrow['postedTime']:
count+=1
else:
count+=0
else:
count+=0
else:
count+=0
full_count.append(str(count))
survey['count'] = full_count
我能做些什么来优化这段代码?我正在使用 Python 3 和pandas
. 谢谢!!
更新:此代码提高了速度,但仍然需要大量时间:
survey_fips = survey['FIPS']
social_media_fips = social_media['FIPS']
survey_tm_finish = survey['completionTime']
social_media_postedTime = social_media['postedTime']
survey_tm_finish_minus60 = survey['60daysprior']
full_count = []
for i, j, k in zip(survey_fips, survey_tm_finish, survey_tm_finish_minus60):
count = 0
for a, b in zip(social_media_fips, social_media_postedTime):
if i == a:
if j>=b:
if k<=b:
count+=1
else:
count
else:
count
else:
count
full_count.append(str(count))
解决方案
推荐阅读
- python - 从蒙版图像区域获取值 OpenCV Python
- clock - 日期时间和 if 语句与
- c - 编写一个程序,将三个整数作为输入,并打印第二大数字
- android - 如何计算android中两个时间选择器之间的时间差?
- python - 为字典中的每个项目仅选择一个同义词同义词
- python - 引发异常后,python 回溯如何运行?
- python - 当 url 无效时 Request.get 抛出 ConnectionError 并且 python 脚本终止
- javascript - 为什么我收到错误“无法生成令牌。使用 Nodemailer 时检查您的身份验证选项?
- unity3d - unity Setactive 函数在指针事件中不起作用
- javascript - Nodejs Express - 有没有办法将以下代码简化为更简单的代码?