【问题标题】:What is the fastest way to build a DataFrame piece by piece?逐个构建 DataFrame 的最快方法是什么?
【发布时间】:2013-06-13 16:29:30
【问题描述】:

我正在从Bloomberg 下载价格数据,并希望以最快且内存占用最少的方式构建一个DataFrame。假设我通过 python 向彭博社提交了一个数据请求,以获取从 2000 年 1 月 1 日到 2013 年 1 月 1 日所有当前 S&P 500 股票的价格数据。数据由ticker 返回,然后是日期和值,一次一个。我目前的方法是为要存储的日期创建一个列表,为要存储的价格创建另一个列表,并在从彭博数据请求响应中读取每个列表时附加一个日期和价格。然后,当读取特定代码的所有日期和价格时,我使用

为代码创建一个 DataFrame
ticker_df = pd.DataFrame(price_list, index = dates_list, columns= [ticker], dtype=float)

我为每个代码执行此操作,在读取每个代码的数据后将每个代码数据帧附加到列表 >。当所有代码数据帧都制作完成后,我将所有单独的数据帧合并到一个数据帧中:

lg_index = []
for num in range(len(df_list)):
    if len(lg_index) < len(df_list[num].index):
        lg_index = df_list[num].index  # Use the largest index for creating the result_df
result_df = pd.DataFrame(index= lg_index)
for num in range(len(df_list)):
    result_df[df_list[num].columns[0]] = df_list[num]

我这样做的原因是因为每个股票代码的指数都不相同(如果一只股票仅在去年首次公开募股,等等)

我猜一定有更好的方法来使用更少的内存和更快的方式完成我在这里所做的事情,我只是想不出。谢谢!

【问题讨论】:

    标签: python performance memory pandas dataframe


    【解决方案1】:

    我不能 100% 确定你的目标是哪个,但你可以 concat 一个 DataFrame 列表:

    pd.concat(df_list)
    

    例如:

    In [11]: df = pd.DataFrame([[1, 2], [3, 4]])
    
    In [12]: pd.concat([df, df, df])
    Out[12]:
       0  1
    0  1  2
    1  3  4
    0  1  2
    1  3  4
    0  1  2
    1  3  4
    
    In [13]: pd.concat([df, df, df], axis=1)
    Out[13]:
       0  1  0  1  0  1
    0  1  2  1  2  1  2
    1  3  4  3  4  3  4
    

    或进行外部合并/加入:

    In [14]: df1 = pd.DataFrame([[1, 2]], columns=[0, 2])
    
    In [15]: df.merge(df1, how='outer')  # do several of these
    Out[15]:
       0  1   2
    0  1  2   2
    1  3  4 NaN
    

    merge, join, concatenate section of the docs

    【讨论】:

      猜你喜欢
      • 2017-12-11
      • 1970-01-01
      • 2021-12-08
      • 2011-12-23
      • 2011-09-26
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      相关资源
      最近更新 更多