简体   繁体   中英

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

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.

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())

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