下面是一个示例代码,演示如何在按年份和月份分组的数据中创建缺失月份的行:
import pandas as pd
# 创建示例数据
data = {'year': [2019, 2019, 2020, 2020, 2021],
'month': [1, 3, 2, 4, 1],
'value': [10, 20, 30, 40, 50]}
df = pd.DataFrame(data)
# 将年份和月份设置为索引
df.set_index(['year', 'month'], inplace=True)
# 创建包含所有年份和月份的多级索引
index = pd.MultiIndex.from_product([df.index.levels[0], range(1, 13)], names=['year', 'month'])
# 重新索引数据框,使用新的多级索引
df = df.reindex(index)
# 打印结果
print(df)
输出结果为:
value
year month
2019 1 10.0
2 NaN
3 20.0
4 NaN
5 NaN
6 NaN
7 NaN
8 NaN
9 NaN
10 NaN
11 NaN
12 NaN
2020 1 NaN
2 30.0
3 NaN
4 40.0
5 NaN
6 NaN
7 NaN
8 NaN
9 NaN
10 NaN
11 NaN
12 NaN
2021 1 50.0
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 NaN
9 NaN
10 NaN
11 NaN
12 NaN
在这个示例中,我们首先创建了一个包含年份、月份和值的示例数据框。然后,我们将年份和月份设置为索引,以便按年份和月份进行分组。接下来,我们使用from_product
函数创建了包含所有年份和月份的多级索引。最后,我们使用reindex
函数重新索引数据框,使用新的多级索引来创建缺失的月份行。
上一篇:按年份和月份范围筛选数据