gpt4 book ai didi

python - 如何在 DataFrame 中有效更新一组行值?如何使这个算法具有可扩展性?

转载 作者:太空宇宙 更新时间:2023-11-03 21:03:25 30 4
gpt4 key购买 nike

我的算法存在一些效率问题,我将通过片段进行解释:

  1. 首先创建df_fs。我在这里创建一个随机 DataFrame 以使其与示例一起使用

    import pandas as pd
    import numpy as np
    import random as rd
    import string

    R = 2500 # ROWS / 2
    C = 100 # COLUMNS
    NPROF = 1 # NUMBER OF PROFILES, up to 6

    STNNBR = 'STNNBR'
    d = {}
    for x in range(C):
    key = ''.join(rd.choices(string.ascii_uppercase + string.digits, k=10))
    nan_list = [np.nan] * R
    float_list = [float(1000 * rd.random()) for i in range(R)]
    l = nan_list + float_list
    rd.shuffle(l)
    d[key] = l

    d[STNNBR] = [int(200 * rd.random()) for i in range(R*2)]

    df_fs = pd.DataFrame(d)
  2. 列表 cur_plot_cols 表示我们要使用的列的名称:

    pos_list = []
    while len(pos_list) < 20:
    v = int(C * rd.random())
    if v not in pos_list:
    pos_list.append(v)
    d_keys = list(d.keys())
    cur_plot_cols = [d_keys[p] for p in pos_list]
  3. prof_df 是一个巨大的 DataFrame,我使用许多 NaN 值和许多列进行初始化。列数随着 cur_plot_colsNFPROF 的增加而增加:

    tab_list = ['SALNTY', 'OXYGEN', 'NITRAT', 'PHSPHT', 'SILCAT', 'ALKALI', 'TCARBN', 'PH_TOT', 'CFC_11', 'CFC_12', 'CFC113', 'SF6']
    compound_cols = []
    for tab in tab_list:
    for col in cur_plot_cols:
    for n in range(NPROF):
    compound_cols.append('{}_{}_{}'.format(tab, col, n))

    d_aux = {}
    if compound_cols != []:
    d_aux = dict.fromkeys(compound_cols, [])
    prof_df = pd.DataFrame(d_aux) # init empty columns
    prof_df['INDEX'] = df_fs.index.values
    prof_df = prof_df.set_index(['INDEX'])
  4. 使示例正常工作所需的更多变量:

    plot_prof_invsbl_points = True
    stt_order_reversed = [31] # up to 6 elements
    tabs_flags_plots = {
    'NITRAT': { # tab name
    'flag': 'NITRAT_FLAG_W',
    },
    'SALNTY': {
    'flag': 'SALNTY_FLAG_W',
    },
    }
    visible_flags = [3, 4, 5, 6]
  5. 最后是有问题的算法,标有FIXME的行是主要瓶颈

    f = cur_plot_cols + [STNNBR]
    df_fs = df_fs.filter(f)

    for tab in tab_list:
    i = NPROF - 1
    for stt in stt_order_reversed:
    for col in cur_plot_cols:
    df_aux = df_fs[(df_fs[STNNBR] == stt) & df_fs[col].notnull()]
    if plot_prof_invsbl_points is False: # this is never True in this example extracted from the original code
    if tab in tabs_flags_plots.keys():
    flag = tabs_flags_plots[tab]['flag']
    df_aux = df_aux[df_aux[flag].isin(visible_flags)]
    prof_df.loc[df_aux.index.values, '{}_{}_{}'.format(tab, col, i)] = df_aux[col] # FIXME: this is the main bottle neck
    i -= 1

测量

我用 line_profile 测量了时间工具,这是结果:

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
31 13 114.0 8.8 0.0 for tab in tab_list:
32 12 148.0 12.3 0.0 i = NPROF - 1
37 24 267.0 11.1 0.0 for stt in stt_order_reversed:
38 372 12430.0 33.4 0.0 for col in cur_plot_cols:
39 360 12890156.0 35806.0 13.1 df_aux = df_fs[(df_fs[STNNBR] == stt) & df_fs[col].notnull()]
40 360 11687.0 32.5 0.0 if plot_prof_invsbl_points is False:
41 flag = self.env.tabs_flags_plots[tab]['flag']
42 df_aux = df_aux[df_aux[flag].isin(self.env.visible_flags)]
43 360 85075802.0 236321.7 86.3 prof_df.loc[df_aux.index.values, '{}_{}_{}'.format(tab, col, i)] = df_aux[col]
44 12 201.0 16.8 0.0 i -= 1

有什么建议可以让这些线路更快吗?

df_aux = df_fs[(df_fs[STNNBR] == stt) & df_fs[col].notnull()]

prof_df.loc[df_aux.index.values, '{}_{}_{}'.format(tab, col, i)] = df_aux[col]

注释

实际上,我在 DataFrame 中使用的真正索引是哈希值,也就是说,字符串。

我必须更新 prof_df DataFrame 列。但是列名称是用参数 [tab, col, i] 指定的,我需要迭代它们以设置我想要在每次迭代中更新的列。有没有办法更快地迭代并更新这些列?还有其他选择吗?

不久前我使用这个表达式来分配分组值:

ml_df['xs{}'.format(n_plot)] = df_p.groupby('STNNBR').apply(lambda x: list(x[col_x_name]))

但我不知道如何在这里应用相同的方法,因为这次我需要分配左侧的列名称i值。

该算法需要 6 秒才能完成,太多了。

最佳答案

我仍然对你的问题感到困惑,但我认为你应该尝试使用枚举查看循环:

http://book.pythontips.com/en/latest/enumerate.html

这将允许您使用 i 值以及列名称。

关于python - 如何在 DataFrame 中有效更新一组行值?如何使这个算法具有可扩展性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55579532/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com