Python 如何为熊猫中的日期的时间列填充缺少的时间戳
我的时间序列数据如下:Python 如何为熊猫中的日期的时间列填充缺少的时间戳,python,pandas,time-series,Python,Pandas,Time Series,我的时间序列数据如下: print(df) ric datel timel val 0 xyz 2017-01-01 09:00:00 2 1 xyz 2017-01-01 09:04:00 5 2 xyz 2017-01-01 09:37:00 6 现在我必须将丢失的时间戳填充到09:45:00 预期产出: ric datel timel v
print(df)
ric datel timel val
0 xyz 2017-01-01 09:00:00 2
1 xyz 2017-01-01 09:04:00 5
2 xyz 2017-01-01 09:37:00 6
现在我必须将丢失的时间戳填充到09:45:00
预期产出:
ric datel timel val
0 xyz 2017-01-01 09:00:00 2
1 xyz 2017-01-01 09:01:00 nan
2 xyz 2017-01-01 09:02:00 nan
3 xyz 2017-01-01 09:03:00 nan
4 xyz 2017-01-01 09:04:00 5
...
...
37 xyz 2017-01-01 09:37:00 6
...
...
45 xyz 2017-01-01 09:45:00 nan
我所尝试的:
df1=df.resample("1 min", on ='datel').first()
其输出为:
ric datel timel val
datel
2017-01-01 xyz 2017-01-01 09:00:00 2
还尝试了pd.date\u range
,但它主要适用于datetime列。
我有两个不同的栏目日期和时间。有没有一种方法可以在不将日期和列合并到日期时间的情况下实现这一点?主要思想是由time
s创建的:
与重采样类似的解决方案
:
df['timel'] = pd.to_datetime(df['timel'])
#if missing row with 09:45:00 add it
if not (df['timel'] == pd.to_datetime('09:45:00')).any():
df.loc[len(df.index), 'timel'] = pd.to_datetime('09:45:00')
df=df.set_index('timel').resample("1min").first().reset_index().reindex(columns=df.columns)
cols = df.columns.difference(['val'])
df[cols] = df[cols].ffill()
df['timel'] = df['timel'].dt.time
print (df.head())
ric datel timel val
0 xyz 2017-01-01 09:00:00 2.0
1 xyz 2017-01-01 09:01:00 NaN
2 xyz 2017-01-01 09:02:00 NaN
3 xyz 2017-01-01 09:03:00 NaN
4 xyz 2017-01-01 09:04:00 5.0
生成日期范围为date_的日期后,您可以使用类似于以下函数的函数将其拆分 返回值可以输入df 从日期时间导入日期时间
def split_datetime(date_with_time):
"""
This function will return date and time from datetime input
"""
date_with_time = date_with_time.split(' ')
date = date_with_time[0]
time = date_with_time[1].split('.')[0]
return date, time
#Eg:
date, time = split_datetime(str(datetime.now()))
@AkshayNevrekar-很高兴能帮上忙!这正是我想要的…非常感谢!
def split_datetime(date_with_time):
"""
This function will return date and time from datetime input
"""
date_with_time = date_with_time.split(' ')
date = date_with_time[0]
time = date_with_time[1].split('.')[0]
return date, time
#Eg:
date, time = split_datetime(str(datetime.now()))