【问题标题】:I need to make an analysis of accumulated value for each day of a time series我需要对时间序列的每一天的累积值进行分析
【发布时间】:2020-03-19 16:11:04
【问题描述】:

我有一个具有时间序列的 DataFrame。我需要获得第一行并添加喜欢我的投资。下一行是另一天,我需要比较以获取值差异,这将是我 1 天的累积值。

我的数据:

My Data

翻译: 数据 = 日期

Cota = 配额

Patrimonio Liquido = 净资产

目前我的代码如下所示:

len_fundo = len(self.fundo)
    investiment = self.fundo.iloc[0]
    dict_accumulated = {}
    for value in range(1, len_fundo):
        next_line = self.fundo.iloc[value]
        dict_accumulated['Data'] = next_line['Data']
        dict_accumulated['Acumulado'] = next_line['PL'] - investiment['PL']
        investiment = next_line
        accumulated = pd.DataFrame(data=dict_accumulated, index=[value])
    return accumulated

但结果只有最后一行。

  Data         Acumulado
4 2019-12-06   942355.3

我知道这是因为 python dict 不接受重复键;因此,它取代了钥匙,但我该如何解决这种情况? 我需要为每一天生成一个包含日期和累计值列的新 DF...

结果将是一个像这样的新 DF:

enter image description here

【问题讨论】:

    标签: python pandas dataframe dictionary time-series


    【解决方案1】:

    我认为你应该使用

    df['gains'] = df['current'].shift(1) - df['current'] # difference per day
    df['acumulado'] = df['gains'].cumsum() # for cumulative sum of gains
    

    在pandas 中使用循环通常是不好的做法

    【讨论】:

    • 您的解决方案部分解决了我的问题,因为我也需要日期字段。我提供了有关我的问题的更多信息,更改了我的帖子,并添加了图像和示例...
    • 日期不受影响。这只是添加新列
    • 好的,但是,我不需要返回所有字段,只返回日期和增益...所以,我想创建一个接收日期和增益的新数据框,但我不能这样做。
    • 只需使用df = df.drop(['col1', 'col2'], axis=1) 删除它们,您不需要保留它们。
    【解决方案2】:

    您没有提供一个功能齐全的示例,所以我无法测试它是否按预期工作,但您不能只制作 dict_accumulated['Data'] 和 dict_accumulated['Acumulado'] 列表,然后在每个循环中附加到它们吗?像这样的:

        len_fundo = len(self.fundo)
        investiment = self.fundo.iloc[0]
        dict_accumulated = {}
        dict_accumulated['Data'] = []
        dict_accumulated['Acumulado'] = []
        for value in range(1, len_fundo):
            next_line = self.fundo.iloc[value]
            dict_accumulated['Data'].append(next_line['Data'])
            dict_accumulated['Acumulado'].append(next_line['PL'] - investiment['PL'])
            investiment = next_line
            accumulated = pd.DataFrame(data=dict_accumulated, index=[value])
        return accumulated
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2021-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-12
      相关资源
      最近更新 更多