我有一個資料集,每當mig2列中的日期值輸入到 input() 提示中時,mig1、de和re
值將根據以下規則更新:
mig1 is 5 months from the date entered in the input() prompt
de is 3 months from the date entered in the input() prompt
re is 1 month from the date entered in the input() prompt
Where [type] column values == 'aa'
唯一發生變化的資料是日期,它們基本上是根據用戶輸入而變化的。
資料
location type mig1 de mig2 re
ny aa 8/1/2021 10/1/2021 1/1/2022 2/1/2022
ny aa 8/1/2021 10/1/2021 1/1/2022 2/1/2022
ca aa 8/1/2021 10/1/2021 1/1/2022 2/1/2022
tx bb 9/1/2021 11/1/2021 2/1/2022 3/1/2022
想要的
#Date 8/1/2022 is input, which yields:
location type mig1 de mig2 re
ny aa 03/1/2022 05/1/2022 8/1/2022 7/1/2022
ny aa 03/1/2022 05/1/2022 8/1/2022 7/1/2022
ca aa 03/1/2022 05/1/2022 8/1/2022 7/1/2022
tx bb 03/1/2021 11/1/2021 08/1/2022 3/1/2022
輸入提示將詢問用戶他們希望輸入的日期值。 用戶輸入日期 '8/1/2021',這將更新剩余的列日期值。基于上述規則。
正在做
datevalue = pd.to_datetime(input("Enter shift: "))
d = {
'mig1': pd.DateOffset(months=5),
'de': pd.DateOffset(months=3),
're': pd.DateOffset(months=1),
}
e = {
'mig1': pd.DateOffset(months=5),
}
s = pd.Series(d).rsub(datevalue)
s1 = pd.Series(e).rsub(datevalue)
df.assign(**{**s,s1, 'mig2': datevalue})
Run d if type == 'aa'
Run e if type = 'bb'
任何建議表示贊賞 - 以上腳本運行良好,但尋找合并條件的建議
uj5u.com熱心網友回復:
與其使用條件陳述句,不如構建一個資料框來更新您的資料框。為此,我稍微修改了您的輸入:
data = {
'aa': {'mig1': pd.DateOffset(months=5),
'de': pd.DateOffset(months=3),
're': pd.DateOffset(months=1),
'mig2': pd.DateOffset(0)},
'bb': {'mig1': pd.DateOffset(months=5),
'mig2': pd.DateOffset(0)}
}
現在,使用datevalue, 格式日期計算新值以與原始資料幀合并并創建新資料幀:
data = {typ: {col: (datevalue - offset).strftime('%-m/%-d/%Y')
for col, offset in cols.items()}
for typ, cols in data.items()}
df1 = pd.DataFrame(data).T.loc[df['type']].set_index(df.index)
print(df1)
# Output
type mig1 de re mig2
0 aa 3/1/2022 5/1/2022 7/1/2022 8/1/2022
1 aa 3/1/2022 5/1/2022 7/1/2022 8/1/2022
2 aa 3/1/2022 5/1/2022 7/1/2022 8/1/2022
3 bb 3/1/2022 NaN NaN 8/1/2022
最后更新您的資料框:
df.update(df1)
print(df)
# Output
location type mig1 de mig2 re
0 ny aa 3/1/2022 5/1/2022 8/1/2022 7/1/2022
1 ny aa 3/1/2022 5/1/2022 8/1/2022 7/1/2022
2 ca aa 3/1/2022 5/1/2022 8/1/2022 7/1/2022
3 tx bb 3/1/2022 11/1/2021 8/1/2022 3/1/2022
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/397949.html
