gpt4 book ai didi

python - 在 Python pandas 中将数据映射到另一年的同一工作日

转载 作者:行者123 更新时间:2023-11-30 22:00:13 25 4
gpt4 key购买 nike

我有一个包含全年用电量数据的 pandas 数据框,但希望将表格更新到另一年。我希望数据值落在与以前相同的工作日。

我有:

Date          00:00   ...     WeekDay   requiredDate  requiredWeekDay
25/11/2018 20 Sunday 25/11/2018 Sunday
26/11/2018 30 Monday 26/11/2018 Monday
27/11/2018 25 Tuesday 27/11/2018 Tuesday
28/11/2018 35 Wednesday 28/11/2018 Wednesday
29/11/2018 40 Thursday 29/11/2018 Thursday
30/11/2018 15 Friday 30/11/2018 Friday
01/12/2017 65 Sunday 01/12/2018 Saturday
02/12/2017 34 Monday 02/12/2018 Sunday
03/12/2017 81 Tuesday 03/12/2018 Monday
04/12/2017 62 Wednesday 04/12/2018 Tuesday
...

我想要什么:

Date          00:00   ...     WeekDay     
25/11/2018 20 Sunday
26/11/2018 30 Monday
27/11/2018 25 Tuesday
28/11/2018 35 Wednesday
29/11/2018 40 Thursday
30/11/2018 15 Friday
01/12/2018 Saturday
02/12/2018 65 Sunday
03/12/2018 34 Monday
04/12/2018 81 Tuesday
...

我尝试过的:

df['Day'] = df['Date'].dt.day
df['Month'] = df['Date'].dt.month
df['Year'] = df['Date'].dt.year
requiredYear = str(df['Year'].median()).replace(".0","")

df = df.sort_values(by = ['Month', 'Day']).reset_index()

df['RemappedDate']= np.nan

for index, row in df.iterrows():
if row['Weekday'] != row['requiredWeekday']:
while row[row['Day']]<31:
row['Day'] = row['Day']-1
row['RemappedDate'] = pd.to_datetime(str(row['Month'])+"/"+
str(row['Day'])+"/"+requiredYear)
else:
print("Already equal")

df['Date'] = df['RemappedDate']
df['Weekday'] = df['requiredWeekday']

可能还很遥远,如果没有的话很抱歉。我是初学者。

最佳答案

如果我是您,我只会“保留”已经为您制作的 2 列,并“移动”某物 列,例如...

mask = df['Date'] <= '2018-01-01'
df['something'][mask] = df['something'][mask].shift(1)

您可以保留两列“new_date”和“new_day”。丢弃其他的并重新命名其中 2 个,无论您想做什么。 :)

关于python - 在 Python pandas 中将数据映射到另一年的同一工作日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54369984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com