python - 根据数据集中的值返回最早日期
问题描述
我正在处理记录世界各国选举和领导人的 REIGN 数据 ( https://www.oneearthfuture.org/datasets/reign )
在数据集中,有一个布尔选举预期变量,它从 0 变为 1,表示预计至少在未来 6 个月内会进行选举,可能会更早。
我想创建一个新列,它返回预期(第 N 列)变为 1 的最早日期(即第一次预期选举的时间)。
因此,例如,阿富汗在列中,我们在 2014 年和 2017 年进行了选举。在 N 列中,我们看到它在 2014 年 10 月从 0 变为 1(预期选举),然后我们看到它在 2014 年 7 月回到 0 (选举结束)直到它在 2019 年 1 月回到 1(预期选举),然后在 2019 年 10 月回到 0。
因此,如果成功,我会将 2014 年 10 月(预计选举)和 2019 年 1 月(预计选举)作为新列中的选举公告日期以及预计选举的任何其他日期。
目前我有以下内容:
#bringing in Reign CSV
regin = pd.read_csv('REIGN_2021_7(1).csv')
#shows us the first 5 rows to make sure they look good
print(regin.head())
#show us the rows and columns in the file
regin.shape
#Getting our index
print(regin.columns)
#adding in a date column that concatenates year and month
regin['date'] = pd.to_datetime(regin[['year', 'month']].assign(DAY=1))
regin.head
#def conditions(s):
if (s['anticipation'] == 1):
return (s['date'])
else:
return 0
regin['announced_date'] = regin.apply(conditions, axis=1)
print(regin.head)
对我来说最大的问题是,虽然这会返回 1 出现的日期,但它不会显示最早的日期。我如何遍历预期列并返回最短日期,但要多次这样做,因为一个国家多年来将进行多次选举,因此在 N 列中有多个实例代表一个预期开启的国家(1)和关闭(0)。
提前感谢您的任何帮助!让我知道是否有任何不清楚的地方。
解决方案
如果您可以遍历您的日期,您可能会想要使用该datetime
模块(假设所有日期都具有相同的格式):
from datetime import datetime
[...]
earliest_date = datetime.today()
[... loop over data, by country ...]
date1 = datetime.strptime(input_date_string1, date_string_format)
if date1 < earliest_date:
earliest_date = date1
[...]
该模块支持(除其他外):
- 从字符串中解析日期对象 (
.strptime(in_str, format)
) - 日期对象的比较 (
date1 > date2
) - 当前日期 + 时间的日期时间对象 (
.today()
) - 来自任意日期的日期时间对象 (
.date(year, month, day)
)
推荐阅读
- javascript - 以角度保存和获取firebase不起作用
- c++ - 通过函数参数确定结构成员
- swift - 如何在 macOS 中使用 iosMath 数学库?
- node.js - 当我从nodejs发送它时,有什么方法可以隐藏来自浏览器的获取请求响应?
- heap-memory - 堆和栈内存划分的主要来源是什么?
- box2d - 如何在 LOVE2D 中设置车轮关节
- ios - 如何让 UIDatePicker 在 Swift 4 中更新文本字段和数据库
- math - 朝着圆上的特定角度迭代
- django - 如何在所有页面上获取 django 分页唯一项目 ID?
- pip - pip install apache-airflow 然后气流 initdb 在新的虚拟环境中:SyntaxError