熊猫:根据时间分类数据帧字典

时间:2017-12-06 15:53:44

标签: python pandas dictionary dataframe chunks

我有一个数据框字典,其中每个数据框都有价格和时间戳列。像这样{'A':df1, 'B':df2}

我需要构建一个函数,它可以在时间戳的H小时块中切割dict中的数据帧,然后将这个数据帧的dict传递给每个chunk的另一个函数(对其进行一些计算)。

我如何继续前进?

例如

def foo(dict_of_dataframes):
    for id, df in dict_of_dataframes.items():
        do_something()

def boo(dict_of_dataframes, chunksize):
    """
    Needs to chunk up the @dict_of_dataframes in @chunksize hours
    and needs to call foo function on these chunks of
    @dicts_of_dataframes
    """

示例数据:

df1:
Time                       Price
2017-03-07 09:47:31+00:00  100
2017-03-07 11:27:31+00:00  120
2017-03-07 14:47:31+00:00  150
2017-03-07 17:17:31+00:00  135
2017-03-07 20:57:31+00:00  200
2017-03-08 03:27:31+00:00  120
2017-03-08 09:57:31+00:00  100
2017-03-08 11:27:31+00:00  150

df2:
Time                       Price
2017-03-07 09:07:31+00:00  200
2017-03-07 10:27:31+00:00  300
2017-03-07 12:47:31+00:00  100
2017-03-07 17:47:31+00:00  250
2017-03-07 22:27:31+00:00  300
2017-03-08 01:57:31+00:00  500
2017-03-08 02:57:31+00:00  500
2017-03-08 10:27:31+00:00  100

我需要有关boo功能的帮助。一个人如何继续前进?

对于这些模拟其他函数调用的boo函数,还有任何特定的术语。我已经看过几次,如果你能指出一个解释如何设计这些功能调用者的资源。功能,我真的很感激。

1 个答案:

答案 0 :(得分:0)

我认为你真正想要的是使用resample实现的 - 基本上是日期时间的groupby。假设您需要在6小时内获得交易金额,您可以使用:

def boo(dict_dfs, hours):
    return {k: v.resample(f'{hours}H').sum() for k,v in dict_dfs.items()}

现在,如果您100%确定需要使用dicts,请使用groupby

def boo(dict_dfs, hours):
    return {k:{hr:v for hr, v in df.groupby(Grouper(key='Time', freq=f'{hours}H'))} for k, df in dict_dfs.items()}

顺便说一下,如果你想在dicts上循环{key,value},请使用dict.items(),而不是单词本身。

还有一点需要注意:我看到很多时候人们对数据结构过于复杂。大多数情况下,您不需要数据帧的字典 - 您可以使用一个数据帧,只需要category列,甚至可以使用多索引(例如,[category,Time]多索引)有了它,您将获得更多可重用,快速和干净的代码!

相关问题