Python 从数据帧中的序列中查找缺少的编号
我的数据框中有以下数据:Python 从数据帧中的序列中查找缺少的编号,python,pandas,dataframe,missing-data,Python,Pandas,Dataframe,Missing Data,我的数据框中有以下数据: uniquecode一年一个月名称销售 1029 2020 5 ABC 10 1029 2020 6 ABC 20 1029 2020 10 ABC 30 1029 2020 11 ABC 35 1029 2020 12 ABC 38 1050 2020 4 DEF 39 1050 2020 5 DEF 40 1050 2020 6 DEF 31 1050 2020 7 DEF 45 1050 2020 8 DEF 55 1079 2020 4 GHI 65 1079
uniquecode一年一个月名称销售
1029 2020 5 ABC 10
1029 2020 6 ABC 20
1029 2020 10 ABC 30
1029 2020 11 ABC 35
1029 2020 12 ABC 38
1050 2020 4 DEF 39
1050 2020 5 DEF 40
1050 2020 6 DEF 31
1050 2020 7 DEF 45
1050 2020 8 DEF 55
1079 2020 4 GHI 65
1079 2021 2 GHI 75
10810 2021 1 XYZ 85
假设我们坐在3月21日。对于2021年的月上限,我们将限制在3月21日减去1日,即2月21日
我们看到数据被分成不同的唯一代码组1。对于每组uniquecode1,我们在“月”列中缺少值
请告诉我您可能需要的其他详细信息。您可以将
年
和月
转换为日期时间,然后添加所有缺少的组合,对于不存在的值,使用新的0
,对于原始格式:
df['dates'] = pd.to_datetime(df[['year','month']].assign(day=1))
df = (df.set_index(['uniquecode1','Name', 'dates'])['Sale']
.unstack(fill_value=0)
.stack()
.reset_index(name='Sale'))
添加年份和月份的最后期限:
df = df.assign(year = df['dates'].dt.year, month = df['dates'].dt.month)
print (df.head())
uniquecode1 Name dates Sale year month
0 1029 ABC 2020-04-01 0 2020 4
1 1029 ABC 2020-05-01 10 2020 5
2 1029 ABC 2020-06-01 20 2020 6
3 1029 ABC 2020-07-01 0 2020 7
4 1029 ABC 2020-08-01 0 2020 8
但不幸的是,缺少了09-2020
,因此有必要添加:
您可以将
year
withmonth
转换为datetimes,然后添加所有缺少的组合,对于不存在的值,使用新的0
,对于原始格式:
df['dates'] = pd.to_datetime(df[['year','month']].assign(day=1))
df = (df.set_index(['uniquecode1','Name', 'dates'])['Sale']
.unstack(fill_value=0)
.stack()
.reset_index(name='Sale'))
添加年份和月份的最后期限:
df = df.assign(year = df['dates'].dt.year, month = df['dates'].dt.month)
print (df.head())
uniquecode1 Name dates Sale year month
0 1029 ABC 2020-04-01 0 2020 4
1 1029 ABC 2020-05-01 10 2020 5
2 1029 ABC 2020-06-01 20 2020 6
3 1029 ABC 2020-07-01 0 2020 7
4 1029 ABC 2020-08-01 0 2020 8
但不幸的是,缺少了09-2020
,因此有必要添加: