【问题标题】:How to solve the performance warning while adding a dataframe in list in a for loop?在 for 循环中的列表中添加数据框时如何解决性能警告?
【发布时间】:2017-09-25 08:11:49
【问题描述】:

我创建了一个 for 循环,我得到了一个数据框(如下所示)作为输出。我将每个输出附加到一个空白列表中。我得到了输出,但有一个性能警告:

PerformanceWarning:向未矢量化的系列添加/减去 DateOffsets 数组

输出数据框:

截距坡度 0 3.008165 -0.001024 截距斜率 0 2.153798 0.001749

代码:

coeff = []

for x in something:
    #do something
    reg_df = DataFrame({"Slope":slope,"Intercept":intercept})
    coeff.append(reg_df)

为什么我会收到警告?

我该如何解决这个问题?

任何帮助将不胜感激。

【问题讨论】:

    标签: python pandas dataframe series


    【解决方案1】:

    我认为最好将值附加到列表并只调用一次DataFrame 构造函数:

    L = []
    for x in range(2):
        #do something
        slope = x * 2
        intercept = x ** 2
        L.append({"Slope":slope,"Intercept":intercept})
    
    print (L)
    [{'Slope': 0, 'Intercept': 0}, {'Slope': 2, 'Intercept': 1}]
    
    df = pd.DataFrame(L)
    print (df)
       Intercept  Slope
    0          0      0
    1          1      2
    

    另一个类似的解决方案:

    L = []
    for x in range(2):
        #do something
        slope = x * 2
        intercept = x ** 2
        L.append([slope,intercept])
    
    print (L)
    [[0, 0], [2, 1]]
    
    df = pd.DataFrame(L, columns=['Intercept','Slope'])
    print (df)
       Intercept  Slope
    0          0      0
    1          2      1
    

    【讨论】:

    • 使用第一种方法后,我得到了单个列表中的所有值?
    • 我认为在第一种方法中获取列表中的字典,在第二种方法中获取列表中的列表
    • 将它们转换为数据帧后,我得到的输出为 Slope Intercept 0 [-0.00102418207681] [3.00816500711]
    • 是否可以添加mre代码?因为我无法模拟你的问题。
    • 如果我正在运行您的代码,那么在 for 循环中只存储第一个结果而不存储其他结果。你能告诉我为什么吗??
    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 2011-10-02
    • 1970-01-01
    • 2019-12-26
    • 2017-12-23
    • 1970-01-01
    • 2019-03-02
    • 2022-08-10
    相关资源
    最近更新 更多