简体   繁体   English

如何从熊猫中的字典值创建多行和多列

[英]how to create multiple rows and columns from a dictionary value in pandas

I have a data frame like following 我有一个如下的数据框

id,  values
1, {'foo':2 , 'bar':2}
2, {'baz':20}
and so on

I want to transform this dataframe into 我想将此数据框转换为

id val1 val2
1  foo    2
1 bar     2
2 baz     20

and so on.. I dont want to like iterate each row in dataframe.. as I am pretty sure there is a way in pandas to do the above? 依此类推。.我不想在数据框中重复每一行。.我很确定熊猫中有一种方法可以执行上述操作?

IIUC PS: you can add rename at the end IIUC PS:您可以在末尾添加rename

df.set_index('id')['values'].apply(pd.Series).stack().reset_index()
Out[920]: 
   id level_1     0
0   1     bar   2.0
1   1     foo   2.0
2   2     baz  20.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python 如何使用多个 pandas dataframe 列中的值作为元组键和单个列作为值来创建字典 - Python how to create a dictionary using the values in multiple pandas dataframe columns as tuple keys and a single column as value 如何通过字典在熊猫中创建行 - How to create rows in pandas by dictionary 如何为列表中的一个键创建具有多个值的 Python 字典,然后创建具有一列和多行的 pandas 数据框 - How can I create a Python dictionary with multiple values for one key from a list, to then create a pandas dataframe with one column and multiple rows 在 pandas 中创建具有多列的嵌套字典 - Create a nested dictionary with multiple columns in pandas 如何根据条件从 pandas 列创建字典 - How do I create dictionary from pandas columns based on condition 如何从给定键的行创建列:pandas 列中的值对? - How to create columns from rows given key:value pair in the column in pandas? 如何创建具有一个索引键列和多个值列的字典 - how to create a dictionary with one index key column and multiple value columns 从熊猫中的多列创建字典 - creating dictionary from multiple columns in pandas 通过(pandas)在一组中的多个列中创建字典 - creating a dictionary from multiple columns in a group by (pandas) 用字典中的常量替换多个 pandas 列 - Replace multiple pandas columns with constants from dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM