繁体   English   中英

生成新行和 append 到 DataFrame 的最快方法

[英]Fastest way to generate new rows and append them to DataFrame

我想在一定的时间间隔内改变数据集中的目标值。 当使用 500 个数据时,大约需要 1.5 秒,但我有大约 100000 个数据。 大部分执行时间都花在了这个过程中。 我想加快速度。

append 行到 DataFrame 的最快和最有效的方法是什么? 我尝试了此链接中的解决方案,尝试创建字典,但我做不到。

这是 500 条数据大约需要 1.5 秒的代码。

def add_new(df,base,interval):
    df_appended = pd.DataFrame() 
    np.random.seed(5)
    s = np.random.normal(base,interval/3,4)
    s = np.append(s,base)
    for i in range(0,5):
        df_new = df
        df_new["DeltaG"] = s[i]
        df_appended = df_appended.append(df_new)
    return df_appended
def add_new(df1,base,interval,has_interval):
    dictionary = {}
    if has_interval == 0:
        for i in range(0,5):
            dictionary[i] = (df1.copy())
    elif has_interval == 1:
        np.random.seed(5)
        s = np.random.normal(base,interval/3,4)
        s = np.append(s,base)
        for i in range(0,5):
            df_new = df1
            df_new[4] = s[i]

            dictionary[i] = (df_new.copy())
    return dictionary

有用。 整个数据大约需要 10 秒。 感谢您的回答。

pandas 中的 DataFrames 是 memory 的连续和平,因此附加或连接等数据帧效率非常低 - 此操作创建新的 DataFrames 并覆盖旧 DataFrames 中的所有数据。 但是作为列表和字典的基本 python 结构不是,当 append 向它添加新元素时 python 只是创建指向新结构元素的指针。

所以我的建议 - 让你在列表或字典上处理所有数据,最后将它们转换为 DataFrame。

另一个建议是创建最终大小的预分配 DataFrame 并使用.iloc更改其中的值。 但它只有在您知道生成的 DataFrame 的最终大小时才有效。

带代码的好例子:向 pandas DataFrame 添加一行

如果您需要更多代码示例 - 请告诉我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM