【问题标题】:I have a dictionary of dataframes. I need a merged dataframe我有一个数据框字典。我需要一个合并的数据框
【发布时间】:2021-08-31 17:57:56
【问题描述】:

我有一个数据框字典。代码通过列表读取代码并获取 Open High Low Close 和 Volume,然后添加带有代码名称的列。所有不需要的列都被删除。这适用于列表中的所有项目并存储在字典中。这是代码..

dataframe_collection = {}
for i in range(0,len(list)):
   i=list[i]
   ohlc = fetchOHLC(i, "day", 5)
   ohlc['base'] = ohlc.close / ohlc.close[0]
   ohlc.rename(columns={'base': i}, inplace=True)
   # Drop un-required columns
   ohlc.drop(ohlc.iloc[:, 0:5], axis=1, inplace=True)
   dataframe_collection[i]= ohlc

每个数据框都有相同的索引。我打算创建一个合并的通用数据框,使数据框看起来像这样

date                         ACC            HINDUNILVR           LT   
2021-08-26 00:00:00+05:30    1.000000       1.000000            1.000000
2021-08-27 00:00:00+05:30    1.031882       1.004332            1.026539    
2021-08-30 00:00:00+05:30    1.048757       1.007988            1.040326
2021-08-31 00:00:00+05:30    1.057810       1.020102            1.020102
. 

【问题讨论】:

    标签: python dataframe dictionary


    【解决方案1】:

    我希望已经解决了你的问题:

    #convert your dictionnary to a list
    list_dataframes = dataframe_collection.values()
    #keep the dictionnary keys with the same order, in case you will need them
    list_dataframes_keys = dataframe_collection.keys()
    
    #if the date is not the index
    df = pd.concat([x.set_index('date') for x in list_dataframes], axis=1)
    #if the date is the index
    df = pd.concat([x for x in list_dataframes], axis=1)
    

    编辑:

    @chris 建议的一行代码:

    pd.concat([v.set_index('date') for k,v in dataframe_collection.items()], axis=1)
    

    【讨论】:

    • pd.concat([v.set_index('date') for k,v in dataframe_collection.items()], axis=1)
    • 克里斯非常感谢您的回复。我收到以下错误。 KeyError:“['date'] 均不在列中”
    • 感谢 Issam,它的工作就像一个魅力......非常感谢您的超级快速帮助。
    • @Chris 建议给出以下错误。 KeyError:“['date'] 均不在列中”
    • @ANen 在您的情况下,请改用 pd.concat([v for k,v in dataframe_collection.items()], axis=1)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    相关资源
    最近更新 更多