简体   繁体   中英

Create dataframe from dictionary with column names

I'm attempting to create a dataframe with dictionary keys and values in two different columns then name then name the columns with string names

Here is my dictionary:

my_dict = {'amd_0': 102, 'amd_3': 11}

Column names:

columns = ['column1', column2']

Desired output:

column1 column2
amd_0   102
amd_3   11

I tried from_dict but I'm having a hard time naming the columns. Any help is appreciated.

You can create a dataframe using the dictionary items and specify the columns list as the columns:

>>> df = pd.DataFrame(my_dict.items(), columns=columns)
>>> df
  column1  column2
0   amd_0      102
1   amd_3       11

Why would to_dict be your choice? You already HAVE a dict. You need to convert that TO a dataframe.

my_dict = {'amd_0': 102, 'amd_3': 11}
columns = ['column1', 'column2']

import pandas as pd
df = pd.DataFrame( my_dict.items(), columns=columns )
print(df)

Output:

  column1  column2
0   amd_0      102
1   amd_3       11

I realized I over-complicated things, but will leave my answer up as it will work in some edge cases. One of which being even if your columns list were longer than the number of my_dict items.

data = {col:[k, v] for col, k, v in zip(columns, *my_dict.items())}
df = pd.DataFrame(data)
print(df)

# Output:

  column1  column2
0   amd_0      102
1   amd_3       11

Most likely not the best method but this is the first thing that came to mind:

my_dict = {'amd_0': 102, 'amd_3': 11}
cols = ['column1', 'column2']
df=pd.DataFrame(my_dict,index=[0]).T.reset_index()
df.rename(columns={'index':cols[0],0:cols[1]})

you want to use this format if you want to specify the column names

my_dict = {"column1": ['amd_0', 'amd_3'], 'column2': [102, 11]}
print(pd.DataFrame(my_dict))

or this format if you want to specify rows too

my_dict = {"column1": {'row 1': 'amd_0', 'row 2': 'amd_3'},
       'column2': {'row 1': 102, 'row 2': 11}}
print(pd.DataFrame(my_dict))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM