首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何按另一列对现有列进行排序?

问如何按另一列对现有列进行排序?
EN

Stack Overflow用户
提问于 2022-04-15 23:58:07
回答 2查看 53关注 0票数 0

嗨,我正试着用另一种方法对熊猫中现有的栏目进行分类。这是我的熊猫数据集的输出

代码语言:javascript
复制
d_id a  b   c   d   sort_d_id
3    1  1   0   0   53
21   0  0   0   1   32
32   0  1   0   1   32
32   0  1   0   1   3
53   0  0   1   0   21

基本上,我想按d_id按sort_d_did排序。我想要的结果是

代码语言:javascript
复制
d_id a  b   c   d   sort_d_id
53   0  0   1   0   53
32   0  1   0   1   32
32   0  1   0   1   32
3    1  1   0   0   3
21   0  0   0   1   21

你能告诉我怎么做吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-04-16 00:46:56

以下是如何做到这一点:

代码语言:javascript
复制
# Get the d_id and sort_d_id columns for easy handling and rearranging
sort_d_id = df["sort_d_id"].tolist()
d_id = df["d_id"].tolist()

# Also get the row indices (i.e. 0 to 4) in order.
indices = list(range(len(d_id)))

# The 1st column of arr will be indices, 2nd column is sort_d_id, 3rd column is d_id.
arr = np.array([indices, sort_d_id, d_id]).T

# Sort columns according to sort_d_id.
arr = arr[np.argsort(arr[:, 1])]

# The order is now the d_id indices mapped to the sort_id_indices
# e.g. d_id[0] will become d_id[3], d_id[1] will become d_id[4], etc.
new_order = arr[:, 0]

# But we don't want that; we want sort_d_id mapped to the d_id indices.
# So we do another reordering and get the new indices.
new_order_zipped = sorted(zip(new_order, indices))
final_order = list(map(list, zip(*new_order_zipped)))[1]

# Reorder by the final indices.
df = df.reindex(final_order)

# Replace the sort_d_id column which got messed up during reordering.
df["sort_d_id"] = sort_d_id

# Reset indices if you want
df = df.reset_index(drop=True)

得到的df现在看起来应该是什么样子的。我知道,这很让人困惑,但它确实能正常工作。

票数 1
EN

Stack Overflow用户

发布于 2022-04-16 01:10:31

我想得到您想要的输出的唯一方法是:

代码语言:javascript
复制
df_1 = df['sort_d_id'].sort_values(ascending=False, key=lambda x: x.astype('string'))
df_2 = df.drop('sort_d_id', axis=1).sort_values('d_id', ascending=False, key=lambda x: x.astype('string')).reset_index(drop=True)
df = pd.concat([df_1, df_2], axis=1,)[df.columns]
print(df)

输出:

代码语言:javascript
复制
   d_id  a  b  c  d  sort_d_id
0    53  0  0  1  0         53
1    32  0  1  0  1         32
2    32  0  1  0  1         32
3     3  1  1  0  0          3
4    21  0  0  0  1         21
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71889972

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档