在Pandas DataFrame对象中重新定义索引

编程入门 行业动态 更新时间:2024-10-11 23:15:28
本文介绍了在Pandas DataFrame对象中重新定义索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试重新索引熊猫DataFrame对象,

I am trying to re-index a pandas DataFrame object, like so,

From: a b c 0 1 2 3 1 10 11 12 2 20 21 22 To : b c 1 2 3 10 11 12 20 21 22

我正在如下所示进行操作,并且得到了错误的答案.有关如何执行此操作的任何线索?

I am going about this as shown below and am getting the wrong answer. Any clues on how to do this?

>>> col = ['a','b','c'] >>> data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col) >>> data a b c 0 1 2 3 1 10 11 12 2 20 21 22 >>> idx2 = data.a.values >>> idx2 array([ 1, 10, 20], dtype=int64) >>> data2 = DataFrame(data,index=idx2,columns=col[1:]) >>> data2 b c 1 11 12 10 NaN NaN 20 NaN NaN

知道为什么会这样吗?

推荐答案

为什么不简单地使用 set_index 方法?

Why don't you simply use set_index method?

In : col = ['a','b','c'] In : data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col) In : data Out: a b c 0 1 2 3 1 10 11 12 2 20 21 22 In : data2 = data.set_index('a') In : data2 Out: b c a 1 2 3 10 11 12 20 21 22

更多推荐

在Pandas DataFrame对象中重新定义索引

本文发布于:2023-11-28 16:18:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643099.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:象中   索引   定义   Pandas   DataFrame

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!