gpt4 book ai didi

python - 使用带有需要 for 循环的分组值的数据框制作时间线图

转载 作者:行者123 更新时间:2023-12-01 06:28:39 24 4
gpt4 key购买 nike

如果我有数据框:

values               start time   end time
Ed, Taylor, Liv 0:00:00 0:00:15
Ed, Liv, Peter 0:00:15 0:00:30
Taylor, Liv, Peter 0:00:30 0:00:49
Ed, Liv, Peter 0:00:49 0:01:02

如何迭代值并创建一个时间线(最有可能在 matplotlib 中,可能是 plt.broken_barh() )来绘制它们在“值”列中的时间段?例如,X 轴将跨越 0:00:00 到 0:01:02(存在最小值和最大值),Ed 的条形图将从 0:00:00 到 0:00:15, 0:00: 15点到0:30,0:00:30到0:00:49缺席,0:00:49到0:01:02回来。迭代 Ed 后,它会先执行 Taylor、Liv,然后执行 Peter(将包含在 value.unique() 中的值),以完成一个包含 4 个条形图且缺少分段的图表,其中没有时间序列值“值”元素

我对时间序列数据相当不熟悉,尤其是当我要绘制的值只是列中存在的字符串而不是金钱或温度等值时。基本上我要寻找的是该值是否存在于时间轴上。

最佳答案

数据帧的设置方式使用起来并不那么简单。由于所有名称都放在一个复合字符串中,因此需要将它们分开才能使用。

可以使用pd.to_datatime将时间戳转换为pandas时间戳。

这是一种显示数据的方法。许多其他方法都是可能的,例如为每个人创建一个列,并用 bool 值来判断他们是否包含在 values 列中。

from matplotlib import pyplot as plt
import pandas as pd
from datetime import datetime
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

df = pd.DataFrame([['Ed, Taylor, Liv', '0:00:00', '0:00:15'],
['Ed, Liv, Peter', '0:00:15', '0:00:30'],
['Taylor, Liv, Peter', '0:00:30', '0:00:49'],
['Ed, Liv, Peter', '0:00:49', '0:01:02']],
columns=['values', 'start time', 'end time'])
df['start time'] = pd.to_datetime(df['start time'])
df['end time'] = pd.to_datetime(df['end time'])

persons_set = set(name.strip() for names in df['values'] for name in names.split(","))
persons = {p: i for i, p in enumerate(sorted(persons_set))}
print(persons)
for person in persons:
periods = []
for names, start, end in zip(df['values'], df['start time'], df['end time']):
if person in set(name.strip() for name in names.split(",")):
periods.append((start, end - start))
plt.broken_barh(periods, (persons[person] - 0.45, 0.9),
facecolors=plt.cm.plasma(persons[person] / len(persons)))

plt.yticks(range(len(persons)), persons)
plt.show()

resulting plot

关于python - 使用带有需要 for 循环的分组值的数据框制作时间线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60009441/

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