Reputation: 4353
My question is a bit linked to this one, except that I want to turn my lists into rows not columns, and specify the names of the columns.
For example, I start with a dictionary:
my_dict = {'label1' : [0.1, 1.1, 32.1] , 'label2' : [12.3, 5.3, 2.4], 'label3' : [1.5, 7.5, 7.4]}
I want to be able to specify column names like:
cols = ['labels','val1' ,'val2, 'val3']
and create the dataframe
labels | val1 | val2 | val3
label1 0.1 1.1 32.1
label2 12.3 5.3 2.4
label3 1.5 7.5 7.4
Upvotes: 1
Views: 65
Reputation: 17176
You can use pandas.DataFrame.from_dict but using 'orientation' of index rather than columns.
This allows the labels to be used as the index.
df = pd.DataFrame.from_dict(my_dict, orient='index', columns = ['val1' ,'val2', 'val3'])
df.index.name = 'labels' # rename index column
print(df)
Output
val1 val2 val3
labels
label1 0.1 1.1 32.1
label2 12.3 5.3 2.4
label3 1.5 7.5 7.4
Upvotes: 0
Reputation: 38425
You want a transposed dataframe and then assign column names,
df = pd.DataFrame(my_dict)
df = df.T.reset_index()
df.columns = cols
labels val1 val2 val3
0 label1 0.1 1.1 32.1
1 label2 12.3 5.3 2.4
2 label3 1.5 7.5 7.4
Upvotes: 1