【问题标题】:Python: How to turn a dictionary of Dataframes into one big dataframe with column names being the key of the previous dict?Python:如何将数据框字典变成一个大数据框,其中列名是前一个字典的键?
【发布时间】:2016-06-13 13:31:48
【问题描述】:

所以我的数据框是由许多单独的 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

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

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

【问题讨论】:

    标签: python python-2.7 dictionary pandas dataframe


    【解决方案1】:

    您可以先尝试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
    

    【讨论】:

    【解决方案2】:

    解决方案:

    pd.concat(d, axis=1).sum(axis=1, level=0)
    

    说明:

    .concat(d, axis=1)之后你会得到

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

    并添加.sum(axis=1, level=0) 将其转换为

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

    【讨论】:

      【解决方案3】:

      这样的事情可能会起作用:遍历字典,使用字典键添加常量列,连接然后将日期设置为索引

      pd.concat(
          (i_value_df.assign(date=i_key) for i_key, i_value_df in d.items())
      ).set_index('date')
      

      【讨论】:

        猜你喜欢
        • 2022-10-01
        • 1970-01-01
        • 2020-01-01
        • 2019-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-28
        • 2019-11-04
        相关资源
        最近更新 更多