python字典转数据框_Python:如何将数据框字典转换为一个大数据框,而列名称是上一字典的关键?...

So my dataframe is made from lots of individual excel files, each with the the date as their file name and the prices of the fruits on that day in the spreadsheet, so the spreadsheets look something like this:

15012016:

Fruit Price

Orange 1

Apple 2

Pear 3

16012016:

Fruit Price

Orange 4

Apple 5

Pear 6

17012016:

Fruit Price

Orange 7

Apple 8

Pear 9

So to put all that information together I run the following code to put all the information into a dictionary of dataframes

(all fruit price files stored in 'C:\Fruit_Prices_by_Day'

#find all the file names

file_list = []

for x in os.listdir('C:\Fruit_Prices_by_Day'):

file_list.append(x)

file_list= list(set(file_list))

d = {}

for date in Raw_list:

df1 = pd.read_excel(os.path.join('C:\Fruit_Prices_by_Day', date +'.xlsx'), index_col = 'Fruit')

d[date] = df1

Then this is the part where I'm stuck. How do I then make this dict into a dataframe where the column names are the dict keys i.e. the dates, so I can get the price of each fruit per day all in the same dataframe like:

15012016 16012016 17012016

Orange 1 4 7

Apple 2 5 8

Pear 3 6 9

解决方案

You can try first set_index of all dataframes in comprehension and then use concat with remove last level of multiindex in columns:

print d

{'17012016': Fruit Price

0 Orange 7

1 Apple 8

2 Pear 9, '16012016': Fruit Price

0 Orange 4

1 Apple 5

2 Pear 6, '15012016': Fruit Price

0 Orange 1

1 Apple 2

2 Pear 3}

d = { k: v.set_index('Fruit') for k, v in d.items()}

df = pd.concat(d, axis=1)

df.columns = df.columns.droplevel(-1)

print df

15012016 16012016 17012016

Fruit

Orange 1 4 7

Apple 2 5 8

Pear 3 6 9

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值