gpt4 book ai didi

python - 从 Pandas 长格式创建事件图

转载 作者:行者123 更新时间:2023-12-04 13:07:29 26 4
gpt4 key购买 nike

我无法将包含多个观察结果的 Pandas 数据框转换为正确的格式以显示事件图。 'creator' 列应该是用于区分数据集的标签。

import pandas as pd
from matplotlib import pyplot as plt

data = {
"creator": [1, 2, 1, 1, 2],
"creationdate": ["2019-03-13 16:43:55", "2019-03-13 16:43:55", "2019-03-15 15:52:05",
"2019-03-16 15:52:05", "2019-03-17 15:52:05"]
}

df = pd.DataFrame(data)
df["creationdate"] = pd.to_datetime(df["creationdate"])

# df
# creator creationdate
#0 1 2019-03-13 16:43:55
#1 2 2019-03-13 16:43:55
#2 1 2019-03-15 15:52:05
#3 1 2019-03-16 15:52:05
#4 2 2019-03-17 15:52:05

# Group by creator
grouped = df.groupby("creator")

# How can the data now be reshaped to actually display the plot
# ...

# TypeError: Invalid comparison between dtype=datetime64[ns] and int
fig = plt.eventplot(grouped)
plt.show()

我尝试遍历分组数组以提取各个组,但这似乎很复杂且没有必要。

data = np.array([grouped.get_group(1)["creationdate"].to_numpy(), grouped.get_group(2)["creationdate"].to_numpy()])

最佳答案

  • groupby 对象上使用 enumerate 来索引颜色列表。
import pandas as pd
import matplotlib.pyplot as plt

# load data
data = {'creator': [1, 2, 1, 1, 2], 'creationdate': ['2019-03-13 16:43:55', '2019-03-13 16:43:55', '2019-03-15 15:52:05', '2019-03-16 15:52:05', '2019-03-17 15:52:05']}

df = pd.DataFrame(data)

# convert column to a datetime dtype
df['creationdate'] = pd.to_datetime(df['creationdate'])

# create the fig / axes
fig, ax = plt.subplots(figsize=(10, 4))

# iterate through each group and plot
colors = ['blue', 'red']
for i, (label, data) in enumerate(df.groupby('creator')):
ax.eventplot('creationdate', colors=colors[i], data=data, label=label)

ax.legend(title='Creator', bbox_to_anchor=(1, 1.02), loc='upper left')
ax.set(xlabel='Datetime', ylabel='Value', title='Eventplot')

enter image description here

关于python - 从 Pandas 长格式创建事件图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68718792/

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