背景:
不同的编码item有最早供应周期与最晚供应周期,在最早供应周期、最晚供应周期之间的每个供应周期展开生成一笔9999的供应量
关键点:apply函数的应用
解决方案:
import pandas as pd
df_item_is_auto = pd.DataFrame({
'ITEM': ['A', 'B', 'C'],
'LAST_PERIOD': [5, 4, 6],
'EARLIEST_PERIOD': [1, 2, 3]
})
def expand_periods(row):
periods = range(int(row['EARLIEST_PERIOD']), int(row['LAST_PERIOD']) + 1)
item_data = pd.DataFrame({
'ITEM': [row['ITEM']] * len(periods),
'PERIOD': periods,
'QTY': [9999] * len(periods)
})
return item_data
# 使用apply函数展开数据
df = df_item_is_auto.apply(expand_periods, axis=1).reset_index(drop=True)
df = pd.concat([df[i] for i in range(len(df))], axis=0, ignore_index=True)
print(df)
输出结果:
ITEM PERIOD QTY
0 A 1 9999
1 A 2 9999