首页 > 解决方案 > 有效地按组对数据帧的一列进行洗牌

问题描述

我正在尝试对大型 Pandas 数据框进行排列测试。数据框如下所示:

    group  some_value  label
0       1           8      1
1       1           7      0
2       1           6      2
3       1           5      2
4       2           1      0
5       2           2      0
6       2           3      1
7       2           4      2
8       3           2      1
9       3           4      1
10      3           2      1
11      3           4      2

我想按列分组group,并打乱label列并写回数据框,最好就位。该some_value列应保持完整。结果应如下所示:

    group  some_value  label
0       1           8      1
1       1           7      2
2       1           6      2
3       1           5      0
4       2           1      1
5       2           2      0
6       2           3      0
7       2           4      2
8       3           2      1
9       3           4      2
10      3           2      1
11      3           4      1

我用过np.random.permutation,但发现它很慢。

df["label"] = df.groupby("group")["label"].transform(np.random.permutation

这似乎df.sample要快得多。如何使用df.sample()代替np.random.permutation和就地解决这个问题?

标签: pythonpandas

解决方案


我们可以使用sample 注意这是假设df=df.sort_values('group')

df['New']=df.groupby('group').label.apply(lambda x : x.sample(len(x))).values

或者我们可以通过

df['New']=df.sample(len(df)).sort_values('group').New.values

推荐阅读