极客小将

您现在的位置是:首页 » python编程资讯

资讯内容

python中怎么交换列的顺序

极客小将2021-01-17-
简介DataFrame的列有时我们需要对添加的列或原来的列进行交换顺序。data = pd.DataFrame(np.arange(16).reshape(4,4),columns=list('abcd'))In [88]: dataOut[88]

Lsh少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

DataFrame的列有时我们需要对添加的列或原来的列进行交换顺序。Lsh少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

data = pd.DataFrame(np.arange(16).reshape(4,4),columns=list('abcd'))In [88]: data Out[88]:     a   b   c   d 0   0   1   2   3 1   4   5   6   7 2   8   9  10  11 3  12  13  14  15

一:获取DataFrame列标签Lsh少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

cols = list(data)In [94]: cols Out[94]: ['a', 'b', 'c', 'd']

二:改变列标签为指定顺序Lsh少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

cols.insert(0,cols.pop(cols.index('c')))

insert方法:Lsh少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

功能Lsh少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

insert()函数用于将指定对象插入列表的指定位置。Lsh少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

语法Lsh少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

list.insert(index, obj)

参数Lsh少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

index: 对象obj需要插入的索引位置。Lsh少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

obj: 插入列表中的对象。Lsh少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

三:利用loc获取新的DataFrame,拷贝交换顺序后的DataFrameLsh少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

data = data.loc[:,cols]In [100]: data Out[100]:     c   a   b   d 0   2   0   1   3 1   6   4   5   7 2  10   8   9  11 3  14  12  13  15

更多python知识请关注Python视频教程栏目。Lsh少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

网友点评

共有5条评论来说两句吧...

在线客服