【问题标题】:How to merge pandas Series with DataFrame如何将熊猫系列与 DataFrame 合并
【发布时间】:2020-03-21 03:22:42
【问题描述】:

我创建了一个没有列名的 pd.Series,如下所示:

Data Inicial                          2019-12-02
Data Final                            2019-12-06
Rentabilidade do Período                 0.2863%
CDI Acumulado no Período                    4.9%
Rentabilidade Relativa                   5.8419%
Evolução do Patrimônio              -0.000454579
Menor Retorno Diário        2019-12-06: (-0.24%)
Maior Retorno Diário         2019-12-05: (0.25%)
dtype: object

我的 DataFrame 看起来像这样:

Data  Ganhos Acumulados
1944 2019-12-02           0.000000
1945 2019-12-03           0.189677
1946 2019-12-04          -0.155147
1947 2019-12-05           0.248015
1948 2019-12-06          -0.236190

我需要什么:我需要创建一个包含两种数据结构的 DataFrame,因为在此之后,我会将其转换为 HTML 并在我的前端绘图。

新的 DataFrame 应该如下所示:

Data Inicial                          2019-12-02
Data Final                            2019-12-06
Rentabilidade do Período                 0.2863%
CDI Acumulado no Período                    4.9%
Rentabilidade Relativa                   5.8419%
Evolução do Patrimônio              -0.000454579
Menor Retorno Diário        2019-12-06: (-0.24%)
Maior Retorno Diário         2019-12-05: (0.25%)
2019-12-02                              0.000000
2019-12-03                              0.189677
2019-12-04                             -0.155147
2019-12-05                              0.248015
2019-12-06                             -0.236190

我该怎么做?

【问题讨论】:

    标签: python-3.x pandas dataframe series


    【解决方案1】:

    您需要将pd.DataFrame'Date' 列定义为其索引。然后,您只需将原始pd.Seriespd.DataFrame"Ganhos Acumulados" 列连接起来,根据定义,pd.Series

    df_as_series = df.set_index(['Date'])['Ganhos Acumulados']
    result = pd.concat([<your_series>, df_as_series])
    

    【讨论】:

    • 这样,我收到了错误消息:f"Cannot remove {len(level)} levels from an index with {self.nlevels} " ValueError: Cannot remove 1 levels from an具有 1 个级别的索引:必须至少保留一个级别。
    • 数据框中的列是什么?
    • 我有索引“日期”和列“Ganhos Acumulados”的值...
    • 然后,df = df.set_index('Date')['Ganhos Acumulados']然后result = pd.concat([&lt;your_series&gt;, df]):)
    • 请不要只发布代码作为答案,还要说明您的代码的作用以及它如何解决问题。带有解释的答案通常质量更高,更有可能吸引投票。
    猜你喜欢
    • 1970-01-01
    • 2021-10-27
    • 2014-11-23
    • 2018-01-08
    • 2014-10-20
    相关资源
    最近更新 更多