Str*_*420 7 python numpy dataframe pandas
我想无序地打乱列;完全伪随机,一行代码。
前:
A B
0 1 2
1 1 2
Run Code Online (Sandbox Code Playgroud)
后:
B A
0 2 1
1 2 1
Run Code Online (Sandbox Code Playgroud)
到目前为止我的尝试:
df = df.reindex(columns=columns)
df.sample(frac=1, axis=1)
df.apply(np.random.shuffle, axis=1)
Run Code Online (Sandbox Code Playgroud)
您可以将np.random.default_rng()spermutation与 a 一起使用seed以使其可重现。
df = df[np.random.default_rng(seed=42).permutation(df.columns.values)]
Run Code Online (Sandbox Code Playgroud)
DataFrame.sample与设置为列 (1) 的轴参数一起使用:
df = df.sample(frac=1, axis=1)
print(df)
B A
0 2 1
1 2 1
Run Code Online (Sandbox Code Playgroud)
Series.sample或者与转换为的列一起使用Series并按子集更改列的顺序:
df = df[df.columns.to_series().sample(frac=1)]
print(df)
B A
0 2 1
1 2 1
Run Code Online (Sandbox Code Playgroud)