簡體   English   中英

對大熊貓數據幀的詞典dict - 將多索引行更改為列

[英]Dict of dict of dicts to pandas dataframe - changing multiindex rows to be columns

我有一個這樣的字典:

my_dict = {'Key': {'Service': {'Number': 61, 'Percent': 2.54 }, 'Service2': {'Number': 42, 'Percent': 2.2 } }, 'Key2': {'Service3': {'Number': 8, 'Percent': 2.74}, 'Service2': {'Number': 52, 'Percent': 2.5 } }}

我正在嘗試將其轉換為pandas數據幀。 我得到了這個解決方案

pandas.concat(map(pandas.DataFrame, my_dict.itervalues()), keys=my_dict.keys()).stack().unstack(0)

但是,我的問題是我得到一個表,其中行索引是Service&Number / Percent的多索引。 相反,我希望索引只是出現的不同服務(不是多索引),並希望列像現在一樣是鍵,但是1列部分是Number,第2列部分是所有鍵百分比,如果這是有道理的。 轉置不是我想要的,因為我不希望整個索引發生變化,只需要數量/百分比。 我希望它看起來像這樣,從我上面寫的字典轉換為數據幀后:

          Number         Percent
          Key    Key2    Key     Key2
Service   61     NaN     2.54    NaN
Service2  42     52      2.2     2.5
Service3  NaN    8       NaN     2.74

有什么建議嗎?

pd.concat({k: pd.DataFrame(v) for k, v in my_dict.items()})

              Service  Service2  Service3
Key  Number     61.00      42.0       NaN
     Percent     2.54       2.2       NaN
Key2 Number       NaN      52.0      8.00
     Percent      NaN       2.5      2.74

pd.concat({k: pd.DataFrame(v) for k, v in my_dict.items()}, axis=1).stack(0).T

         Number       Percent      
            Key  Key2     Key  Key2
Service    61.0   NaN    2.54   NaN
Service2   42.0  52.0    2.20  2.50
Service3    NaN   8.0     NaN  2.74

這不依賴於理解

pd.DataFrame(my_dict).stack().apply(pd.Series).unstack()
# pandas.DataFrame(i).stack().apply(pandas.Series).unstack()

         Number       Percent      
            Key  Key2     Key  Key2
Service    61.0   NaN    2.54   NaN
Service2   42.0  52.0    2.20  2.50
Service3    NaN   8.0     NaN  2.74

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM