【问题标题】:how do I combine a single row with it's own index with an unstacked multi-index dataframe?如何将单行与它自己的索引与未堆叠的多索引数据框结合起来?
【发布时间】:2021-11-17 21:32:55
【问题描述】:

我有一个由以下代码创建的数据框:

dfHubR2I=dfHubPV2.loc[dfHubPV2['Ind'].dt.year == year, :].groupby(['SHOP_CODE', dfHubPV2['Ind'].dt.month])['R2I'].agg(['median']).fillna('-')
dfHubR2I=dfHubR2I['median'].unstack('SHOP_CODE')
dfHubR2I=dfHubR2I.iloc[:date.month-1]
dfHubR2I

看起来像这样:

shop code     A     B    C    D   All Shops
ind
1            23     34   23   56      34
2            13     23   45   47      34
3            56     67   42   85      57
4            3       3    2   6       46

ind 是月份,字母是不同的商店

然后我从这段代码中得到了每个月所有商店的中位数:

dfHubR2Imonthallshops=dfHubPV2.loc[dfHubPV2['Ind'].dt.year == year, :].groupby([dfHubPV2['Ind'].dt.month])['R2I'].agg(['median']).fillna('-')
dfHubR2Imonthallshops=dfHubR2Imonthallshops.rename(columns={'median':'All Shops'})
dfHubR2Imonthallshops=dfHubR2Imonthallshops.iloc[:date.month-1]
dfHubR2Imonthallshops

看起来像这样:

          A  B C D All shops
median    2  3 4 5    2

我需要将它作为一行附加到更大的数据帧中,但是当我尝试使用 pd.concat 时出现错误 InvalidIndexError: Reindexing only valid with unique value Index objects

我假设这是因为较大的数据框有 2 个级别,但我不确定如何获得最终想要的结果:

shop code     A     B    C    D  All shops
ind
1            23     34   23   56    34
2            13     23   45   47    34
3            56     67   42   85    57 
4            3       3    2   6     46
YTD          2       3    4    5    2

【问题讨论】:

  • oops 对不起,我忘了把每个月的中位数部分换掉,我修好了,那行的图片是正确的,我发现所有商店的中位数都是 YTD我想追加到数据框。

标签: python pandas dataframe merge concatenation


【解决方案1】:

您是否尝试过通过作业来完成?

dfHubR2I.loc['YTD', :] = dfHubR2Imonthallshops.loc['median', :]

埃莉奥诺拉

【讨论】:

    猜你喜欢
    • 2021-02-07
    • 2019-05-08
    • 2012-12-18
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    相关资源
    最近更新 更多