Home > Mobile >  Create 1 row dataframe from dictionary, with three columns and attach variable to first column
Create 1 row dataframe from dictionary, with three columns and attach variable to first column

Time:11-03

I have a dictionary with a set of data as follows:

fruit_dict = {'apples': 12.0, 'pears': 14.0, 'oranges': 5.0, 'lemons': 2.0}

I would like to create a dataframe of these items with the title of each fruit as a column as well as having one DATE column, like so (capitalised column titles needed):

 DATE         APPLES   PEARS   ORANGES   LEMONS
 2017-09-01   12.0     14.0    5.0       2.0

I have created the necessary variable for the date as follows:

now = datetime.datetime.now()
today = now.strftime("%d/%m/%Y")
print(today)

However when I try and create a dataframe from the dictionary, I end up with:

apples 0 12.0
pears  0 14.0
oranges 0 5.0
lemons 0 2.0

The code I try to use to create said frame is:

fruit_price = pd.DataFrame.from_dict(fruit_dict, orient='index').stack()
fruit_price.columns = ['DATE','APPLES', 'PEARS', 'ORANGES', 'LEMONS']
print(fruit_price)

If you have any advice I would greatly appreciate it.

CodePudding user response:

First merge dictionaries for Date column and then pass to list in DataFrame constructor:

d = {**{'date': today}, **fruit_dict}
fruit_price = pd.DataFrame([d]).rename(columns=lambda x: x.upper())
  • Related