簡體   English   中英

將值和鍵從嵌套字典映射到列

[英]Mapping values and keys from a nested dictionary to columns

我正在使用以下字典

store_dict = {'store1': {'itemA' : 1},
              'store2': {'itemB' : 2},
              'store3': {'itemC' : 3}}

我的最終目標是將值(即嵌套字典)映射到數據框的單獨列中。 所以我想把這個數據框

    store

0  store1
1  store2
2  store3
3  store1 

到以下數據框。

    store   item   price

0  store1  itemA       1
1  store2  itemB       2
2  store3  itemC       3
3  store1  itemA       1

我做了df['store'].map(store_dict)和一些正則表達式兩次,使項目和價格列,但現在我更想知道是否有一種方法可以直接獲取嵌套字典的鍵和值列。 在我研究嵌套字典以獲取價格的整個過程中,我們必須使用store_dict['store1']['item1'] ,它無法根據數據大小進行縮放,而且我仍然不太確定如何去做只得到物品。

嘗試這個:

store_dict = {'store1': {'itemA' : 1},
              'store2': {'itemB' : 2},
              'store3': {'itemC' : 3}}
df = pd.concat({        k: pd.DataFrame.from_dict(v, 'index') for k, v in store_dict.items() }, 
    axis=0).reset_index()
df.columns =  ['store', 'item', 'price']
df

輸出:

    store   item    price
0   store1  itemA   1
1   store2  itemB   2
2   store3  itemC   3

你可以做:

>>> store_dict = {'store1': {'itemA' : 1},
              'store2': {'itemB' : 2},
              'store3': {'itemC' : 3}}
>>> temp_df = pd.DataFrame(store_dict)
>>> df = pd.DataFrame({'store':temp_df.columns, 'item':temp_df.index, 'price':temp_df.sum(axis = 1)})
>>> df = df.append(df.iloc[0])
>>> df.reset_index()
    store   item  price
0  store1  itemA    1.0
1  store2  itemB    2.0
2  store3  itemC    3.0
3  store1  itemA    1.0

暫無
暫無

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

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