【问题标题】:Progress bar for pandas .corr() methodpandas .corr() 方法的进度条
【发布时间】:2020-08-26 12:48:43
【问题描述】:

我正在尝试使用tqdm 或其他库在以下代码行中显示进度条:

corrmatrix = adjClose.corr('spearman')

其中 adjClose 是一个dataframe,它有许多股票代码作为列,并按日期索引了多年的收盘价。输出最终是一个相关矩阵。

随着更多代码被添加到dataframe,此代码往往会花费成倍增加的时间,我想要某种进度的可视化表示,以表明代码仍在运行。除非我严重忽略了某些事情,否则 Google 在这方面的表现并不多。

【问题讨论】:

    标签: python pandas correlation tqdm


    【解决方案1】:

    注意:由于计算时间增加,这不是一个真正可行的答案。根据我的测量,当使用小数据帧(高达 40 倍)时,它的接缝会显着增加,但是当使用大数据帧时,它大约是 2 - 3 倍。

    也许有人可以找到自定义函数calc_corr_coefs的更有效实现。

    我已经设法使用 pythons tqdm 模块来显示进度,但这需要我使用它的df.progress_apply() 函数。下面是一些示例代码:

    import time
    from tqdm import tqdm
    import numpy as np
    import pandas as pd
    
    
    def calc_corr_coefs(s: pd.Series, df_all: pd.DataFrame) -> pd.Series:
        """
        calculates the correlation coefficient between one series and all columns in the dataframe
    
        :param s:       pd.Series; the column from which you want to calculate the correlation with all other columns
        :param df_all:  pd.DataFrame; the complete dataframe
    
        return:     a series with all the correlation coefficients
        """
    
        corr_coef = {}
        for col in df_all:
            # corr_coef[col] = s.corr(df_all[col])
            corr_coef[col] = np.corrcoef(s.values, df_all[col].values)[0, 1]
    
        return pd.Series(data=corr_coef)
    
    
    df = pd.DataFrame(np.random.randint(0, 1000, (10000, 200)))
    
    t0 = time.perf_counter()
    
    # first use the basic df.corr()
    df_corr_pd = df.corr()
    
    t1 = time.perf_counter()
    print(f'base df.corr(): {t1 - t0} s')
    
    # compare to df.progress_apply()
    tqdm.pandas(ncols=100)
    df_corr_cust = df.progress_apply(calc_corr_coefs, axis=0, args=(df,))
    
    t2 = time.perf_counter()
    print(f'with progress bar: {t2 - t1} s')
    
    print(f'factor: {(t2 - t1) / (t1 - t0)}')
    

    我希望这会有所帮助,并且有人能够加快实施速度。

    【讨论】:

      猜你喜欢
      • 2019-08-10
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-13
      相关资源
      最近更新 更多