[英]Converting nested dictionary to dataframe with the keys as rownames and the dictionaries in the values as columns?
[英]Converting both a dictionary's keys and values to columns in a pandas dataframe efficiently
我有一本像這樣的字典:
dict1 = {k1:v1,k2:v2,k3:v3}
我想把這本字典變成 dataframe。 我以前在這里使用pd.Series(dict1)
看到過其他問題,這會產生 DataFrame ,如下所示:
Index col1
k1 v1
k2 v2
k3 v3
但就我而言,我希望 DataFrame 像:
Index col1 col2 col3 col4 col5 col6
0 k1 v1 k2 v2 k3 v3
因此,我希望將每個鍵和每個值都作為一列,並且不使用它們作為索引,這是傳統上推薦的將 dict 轉換為 DataFrame 的方法通常使用的方法。 在此示例中,我希望 DataFrame 為 1x6,而不是 2x3 或 3x2。
我還有一個非常大的 N 字典字典,我想將其應用到,在這種情況下會產生 Nx6 dataframe,所以希望給定的方法不會花費太長時間來應用。 有誰知道如何做到這一點? 謝謝
您可以獲取dict
的項目並將其展平。
我已經使用itertools.chain
來展平dict
。
然后對從項目創建的結果 dataframe 進行轉置。
>>> import pandas as pd
>>> from itertools import chain
>>> d = {i: i*i for i in range(1, 6)} # example dict
>>> d
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
>>> df = pd.DataFrame(chain(*d.items())).T
>>> df
0 1 2 3 4 5 6 7 8 9
0 1 1 2 4 3 9 4 16 5 25
使用您問題中的dict
,它看起來像這樣,
>>> dict1 = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
>>> pd.DataFrame(chain(*dict1.items())).T
0 1 2 3 4 5
0 k1 v1 k2 v2 k3 v3
如果您想要具有不同名稱的列,只需重命名它們。
以下是此方法針對不同大小的輸入字典的一些時間比較。
分別比較100
、 10,000
和1,00,000
個項目。
In [18]: d100_items = {i: i*i for i in range(100)}.items()
In [19]: d10_000_items = {i: i*i for i in range(10_000)}.items()
In [20]: d1_00_000_items = {i: i*i for i in range(1_00_000)}.items()
In [22]: %timeit pd.DataFrame(chain(*d100_items)).T
329 µs ± 10 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [23]: %timeit pd.DataFrame(chain(*d10_000_items)).T
4.62 ms ± 83.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [24]: %timeit pd.DataFrame(chain(*d1_00_000_items)).T
56.8 ms ± 1.4 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.