python - 以毫秒为单位分配时间以获得平滑曲线

标签 python pandas dataframe datetime

我有一个数据框,其中一列包含日期时间。日期时间是秒。我需要自动将毫秒添加到秒中,因为每个秒值都有多个值。 例如-2019 年 2 月 21 日下午 3:50:41,我有这个时间戳 35 次。如果我可以将毫秒添加到这个时间戳,那么当我绘制曲线时,它将是一条平滑的曲线。每个第二个值都有不同数量的实例。

最佳答案

可以尝试groupby修改日期

df = pd.DataFrame({'date': pd.to_datetime(['Feb 21, 2019 3:50:41 PM']*35 + 
                                          ['Feb 21, 2019 3:50:42 PM']*100),
                        'val': np.linspace(0,1,135)})

def time_shift(s):
    count = len(s)
    deltas = pd.timedelta_range('0ms', '1000ms',
                                periods=count+1, closed='left')
    return s + deltas

df.date = df.groupby(['date']).date.transform(time_shift)

plt.plot(df.date, df.val)

原始数据帧图:

![enter image description here

按毫秒缩放后的绘图:

![enter image description here

移位后的数据框:

df.tail(5)

+-----+-------------------------------+----------+
|     | date                          |      val |
|-----+-------------------------------+----------|
| 130 | 2019-02-21 15:50:42.959595959 | 0.970149 |
| 131 | 2019-02-21 15:50:42.969696969 | 0.977612 |
| 132 | 2019-02-21 15:50:42.979797979 | 0.985075 |
| 133 | 2019-02-21 15:50:42.989898989 | 0.992537 |
| 134 | 2019-02-21 15:50:43           | 1        |
+-----+-------------------------------+----------+

关于python - 以毫秒为单位分配时间以获得平滑曲线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56364946/

相关文章:

python - 写入 excel 文件时超过 url 数量

python - 使用相同的键、多个值追加到字典

python - 如何访问新数据框中的单元格?

python - 删除 DataFrame 中满足针对多列评估的条件的行

python - 在Django项目中获取TypeError错误

python - 如何使用标准库在 python 中解析格式错误的 HTML

python - 将不规则时间序列转换为python pandas中的每小时数据

python - 如何展平列中的层次索引

python - 如何从多索引 pandas 数据框中选择连续行?

python - 根据条件填充数据框行的值