![](/img/trans.png)
[英]How to convert pandas df to dictionary with lists nested in the list?
[英]Convert dictionary with nested lists to a specific pandas df structure
如何将dictionary
转换为下面的“所需输出”?
我有一个嵌套列表作为值的dictionary
:
dictionary = {'Person1': ['a', 1, 'b', 2], 'Person2': ['c', 3, 'd', 4]} #(the dict is longer than this, this is just an example)
所需的 output:
姓名 | 信 | 价值 |
---|---|---|
'人 1' | '一个' | 1 |
'人 1' | 'b' | 2 |
'人2' | 'C' | 3 |
'人2' | 'd' | 4 |
当前代码:
import pandas as pd
df = pd.DataFrame.from_dict(dictionary)
通过压缩列表理解中的列表的对和解对值,将字典更改为元组列表,并传递给DataFrame
构造函数:
L = [(k, *x) for k, v in dictionary.items() for x in zip(v[::2], v[1::2])]
df = pd.DataFrame(L, columns=['name','letter','value'])
print (df)
name letter value
0 Person1 a 1
1 Person1 b 2
2 Person2 c 3
3 Person2 d 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.