Pandas中的.corr()方法进度条

7

我想要在下面这段代码的行中使用 tqdm 或其他库来展示进度条:

corrmatrix = adjClose.corr('spearman')

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

随着更多的股票代码被添加到数据框中,这段代码往往需要指数级的时间,我希望能够以某种视觉表示形式来表示进度,以表明代码仍在运行。 谷歌在此方面并没有提供太多信息,除非我粗心大意地忽略了什么。

1个回答

1
注意: 由于计算时间增加,这并不是一种真正可行的答案。根据我的测量,当使用小的数据框(高达40倍)时,时间会显著增加,但是当使用大的数据框时,增加的因素约为2-3倍。
也许有人可以找到更有效的自定义函数calc_corr_coefs的实现方法。
我成功地使用Python的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)}')

我希望这可以帮助到您,也希望有人能够加速实施。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接