我有一个df,数据如下所示:
Time Value
60.8
Jul 2019 58.1
58.8
56.9
Oct 2019 51.8
54.6
56.8
Jan 2020 58.8
54.2
51.3
Apr 2020 52.2
<>我想根据日历年填写^ {< CD1>}变量中的空白单元格。因此: Time Value
Jun 2019 60.8
Jul 2019 58.1
Aug 2019 58.8
Sep 2019 56.9
Oct 2019 51.8
Nov 2019 54.6
Dec 2019 56.8
Jan 2020 58.8
Feb 2020 54.2
Mar 2020 51.3
Apr 2020 52.2
我看到一篇文章,其中pandas可以用于fill in numeric values,但由于我的变量不一定是以数字方式定义的,所以我不完全确定如何在这种情况下应用它
在我看来,有两种方法可以做到这一点:1)在向df写信之前修改列表。2) 修改df
我更喜欢第一种解决方案,但不确定是否可行
谢谢
我的剧本:
totalmonth=['', 'Jul 2019', '', '', 'Oct 2019', '', '', 'Jan 2020', '', '', 'Apr 2020', '']
totalvalue=['60.8', '58.1', '58.8', '56.9', '51.8', '54.6', '56.8', '58.8', '54.2', '51.3', '52.2', '48.7']
df = pd.DataFrame({'Time': totalmonth,
'Value': totalvalue})
首先使用^{} 将} 生成一个周期范围,该周期范围具有每月频率,起始周期等于计算的周期,周期数等于系列} 要以所需格式返回
Time
列转换为datetime系列t
,然后使用^{t
的length
,最后使用带有格式说明符%b %Y
的^{period_range
的字符串表示形式,请执行以下操作:详情:
结果:
好吧,我花了比我想承认的时间更长的时间。我为你的第一个答案解决了
输出:
代码:
细分
这行代码创建了一个所有有效日期的列表,并将它们以我可以运行min()函数的格式放置
new_totalmonth = [datetime.strptime(x,'%b %Y') for x in totalmonth if x != '' ]
这个打印出来的是什么
这将创建变量索引并为其分配totalmonth中最小日期的索引
index = totalmonth.index(min(new_totalmonth).strftime('%b %Y'))
这是使用列表理解
我正在使用totalmonth中最小日期的索引来操纵我要添加到totalmonth中最小月份的值范围(多少个月)
range(-index,len(totalmonth) - index)
由于最短月份(2019年7月)为指数1,我需要加上-1个月,以获得2019年6月之前的月份
因此,它可以被分解为:
取所有这些值并将它们放入每月的列表中
“时间”列中的最小值减1是开始月份,“时间”列中的最大值加2是最后一个月,目标列用
date_range()
更新以获得连续值相关问题 更多 >
编程相关推荐