gpt4 book ai didi

python - 在 Pandas 中,是否有一些紧凑的方法可以在一周中的几天内绘制数据?

转载 作者:太空宇宙 更新时间:2023-11-03 12:02:20 24 4
gpt4 key购买 nike

我有一个简单的数据框,其中包含一组针对设置为索引的 datetime 记录的值。是否有一些紧凑的方法可以在一周中的几天内绘制这些数据?我的意思是类似下面的内容,横轴是星期几,不同周的数据以不同的颜色绘制:

我目前的代码如下,但对于一个概念上简单的东西来说,它似乎很复杂:

df["weekday"]          = df["datetime"].dt.weekday
df["weekday_name"] = df["datetime"].dt.weekday_name
df["time_through_day"] = df["datetime"].map(lambda x: x - datetime.datetime.combine(x.date(), datetime.time()))

def days_through_week(row):

return row["weekday"] + row["time_through_day"] / (24 * np.timedelta64(1, "h"))

df["days_through_week"] = df.apply(lambda row: days_through_week(row), axis = 1)

datasets = []
dataset = []
previous_days_through_week = 0
for days_through_week, value in zip(df["days_through_week"], df["value"]):
if abs(days_through_week - previous_days_through_week) < 5:
dataset.append([days_through_week, value])
else:
datasets.append(dataset)
dataset = []
previous_days_through_week = days_through_week

for dataset in datasets:

x = [datum[0] for datum in dataset]
y = [datum[1] for datum in dataset]

plt.plot(x, y, linestyle = "-", linewidth = 1.3)

plt.ylabel("value")
plt.xticks(
[ 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5],
[ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
)

最佳答案

设置:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates


np.random.seed(51723)

#Make some fake data to play with. Includes a partial week.
n = pd.DatetimeIndex(start="2-Jan-2017", end="1-Mar-2017", freq="1H")
df = pd.DataFrame(index=n, data=np.random.randn(n.size), columns=['A'])
df.A = df.groupby(df.index.week).A.transform('cumsum')

情节:

#list of names for xtick labels. Extra Monday for end.
weekday_names = "Mon Tue Wed Thu Fri Sat Sun Mon".split(' ')

fig, ax = plt.subplots()
for name, group in df.groupby(df.index.week):
start_day= group.index.min().to_pydatetime()
#convert date to week age
Xs = mdates.date2num(group.index.to_pydatetime()) \
- mdates.date2num(start_day)
Ys = group.A
ax.plot(Xs, Ys)
ax.set_xticklabels(weekday_names)
ax.set_xticks(range(0, len(weekday_names)))

plot of weekly chunks

关于python - 在 Pandas 中,是否有一些紧凑的方法可以在一周中的几天内绘制数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45177318/

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