DataFrame列怎么在Pandas中交换顺序

发布时间:2020-12-14 14:31:18 作者:Leah
来源:亿速云 阅读:727

今天就跟大家聊聊有关DataFrame列怎么在Pandas中交换顺序,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

一、获取DataFrame列标签

import pandas as pd 
file_path = '/Users/Arithmetic/da-rnn-master/data/collectd67_power_after_test_smooth.csv' 
dataset = pd.read_csv(file_path)
cols = list(dataset)

['ps_state-stopped', 'ps_state-running', 'ps_state-blocked', 'ps_state-paging', 'ps_state-sleeping', 'ps_state-zombies', 'fork_rate', 'cpu-2-system', 'cpu-2-nice', 'cpu-2-steal',...]

二、改变列标签为指定顺序

import pandas as pd

file_path = '/Users/Arithmetic/da-rnn-master/data/collectd67_power_after_test_smooth.csv'
 
dataset = pd.read_csv(file_path)
cols = list(dataset)
print(cols)
cols.insert(0, cols.pop(cols.index('ps_state-running')))
print(cols)

这里改变第一列和第二列的位置顺序,用到了python list中的两个方法

insert方法:
1.功能
insert()函数用于将指定对象插入列表的指定位置。
2.语法
list.insert(index, obj)
3.参数
index: 对象obj需要插入的索引位置。
obj: 插入列表中的对象。
pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值

三、利用loc获取新的DataFrame,拷贝交换顺序后的DataFrame

import pandas as pd

file_path = '/Users/Arithmetic/da-rnn-master/data/collectd67_power_after_test_smooth.csv'
 
dataset = pd.read_csv(file_path)
cols = list(dataset)
print(cols)
cols.insert(0, cols.pop(cols.index('ps_state-running')))
print(cols)
data = dataset.loc[:, cols]

 四、保存csv覆盖原来的csv

import pandas as pd
 
file_path = '/Users/Arithmetic/da-rnn-master/data/collectd67_power_after_test_smooth.csv'

dataset = pd.read_csv(file_path)
cols = list(dataset)
print(cols)
cols.insert(0, cols.pop(cols.index('ps_state-running')))
print(cols)
data = dataset.loc[:, cols]
data.to_csv(file_path, index=False)

五、也可以这样

import pandas as pd
 
file_path = '/Users/Arithmetic/da-rnn-master/data/collectd67_power_after_test_smooth.csv'
 
dataset = pd.read_csv(file_path)
cols = list(dataset)
print(cols)
cols.insert(0, cols.pop(cols.index('ps_state-running')))
print(cols)
dataset.loc[:, ['ps_state-running', 'ps_state-stopped']] = dataset[['ps_state-stopped', 'ps_state-running']].values
dataset.columns = cols
dataset.to_csv(file_path, index=False)

看完上述内容,你们对DataFrame列怎么在Pandas中交换顺序有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. 怎么更改pandas dataframe中两列的位置
  2. pandas如何实现DataFrame行或列的删除方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

pandas dataframe dat

上一篇:利用jquery怎么实现一个淡入淡出的轮播图效果

下一篇:使用JavaScript编写一个轮播图效果

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》