Pandas数据帧中的时间序列绘图出错

2024-04-26 11:38:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下两个数据框posts,它显示了某个特定的帖子是何时与发布者一起发布的UserId(一个用户发布了多篇帖子)和badges,它显示了某个特定用户获得徽章的日期和时间,我只显示了其中的一部分

我想创建一个线条图,表示用户在获得徽章之前和之后发表的帖子的平均值(即,x轴应具有获得徽章之前和之后1周的天数,y轴应具有用户在此期间发表的帖子的平均数)

我尝试了以下代码,但得到了AttributeError: 'function' object has no attribute 'line'。请给我一个解决这个问题的方法

代码示例(数据集生成和函数):

import pandas as pd
from matplotlib import pyplot as plt

posts = pd.DataFrame({
    'Creation Date': [
        pd.Timestamp('2009-09-28 16:11:38.533'),
        pd.Timestamp('2009-09-28 17:42:23.207'),
        pd.Timestamp('2009-09-28 19:41:13.933'),
        pd.Timestamp('2009-09-28 23:40:55.033')],
    'UserId': [1,2,4,1]
})

badges = pd.DataFrame({
    'UserId': [143, 1, 344],
    'Date': [
        pd.Timestamp('2009-10-17 17:38:32.590'),
        pd.Timestamp('2009-10-19 00:37:23.067'),
        pd.Timestamp('2009-10-20 08:37:14.143')
    ]
})

plt.plot.line(x=(posts['UserId'].CreationDate < badges['UserId'].Date), y=(posts['UserId'].value_counts.mean()))

Tags: 数据代码用户importdateaslineplt
1条回答
网友
1楼 · 发布于 2024-04-26 11:38:53

这两个函数可以计算任何用户在某个特定徽章之前和之后发布的次数总和

def before(user_id):
    count = 0
    for badge_date in badges[badges.UserId==user_id].Date.values:
        count += posts[(posts['Creation Date'] < badge_date) & (posts['UserId'] == user_id)].UserId.count()
    return count

def after(user_id):
    count = 0
    for badge_date in badges[badges.UserId==user_id].Date.values:
        count += posts[(posts['Creation Date'] > badge_date) & (posts['UserId'] == user_id)].UserId.count()
    return count

当应用于“徽章”数据框时:

badges['before']= badges.UserId.apply(before)
badges['after']= badges.UserId.apply(after)

要聚合结果,您可能需要使用

before_df = pd.DataFrame(badges.groupby('UserId').before.sum())
before_df['id'] = before_df.index
before_df = pd.DataFrame(before_df.groupby('before').id.count())
after_df = pd.DataFrame(badges.groupby('UserId').after.sum())
after_df['id'] = after_df.index
after_df = pd.DataFrame(after_df.groupby('after').id.count())

这些最终的before_df和after_df包含作为索引的次数,以及在徽章之前和之后分别发布的用户数作为值

这能完成任务吗

相关问题 更多 >