简体   繁体   English

如何从字典创建一个数据框,其中键和值都是列?

[英]How to create a Dataframe from Dictionary where the key and values are all columns?

Example of dictionary: 字典示例:

{'892420643555336193': (8374, 38224),

 '892177421306343426': (6181, 32765),

 '891815181378084864': (4091, 24675),

 '891689557279858688': (8512, 41548),

 '891327558926688256': (9219, 39740)}

I want a dataframe where (example of first row) 我想要一个数据框(第一行的示例)

Column A

892420643555336193

Column B

8374

Column C

38224

You can create a dataframe of your dictionary keys, and one of your dictionary values, and use pd.concat to combine them: 您可以创建一个包含字典键和一个字典值的数据pd.concat ,然后使用pd.concat进行组合:

import pandas as pd
# where d is your dictionary
df = pd.concat((pd.DataFrame(list(d.keys())),pd.DataFrame(list(d.values()))),axis=1)

>>> df
                    0     0      1
0  892420643555336193  8374  38224
1  892177421306343426  6181  32765
2  891815181378084864  4091  24675
3  891689557279858688  8512  41548
4  891327558926688256  9219  39740

Alternatively, create a normal dataframe with your dictionary, transpose it, and reset the index (note the ordering is switched): 或者,用您的字典创建一个普通的数据框,将其转置并重置索引(请注意顺序已切换):

df = pd.DataFrame(d).T.reset_index()
>>> df
                index     0      1
0  891327558926688256  9219  39740
1  891689557279858688  8512  41548
2  891815181378084864  4091  24675
3  892177421306343426  6181  32765
4  892420643555336193  8374  38224

You can then rename your columns as you wish: 然后,您可以根据需要重命名列:

df.columns = ['A','B','C']

暂无
暂无

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

相关问题 如何创建具有 2 个键的字典,其中第一个键是索引,第二个键来自列表,值来自 df 的列? - How can I create a dictionary with 2 keys where the the first key is the index, the second key is from a list and the values from columns of a df? 从数据框列和值创建嵌套字典 - Create a nested dictionary from dataframe columns and values 如何创建字典,其中每个键都是列表中的一个值,而每个值都是列表中除键之外的所有值 - How do I create a dictionary where every key is a value from a list, and every value is all the values from the list except the key 如何使用字典中的列名创建数据框 - How create dataframe with columns name from dictionary 从 dataframe 中的特定列创建每个键具有多个值的字典 - Creating a dictionary with multiple values per key from specific columns in a dataframe 如何从字典中创建一个pandas数据框,列名作为键,值作为行,其中值是二维数组 - how to create a pandas dataframe from a dictionary with column names as keys and values as rows where the values are 2-d array 如何将字典转换为 pandas dataframe,键和值位于两个单独的列中? - How to convert a dictionary into a pandas dataframe with key and values in two separate columns? 如何将 pandas 数据框列与字典键与数据框索引匹配的字典值相乘 - How to multiply pandas dataframe columns with dictionary value where dictionary key matches dataframe index 从数据框中的列创建字典 - create a dictionary from columns in a dataframe 从 2 列 Dataframe 创建字典 - Create dictionary from 2 columns of Dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM