gpt4 book ai didi

Python:如何将 Dataframes 字典变成一个大数据框,其中列名是前一个字典的键?

转载 作者:太空狗 更新时间:2023-10-29 20:16:42 26 4
gpt4 key购买 nike

所以我的数据框是由许多单独的 excel 文件组成的,每个文件都以日期作为文件名,并在电子表格中显示当天的水果价格,因此电子表格看起来像这样:

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

因此,为了将所有这些信息放在一起,我运行以下代码将所有信息放入一个数据帧字典中(所有水果价格文件存放在'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

然后这是我卡住的部分。然后我如何将这个字典变成一个数据框,其中列名是字典键,即日期,这样我就可以在同一个数据框中获得每天每种水果的价格,例如:

          15012016   16012016   17012016   
Orange 1 4 7
Apple 2 5 8
Pear 3 6 9

最佳答案

可以先试试set_index comprehension 中的所有数据帧,然后使用 concat删除列中 multiindex 的最后一层:

 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

关于Python:如何将 Dataframes 字典变成一个大数据框,其中列名是前一个字典的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35717706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com