python - Pandas: Is there anyway to fill Nan's in a column with continuous dates
问题描述
I have a dataframe like so:
Date Day_number
10/03/2020 1
11/03/2020 2
12/03/2020 3
13/03/2020 4
Nan 5
Nan 6
Nan 7
I want to replace the Nans with a continuation of the dates. There around 100 rows in the dataset.
So I want the df to look like this.
Date Day_number
10/03/2020 1
11/03/2020 2
12/03/2020 3
13/03/2020 4
14/03/2020 5
15/03/2020 6
16/03/2020 7
. .
. .
Any help would be greatly appreciated. Thanks in advance.
解决方案
IIUC
df.Date=pd.to_datetime(df.Date,errors='coerce',dayfirst=True)
s=df.Date.isnull()
df.loc[s,'Date']=pd.to_timedelta(df.Day_number.diff()[s].cumsum(),unit='day')+df['Date'].ffill()
df
Date Day_number
0 2020-03-10 1
1 2020-03-11 2
2 2020-03-12 3
3 2020-03-13 4
4 2020-03-14 5
5 2020-03-15 6
6 2020-03-16 7
推荐阅读
- prometheus - Alertmanager webhook 在单独定义时不起作用
- amp-html - 如何让 amp-youtube 视频在按钮按下时播放?on=tap:id.play 不能始终如一地工作
- python - 在 Maya 中创建递归函数以获取层次结构
- wordpress - 想在wordpress中找到价格表的id,想在购物车页面中获取价格表的详细信息
- prolog - Prolog 中的一阶谓词逻辑:使用签名和算术项
- java - 是否可以停止隐式转换?
- node.js - 更新 MERN 堆栈中的模式
- arrays - 在Objective-C中的嵌套类型对象的对象类型上找不到属性
- python - Python 字典 - 如果键相同,则创建对应值列表(字符串数据类型)
- php - 将 TINYINT 添加到 Doctrine SQL 类型