Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将包含列表作为值的字典转换为数据帧_Python_List_Pandas_Dictionary_Dataframe - Fatal编程技术网

Python 将包含列表作为值的字典转换为数据帧

Python 将包含列表作为值的字典转换为数据帧,python,list,pandas,dictionary,dataframe,Python,List,Pandas,Dictionary,Dataframe,我有这样一本python字典: tag_dict = {'001':['apple', 'orange'], '002':['banana', 'strawberry', 'peach']} 我想将此字典传输到如下数据帧: id value 001 apple 001 orange 002 banana 002 strawberry 002 peach 有两列:“id”和“value” 我有两行id为001,但“value”列中的值不同:“apple”和“orange”。对于id 002类

我有这样一本python字典:

tag_dict = {'001':['apple', 'orange'], '002':['banana', 'strawberry', 'peach']}
我想将此字典传输到如下数据帧:

id  value
001 apple
001 orange
002 banana
002 strawberry
002 peach
有两列:“id”和“value”


我有两行id为001,但“value”列中的值不同:“apple”和“orange”。对于id 002类似。

如果要使用
数据帧。从_dict()
可以使用
stack()
进行后续操作,然后重置索引:

>>> tag_dict = {'001':['apple','orange'], '002':['banana','strawberry','peach']}
>>> df = pd.DataFrame.from_dict(tag_dict, orient='index').stack()
>>> df.reset_index(level=0)
  level_0           0
0     001       apple
1     001      orange
0     002      banana
1     002  strawberry
2     002       peach
然后,您可以重命名这些列,并为其提供您喜欢的任何索引:

>>> df.columns = ['id', 'value']
>>> df.set_index('id')
          value
id             
001       apple
001      orange
002      banana
002  strawberry
002       peach

你尝试了什么,怎么不起作用?我在pandas软件包pd中尝试了这个功能。DataFrame.from_dict()。但它不会重复id,它只会变成两行。你有什么想法吗?非常感谢你,它对我有用。还有一个问题,如果我可以让id列作为索引。我想我会得到一个只有一列的数据框?很高兴它有帮助。您可以编写
df.set_index('id')
将id列设置为索引,然后您将拥有一个只有一列('value')的数据帧。