[英]Converting dictionary of tuples and lists as key values to pandas dataframe
I have a dictionary with tuples as keys and values as lists.我有一个字典,元组作为键,值作为列表。 I would like to convert it to a pandas dataframe for exporting it as an Excel table later.我想将其转换为 Pandas 数据框,以便稍后将其导出为 Excel 表。
Could someone suggest a clean way to achieve the table as below?有人可以建议一种干净的方法来实现下表吗? I would like to have the elements in the list in separate columns.我想将列表中的元素放在单独的列中。
dict={(a,b):[1,2][4,5],(a,c):[7,8][1,3],(b,c):[1,8][1,3]}
K钾 | X X | Y是 |
---|---|---|
a,b一、二 | 1 1 | 2 2 |
a,b一、二 | 4 4 | 5 5 |
a,c一、三 | 7 7 | 8 8 |
a,c一、三 | 1 1 | 3 3 |
b,c公元前 | 1 1 | 8 8 |
b,c公元前 | 1 1 | 3 3 |
Tried this, not getting desired result: df=pd.DataFrame.from_dict(dict, orient='index').T
试过了,没有得到想要的结果: df=pd.DataFrame.from_dict(dict, orient='index').T
Use:用:
import pandas as pd
# toy data
dic = {("a", "b"): [[1, 2], [4, 5]], ("a", "c"): [[7, 8], [1, 3]], ("b", "c"): [[1, 8], [1, 3]]}
# un-ravel the data to create the rows of the DataFrame
data = [[key, *value] for key, values in dic.items() for value in values]
# actually create the DataFrame
df = pd.DataFrame(data, columns=["K", "X", "Y"])
print(df)
Output输出
K X Y
0 (a, b) 1 2
1 (a, b) 4 5
2 (a, c) 7 8
3 (a, c) 1 3
4 (b, c) 1 8
5 (b, c) 1 3
The expression:表达方式:
data = [[key, *value] for key, values in dic.items() for value in values]
is a list comprehension , is equivalent to:是一个列表理解,相当于:
data = []
for key, values in dic.items():
for value in values:
data.append([key, *value])
Check if this helps:检查这是否有帮助:
import pandas as pd
dict={('a','b'):[[1,2],[4,5]],('a','c'):[[7,8],[1,3]],('b','c'):[[1,8],[1,3]]}
dt = []
for k,v in dict.items():
for ls in v:
dt.append([k,ls[0],ls[1]])
df = pd.DataFrame(dt,columns = ['Key','x','y'])
print (df)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.