如何使用python有效地填充“缺失时间模式”和“填充它们”具有特定值?
Posted
技术标签:
【中文标题】如何使用python有效地填充“缺失时间模式”和“填充它们”具有特定值?【英文标题】:How to fill the "missing time pattern" and "fill them" with particular value efficiently with python? 【发布时间】:2019-02-15 17:56:49 【问题描述】:我想从以下位置“扩展”我的行:
+-------------+---------+-------+-------+
| Week Number | Weekday | Time | Speed |
+-------------+---------+-------+-------+
| 1 | Monday | 09.00 | 2 |
| 1 | Monday | 12.00 | 2 |
| 1 | Monday | 14.00 | 2 |
| 1 | Monday | 15.00 | 1 |
| 1 | Tuesday | 08.00 | 4 |
| 1 | Tuesday | 10.00 | 2 |
| 1 | Tuesday | 11.00 | 3 |
| 1 | Tuesday | 13.00 | 2 |
+-------------+---------+-------+-------+
每天进入以下模式: 08.00, 09.00, 10.00, 11.00, 12.00, 13.00, 14.00, 15.00
+-------------+---------+-------+-------+
| Week Number | Weekday | Time | Speed |
+-------------+---------+-------+-------+
| 1 | Monday | 08.00 | 0 |
| 1 | Monday | 09.00 | 2 |
| 1 | Monday | 10.00 | 0 |
| 1 | Monday | 11.00 | 0 |
| 1 | Monday | 12.00 | 2 |
| 1 | Monday | 13.00 | 0 |
| 1 | Monday | 14.00 | 2 |
| 1 | Monday | 15.00 | 1 |
| 1 | Tuesday | 08.00 | 4 |
| 1 | Tuesday | 09.00 | 0 |
| 1 | Tuesday | 10.00 | 2 |
| 1 | Tuesday | 11.00 | 3 |
| 1 | Tuesday | 12.00 | 0 |
| 1 | Tuesday | 13.00 | 3 |
| 1 | Tuesday | 14.00 | 0 |
| 1 | Tuesday | 15.00 | 0 |
+-------------+---------+-------+-------+
并用 0 填充“缺失”。 我该怎么办?
我正在使用带有 pandas 库的 python 3.6。
【问题讨论】:
time
列的 dtype 是什么?
timedelta64[ns]。有什么想法吗?
【参考方案1】:
import pandas as pd
df = pd.DataFrame('Week Number': 1, 'Weekday': ['Monday'] * 4 + ['Tuesday'] * 4, 'Time':['09.00', '12.00', '14.00', '15.00'] * 2,
'Speed': [2, 4] * 4)
假设 times
、days
和 week_nums
都是扩展 DataFrame 的值
times = ['08.00', '09.00', '10.00', '11.00', '12.00', '13.00', '14.00', '15.00']
days = ['Monday', 'Tuesday']
week_nums = [1]
使用Speed = 0
创建所有可能组合的DataFrame
from itertools import product
df_combinations = pd.DataFrame(list(product(, days, times, [0])), columns=['Week Number', 'Weekday', 'Time', 'Speed'])
连接两个数据框(df_combinations
必须是重复删除的第二个!)
df_new = pd.concat([df, df_combinations], ignore_index=True, sort=False)
创建重复的二进制掩码,删除它们并对数据帧进行排序
df_new = df_new[~df_new.duplicated(subset=['Week Number', 'Weekday', 'Time'], keep='first')]
df_new.sort_values(['Week Number', 'Weekday', 'Time'])
【讨论】:
以上是关于如何使用python有效地填充“缺失时间模式”和“填充它们”具有特定值?的主要内容,如果未能解决你的问题,请参考以下文章
如何在python 3中有效地将原始字节写入numpy数组数据