user14618562
user14618562

Reputation:

Creating dataframe from many dictionaries considering their keys as index in the dataframe

I have many dictionaries with same keys and I would like to save their values in a common dataframe.

Here two dictionaries.

row2POS = {0: 101232831, 1: 43067616,}
row2CHROM = {0: '3', 1: '17'}   

And my empty dataframe

column_names = ['CHROM','POS']
df_stage1 = pd.DataFrame(columns = column_names)

My desire output

df_stage1
    CHROM POS
0    3    101232831
1   17    43067616

When I faced this I though that could be easy bu I can figure out how to do this and I have not found this after some search

Upvotes: 1

Views: 33

Answers (3)

ansev
ansev

Reputation: 30940

Use:

df_stage1 = pd.DataFrame((row2CHROM, row2POS)).set_axis(column_names, axis=1)

or

df_stage1 = pd.DataFrame(dict(zip(column_names, (row2CHROM, row2POS))))

print(df_stage1)


  CHROM        POS
0     3  101232831
1    17   43067616

Upvotes: 0

zabop
zabop

Reputation: 7932

You can do:

row2POSdf = pd.DataFrame.from_dict(row2POS,orient='index')
row2CHROMdf = pd.DataFrame.from_dict(row2CHROM,orient='index')
df=pd.concat([row2CHROMdf,row2POSdf],axis=1)
df.columns=['CHROM','POS']

This will give you:

  CHROM        POS
0     3  101232831
1    17   43067616

Upvotes: 0

Asish M.
Asish M.

Reputation: 2647

In [180]: pd.DataFrame.from_dict(dict(zip(column_names, [row2CHROM, row2POS])))
Out[180]:
  CHROM        POS
0     3  101232831
1    17   43067616

Upvotes: 2

Related Questions