![](/img/trans.png)
[英]Create a pandas dataframe from a python dictionary. Python dictionary has multiple keys and its values have both string and list data types
[英]Python Pandas: Create DataFrame from dictionary that has values of list of lists
我有如下字典:
dict = {key_1:[[1, 2], [3, 4]], key_2:[[1, 2], [3, 4]]}
我想將其轉換為如下所示的 dataframe:
colum_1 column_2
key_1 1 2
key_1 3 4
key_2 1 2
key_2 3 4
什么是最有效的方法來做到這一點。 感謝您的幫助=)
讓我們嘗試理解以解除鍵值對的嵌套
pd.DataFrame((k, *l) for k, v in d.items() for l in v).set_index(0)
1 2
0
key_1 1 2
key_1 3 4
key_2 1 2
key_2 3 4
IIUC,你可以使用:
cols = ['col1', 'col2']
df = pd.DataFrame({k: zip(*v) for k,v in d.items()}, index=cols).T.explode(cols)
output:
col1 col2
key_1 1 2
key_1 3 4
key_2 1 2
key_2 3 4
這是一種純粹的 pandas 方法,無需為尋找此內容的任何人使用任何列表/字典理解 -
d = {"key_1":[[1, 2], [3, 4]], "key_2":[[1, 2], [3, 4]]}
df = pd.DataFrame(d).T.stack().droplevel(-1).apply(pd.Series)
print(df)
0 1
key_1 1 2
key_1 3 4
key_2 1 2
key_2 3 4
%%timeit
pd.DataFrame(d).T.stack().droplevel(-1).apply(pd.Series)
100 個循環,5 個循環中的最佳循環:每個循環 2.56 毫秒
%%timeit
pd.DataFrame((k, *l) for k, v in d.items() for l in v).set_index(0)
1000 個循環,5 個循環中的最佳循環:每個循環 719 µs
%%timeit
cols = ['col1', 'col2']
pd.DataFrame({k: zip(*v) for k,v in d.items()}, index=cols).T.explode(cols)
100 個循環,5 個循環中的最佳循環:每個循環 6.53 毫秒
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.