我有一個看起來像這樣的 pandas 數據框, id start end0 1 2020-02-01 2020-04-011 2 2020-04-01 2020-04-28我有兩個附加參數,它們是日期值,例如 x 和 y。x 和 y 將始終是該月的第一天。我想將上面的數據框擴展到下面所示的 x =“2020-01-01”和 y =“2020-06-01”, id month status0 1 2020-01 -11 1 2020-02 12 1 2020-03 23 1 2020-04 24 1 2020-05 -15 1 2020-06 -16 2 2020-01 -17 2 2020-02 -18 2 2020-03 -19 2 2020-04 110 2 2020-05 -111 2 2020-06 -1數據框已擴展,因此對于每個 id,都會有額外的 Month_ Between(x, y) 行。并創建一個狀態列并填充值,以便,如果月份列值等于開始列的月份,則將狀態填充為 1如果月份列值大于開始列的月份但小于或等于結束列的月份,則填寫為 2。如果月份列值小于起始月份,則填寫為-1。另外,如果月份列值大于結束月份,則填充狀態為 -1。我試圖在 pandas 中解決這個問題而不循環。我當前的解決方案是使用循環,并且需要更長的時間來運行巨大的數據集。有沒有熊貓函數可以幫助我?
1 回答

蝴蝶刀刀
TA貢獻1801條經驗 獲得超8個贊
確保start和end列的類型為Timestamp:
# Explode each month between x and y
x = '2020-01-01'
y = '2020-06-01'
df['month'] = [pd.date_range(x, y, freq='MS')] * len(df)
df = df.explode('month').drop_duplicate(['id', 'month'])
# Determine the status
df['status'] = -1
cond = df['start'] == df['month']
df.loc[cond, 'status'] = 1
cond = (df['start'] < df['month']) & (df['month'] <= df['end'])
df.loc[cond, 'status'] = 2
添加回答
舉報
0/150
提交
取消