我有一個資料集,每當Update列中的日期值輸入到 input() 提示中時,Date1、Date2和Date3
值將根據以下規則更新:
Date1 is 5 months from the date entered in the input() prompt
Date2 is 2 months from the date entered in the input() prompt
Date3 is 1 month from the date entered in the input() prompt
唯一發生變化的資料是日期,它們基本上是根據用戶輸入而變化的。
資料
ID Stat Date1 Date2 Date3 Update
aa 500 1/1/2021 4/1/2021 5/1/2021 6/1/2021
bb 800 1/1/2021 4/1/2021 5/1/2021 6/1/2021
想要的
輸入提示將詢問用戶他們希望輸入的日期值。 用戶輸入日期 '8/1/2021',這將更新剩余的列日期值。基于上述規則。
ID Stat Date1 Date2 Date3 Update
aa 500 3/1/2021 6/1/2021 7/1/2021 8/1/2021
bb 800 3/1/2021 6/1/2021 7/1/2021 8/1/2021
正在做
我相信我可以結合使用函式和用戶提示來解決這個問題。
型別輸入
datevalue = pd.to_datetime(input("Enter date value: "))
print(datevalue)
在函式或腳本中使用輸入變數為 Date1、Date2 和 Date3 創建日期更新
df[0] = df[1].apply(lambda x: datevalue - pd.DateOffset(months=x))
s = df['Update'].str.replace(r'(\S ) (\S )', r'\2\1')
df['Update'] = (pd.PeriodIndex(s, freq='D') 3).strftime('D%q %Y')
我正在尋找一些關于如何最好地解決這個問題的起點建議或良好的基礎/檔案。我還在研究。任何建議表示贊賞。
uj5u.com熱心網友回復:
我們可以定義一個映射字典,將列名映射到相應的日期datevalue偏移量,然后從這個字典中創建一個系列并減去偏移量,最后assign將更新的日期值回傳到資料幀
d = {
'Date1': pd.DateOffset(months=5),
'Date2': pd.DateOffset(months=2),
'Date3': pd.DateOffset(months=1),
}
s = pd.Series(d).rsub(datevalue)
df.assign(**{**s, 'Update': datevalue})
ID Stat Date1 Date2 Date3 Update
0 aa 500 2021-03-01 2021-06-01 2021-07-01 2021-08-01
1 bb 800 2021-03-01 2021-06-01 2021-07-01 2021-08-01
uj5u.com熱心網友回復:
我想你正在尋找這樣的東西:
cols = df.filter(like='Date').columns.tolist() ['Update']
df[cols] = df[cols].apply(lambda col: pd.to_datetime(col) (datevalue - df['Update']))
輸出:
>>> df
ID Stat Date1 Date2 Date3 Update
0 aa 500 2021-03-03 2021-06-01 2021-07-01 2021-08-01
1 bb 800 2021-03-03 2021-06-01 2021-07-01 2021-08-01
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/383764.html
上一篇:如何在SAS中使用CATX功能
下一篇:使用Python用戶輸入更新值
