我想“扩展”我的行:
+-------------+---------+-------+-------+
| 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,9.00.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补充“缺失”。我怎么能这样做?
我正在使用python 3.6和pandas库。
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'])
Concat两个数据帧(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'])