Home > Back-end >  Create dataframe from dictionary with column names
Create dataframe from dictionary with column names

Time:08-27

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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]})

CodePudding user response:

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))
  • Related