【问题标题】:Timeseries with multiple columns, each with duplicate entries. How to handle in pandas具有多列的时间序列,每列都有重复的条目。如何在熊猫中处理
【发布时间】:2019-04-01 05:47:00
【问题描述】:

在 Date 和 UID 列中有以下具有重复值的数据框:

Date           UID       Score
2018-08-31       A          5
2018-08-31       B          3
2018-08-31       C          4
2018-05-31       A          4
2018-05-31       C          2
2018-05-31       A          4
2018-05-31       B          1
2018-05-31       A          3
2018-01-31       C          5
2018-01-31       A          3
2018-01-31       A          4
2018-01-31       C          2
2018-01-31       B          5

如果同一日期出现重复的 UID,请创建如下内容:

2018-08-31       A          5
2018-05-31       A          3.67
2018-01-31       A          3.5

2018-08-31       B          3
2018-05-31       B          1
2018-01-31       B          5

2018-08-31       C          4
2018-05-31       C          2
2018-01-31       C          3.5

我想要完成的是将原始数据帧拆分为多个时间序列,我可以将它们一起绘制并使用。在这种情况下,我该如何重塑这个数据框,以便我可以根据 UID 分数使用 3 个不同的时间序列?

我似乎被困在以下点......

df.groupby(['Date', 'UID'], as_index=False)['Score'].mean()

...我不知道如何正确地重塑它。

感谢任何反馈。

【问题讨论】:

    标签: python pandas dataframe duplicates time-series


    【解决方案1】:

    我认为您唯一的问题是您的 group by 中的顺序。试试:

    #Recreating your frame
    df = pd.DataFrame( [['2018-08-31',     'A',         '5'],['2018-08-31','B',3],
    ['2018-08-31','C',4],
    ['2018-05-31','A',4],
    ['2018-05-31','C',2],
    ['2018-05-31','A',4],
    ['2018-05-31','B',1],
    ['2018-05-31','A',3],
    ['2018-01-31','C',5],
    ['2018-01-31','A',3],
    ['2018-01-31','A',4],
    ['2018-01-31','C',2],
    ['2018-01-31','B',5]] , columns =  ['Date','UID','Score'])
    df['Score'] = pd.to_numeric(df['Score'])
    
    #The solution
    df.groupby(['UID', 'Date']).mean()
    

    这会产生:

                    Score
    UID Date    
    A   2018-01-31  3.500000
        2018-05-31  3.666667
        2018-08-31  5.000000
    B   2018-01-31  5.000000
        2018-05-31  1.000000
        2018-08-31  3.000000
    C   2018-01-31  3.500000
        2018-05-31  2.000000
        2018-08-31  4.000000
    

    绘图可以这样完成:

    df.groupby(['UID','Date']).mean().loc["A"].plot()
    df.groupby(['UID','Date']).mean().loc["B"].plot()
    df.groupby(['UID','Date']).mean().loc["C"].plot()
    

    【讨论】:

    • 感谢克里斯蒂安!如何将它们绘制为单独的时间序列?我可能过于复杂,但找到了一个我用来为 UID 实现布尔过滤器并以这种方式绘制的解决方案。对我来说似乎是额外的步骤。
    • @jarwal 添加了绘图,希望对您有所帮助。
    • 感谢您花时间帮助我理解。欣赏它。
    猜你喜欢
    • 2020-04-24
    • 2012-07-01
    • 2020-12-15
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    相关资源
    最近更新 更多