Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

python - Fill dates with last value until current time

I've a dataframe with the following structure:

Time Company Product_type Total_sales
2021-01-31 06:00:00+00:00 Adidas Shoes 20
2021-01-31 05:00:00+00:00 Adidas Shoes 13
2021-01-31 03:00:00+00:00 Adidas Shoes 4
2021-01-31 03:00:00+00:00 Nike Shoes 5
2021-01-31 02:00:00+00:00 Adidas Shoes 3
2021-01-31 02:00:00+00:00 Nike Shoes 3
question from:https://stackoverflow.com/questions/66064076/fill-dates-with-last-value-until-current-time

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The code I've created is limited to Adidas, but you can combine Nike in the same way. The main point is to update the original dataframe by creating a pd.datetime_range() from the last data of the real data to today. At that time, we will fill in the holes backward.

df['Time'] = pd.to_datetime(df['Time'])
df.set_index('Time', inplace=True)
df_adidas = df.loc[df['Company'] == 'Adidas']
tidx = pd.date_range(df_adidas.head(1).index.values[0], datetime.date.today(), freq='1H', tz='UTC')
df_adidas.reindex(tidx, method='bfill')

    Company     Product_type    Total_sales
2021-01-31 06:00:00+00:00   Adidas  Shoes   20
2021-01-31 07:00:00+00:00   Adidas  Shoes   20
2021-01-31 08:00:00+00:00   Adidas  Shoes   20
2021-01-31 09:00:00+00:00   Adidas  Shoes   20
2021-01-31 10:00:00+00:00   Adidas  Shoes   20
...     ...     ...     ...
2021-02-05 20:00:00+00:00   Adidas  Shoes   20
2021-02-05 21:00:00+00:00   Adidas  Shoes   20
2021-02-05 22:00:00+00:00   Adidas  Shoes   20
2021-02-05 23:00:00+00:00   Adidas  Shoes   20
2021-02-06 00:00:00+00:00   Adidas  Shoes   20

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...