Dask DataFrame 计算多列分组内的平均值

Tal*_*war 5 python pandas dask

我有一个如图所示的数据框,我想要做的是沿“试验”列取平均值。对于每个subject,conditionsample(当所有这三列都具有值 1 时),取沿列试验(100 行)的数据的平均值。

我在熊猫中所做的如下

sub_erp_pd= pd.DataFrame()
for j in range(1,4):
    sub_c=subp[subp['condition']==j]
    for i in range(1,3073):
        sub_erp_pd=sub_erp_pd.append(sub_c[sub_c['sample']==i].mean(),ignore_index=True)
Run Code Online (Sandbox Code Playgroud)

但这需要很多时间..所以我想使用 dask 而不是 Pandas。但是在 dask 我在创建空数据框时遇到问题。就像我们在 Pandas 中创建一个空的数据框并将数据附加到它。

数据框的图像

正如@edesz 所建议的,我改变了我的方法
EDIT

%%time
sub_erp=pd.DataFrame()
for subno in progressbar.progressbar(range(1,82)):
    try:
        sub=pd.read_csv('../input/data/{}.csv'.format(subno,subno),header=None)
    except:
        sub=pd.read_csv('../input/data/{}.csv'.format(subno,subno),header=None)    
    sub_erp=sub_erp.append(sub.groupby(['condition','sample'], as_index=False).mean())
Run Code Online (Sandbox Code Playgroud)

使用 pandas 读取文件需要 13.6 秒,而使用 dask 读取文件需要 61.3 毫秒。但是在 dask 中,我在追加时遇到了麻烦。

注意- 原始问题的标题为Create an empty dask dataframe and append values to it

ede*_*esz 3

如果我理解正确的话,你需要

  • 使用groupby在此处阅读更多内容)对subject,conditionsample列 进行分组
    • 这会将这三列中每一列具有相同值的所有行收集到一个组中
  • 使用平均值.mean()
    • 这将为您提供每组内的平均值

生成一些虚拟数据

df = df = pd.DataFrame(np.random.randint(0,100,size=(100, 3)),
                        columns=['trial','condition','sample'])
df.insert(0,'subject',[1]*10 + [2]*30 + [5]*60)

print(df.head())
   subject  trial  condition  sample
0        1     71         96      34
1        1      2         89      66
2        1     90         90      81
3        1     93         43      18
4        1     29         82      32
Run Code Online (Sandbox Code Playgroud)

熊猫方法

聚合并采取mean

df_grouped = df.groupby(['subject','condition','sample'], as_index=False)['trial'].mean()

print(df_grouped.head(15))
    subject  condition  sample  trial
0         1         18      24     89
1         1         43      18     93
2         1         67      47     81
3         1         82      32     29
4         1         85      28     97
5         1         88      13     48
6         1         89      59     23
7         1         89      66      2
8         1         90      81     90
9         1         96      34     71
10        2          0      81     19
11        2          2      39     58
12        2          2      59     94
13        2          5      42     13
14        2          9      42      4
Run Code Online (Sandbox Code Playgroud)

达斯克方法

步骤 1. 导入

import dask.dataframe as dd
from dask.diagnostics import ProgressBar
Run Code Online (Sandbox Code Playgroud)

步骤 2. 将 Pandas 转换DataFrame为 Dask DataFrame,使用.from_pandas

ddf = dd.from_pandas(df, npartitions=2)
Run Code Online (Sandbox Code Playgroud)

步骤 3. 聚合并获取mean

ddf_grouped = (
    ddf.groupby(['subject','condition','sample'])['trial']
        .mean()
        .reset_index(drop=False)
            )

with ProgressBar():
    df_grouped = ddf_grouped.compute()
[                                        ] | 0% Completed |  0.0s
[########################################] | 100% Completed |  0.1s

print(df_grouped.head(15))
    subject  condition  sample  trial
0         1         18      24     89
1         1         43      18     93
2         1         67      47     81
3         1         82      32     29
4         1         85      28     97
5         1         88      13     48
6         1         89      59     23
7         1         89      66      2
8         1         90      81     90
9         1         96      34     71
10        2          0      81     19
11        2          2      39     58
12        2          2      59     94
13        2          5      42     13
14        2          9      42      4
Run Code Online (Sandbox Code Playgroud)

重要提示:此答案中的方法不使用创建空 Dask DataFrame 并向其附加值的方法,以便计算subjectconditionTrial分组内的平均值。相反,此答案提供了另一种方法(使用)来获得所需的最终结果(计算主题条件试验GROUP BY分组内的平均值)。