今天要对csv的数据进行列重拍序,有点费劲,还是用的不熟练
csv数据类似,交换db两列
a b c d
0 196 242 3 881250949
1 186 302 3 891717742
2 22 377 1 878887116
3 244 51 2 880606923
4 166 346 1 886397596
import pandas as pd
import numpy as np
file = 'ppp.csv'
df = pd.read_csv(file, sep='\t', header=None ,names=['a' , 'b' ,'c' ,'d'])
cols = list(df)
cols.insert(2,cols.pop(cols.index('d'))) # 2是将d放在哪一列,cols.pop(cols.index('d')) 是要换的d列
df = df.loc[:,cols] # 开始按照两列互换
print(df)
结果
a b d c
0 196 242 881250949 3
1 186 302 891717742 3
2 22 377 878887116 1
3 244 51 880606923 2
4 166 346 886397596 1
另外,其它用到的如下:
返回列数:df.shape[1]
返回行数:df.shape[0] 或者:len(df)
生成连续数字列表,并插入到某一列:

这篇博客介绍了如何使用Python的Pandas库对CSV数据进行列重拍序,包括插入新列、替换列值和列交换等操作。还展示了如何读取多个CSV文件,处理其中特定列的内容,并保存处理后的文件。同时提到了获取DataFrame行数和列数的方法。
最低0.47元/天 解锁文章
665

被折叠的 条评论
为什么被折叠?



