在 pandas 中按列随机排列行 [英] Shuffle rows by a column in pandas

查看:72
本文介绍了在 pandas 中按列随机排列行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框示例.

    c1     c2
0   1       a
1   2       b
2   3       c
3   4       d
4   5       e

给定一个模板c1 = [3, 2, 5, 4, 1],我想根据列c1的新顺序更改行的顺序,因此它将如下所示:

Given a template c1 = [3, 2, 5, 4, 1], I want to change the order of the rows based on the new order of column c1, so it will look like:

    c1     c2
0    3      c
1    2      b
2    5      e
3    4      d
4    1      a

我找到了以下线程,但随机播放是随机的.嗯.

I found the following thread, but the shuffle is random. Cmmiw.

随机播放DataFrame行

推荐答案

如果值在列表中和c1列中也是唯一的,请使用

If values are unique in list and also in c1 column use reindex:

df = df.set_index('c1').reindex(c1).reset_index()
print (df)
   c1 c2
0   3  c
1   2  b
2   5  e
3   4  d
4   1  a

处理列表中和列中重复项的常规解决方案:

General solution working with duplicates in list and also in column:

c1 = [3, 2, 5, 4, 1, 3, 2, 3]

#create df from list 
list_df = pd.DataFrame({'c1':c1})
print (list_df)
   c1
0   3
1   2
2   5
3   4
4   1
5   3
6   2
7   3

#helper column for count duplicates values
df['g'] = df.groupby('c1').cumcount()
list_df['g'] = list_df.groupby('c1').cumcount()

#merge together, create index from column and remove g column
df = list_df.merge(df).drop('g', axis=1)
print (df)
   c1 c2
0   3  c
1   2  b
2   5  e
3   4  d
4   1  a
5   3  c

这篇关于在 pandas 中按列随机排列行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆