在不丢失或弄乱数据帧的情况下更改数据帧中的行顺序

2024-05-03 02:19:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

(Index)    sample    reads yeasts    
9          CO ref    10
10         CO raai   20
11         CO tus    30

我想根据sample,预期输出更改列的顺序:

(Index)    sample    reads yeasts    
9          CO ref    10
11         CO tus    30
10         CO raai   10

我对行的索引不感兴趣。你知道吗

我尝试了以下基于其他stackoverflow/google帖子的代码:

df=df.reindex(["CO ref","CO tus","CO raai"])

这将正确地更改索引,但所有其他列都获得值nan

我也试过:

df.index=["CO ref","CO tus","CO raai"]  

这会正确地更改索引,但其他列不会切换,因此会弄乱数据帧。你知道吗

此外:

df["sample"].index=["CO ref","CO tus","CO raai"]   

但这没用。你知道吗

我怎样才能让它工作?你知道吗


Tags: 数据samplerefdfindex顺序googlestackoverflow
1条回答
网友
1楼 · 发布于 2024-05-03 02:19:34

对于reindex,需要从sample列创建索引:

df=df.set_index(['sample']).reindex(["CO ref","CO tus","CO raai"]).reset_index()

或使用有序范畴:

cats = ["CO ref","CO tus","CO raai"]
df['sample'] = pd.CategoricalIndex(df['sample'], ordered=True, categories=cats)
df = df.sort_values('sample')

相关问题 更多 >