[英]Python dictionary with list as values: how do I select values?
I have a dictionary with lists as values:我有一个以列表为值的字典:
d = {'a':[0,1],'b':[2,3]}
I want to create a dataframe with one column for the key and two columns for the values in the list:我想创建一个数据框,其中一列用于键,两列用于列表中的值:
|key |val1 |val2 |
|----|-----|-----|
|a |0 |1 |
|b |2 |3 |
|----|-----|-----|
My plan was to create three lists and just add these to a new dataframe.我的计划是创建三个列表,然后将它们添加到新的数据框中。 Works fine for the keys, but I don't know how to separate the elements in the list contained as values.
适用于键,但我不知道如何将列表中包含为值的元素分开。
Here is what I tried:这是我尝试过的:
key = d.keys()
val1 = d.values()[0]
val2 = d.values()[1]
What is the indexing of elements of a list that is stored as values in a dictionary?在字典中存储为值的列表元素的索引是什么?
So first of all if you want to create a data frame from a dictionary there is this method所以首先如果你想从字典创建一个数据框有这个方法
import pandas as pd
pd.DataFrame.from_dict(d, orient='index')
Check the doc to understand what orient
is doing.查看文档以了解
orient
正在做什么。 As per how to create this you can see the command yourself.根据如何创建它,您可以自己查看命令。
Also if you want to access the elements of the list and create the dataframe on your own you can do this此外,如果您想访问列表的元素并自己创建数据框,您可以这样做
for val in d.values():
print(val[0])
print(val[1])
#work with them
You can collect all these values in list as shown here by accessing the elements and then you can create dataframe pd.Dataframe()
您可以通过访问元素来收集列表中的所有这些值,如下所示,然后您可以创建数据帧
pd.Dataframe()
if you want to "manually" to select the elemnts for your columns you can use:如果您想“手动”为您的列选择元素,您可以使用:
{'key': list(d.keys()), **({'val%s' % i: list(map(lambda x: x[i], d.values())) for i in range(len(list(d.values())[0]))})}
output:输出:
{'key': ['a', 'b'], 'val0': [0, 2], 'val1': [1, 3]}
to get the DataFrame:获取数据帧:
pd.DataFrame({'key': list(d.keys()), **({'val%s' % i: list(map(lambda x: x[i], d.values())) for i in range(len(list(d.values())[0]))})})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.