1. 程式人生 > 程式設計 >用python給csv裡的資料排序的具體程式碼

用python給csv裡的資料排序的具體程式碼

1、使用argparse元件,獲取命令列引數;使用re元件,獲取需要查詢的字串所在行

2、使用pandas元件,對檔案進行排序。

3、命令列執行資料獲取及排序,寫入檔案;

以下是完整程式碼:

#coding:utf-8
importre
importargparse
importpandasaspd
parser=argparse.ArgumentParser(description='manualtothisscript')
parser.add_argument('--ip',type=str,default=None)
parser.add_argument('--type',default=None)
args=parser.parse_args()
filterStr=args.ip+""+args.type
f1=file('perf.csv','r')
perfdata=f1.readlines()
f1.close()
results=[]
f2=open('filter.csv','w')
f2.writelines(perfdata[0])
foriinperfdata:
n=re.findall(filterStr,i)
ifn:
f2.writelines(i)
f2.close()
df=pd.read_csv('filter.csv')
df=df.sort_values('elapsed',ascending=False)
df.to_csv('filterOrder.csv',index=False)

例項擴充套件:

Python對csv排序

#/usr/bin/evn python
# -*- coding: utf-8 -*-
import sys
from operator import itemgetter

# input_file = open(sys.argv[1])
input_file = open("D:\\tmp\\a.csv")
output_file = open("D:\\tmp\\asorted.csv","w")

table = []

for line in input_file:
  col = line.split('|') 
  col[0] = col[0].strip()
  col[1] = int(col[1])
  col[2] = int(col[2]) 
  col[3] = int(col[3].strip())
  table.append(col) #巢狀列表table[[8,8][*,*],...]

table_sorted = sorted(table,key=itemgetter(1,2),reverse=True)#先後按列索引1,2排序,降序排列

output_file.write('header' + '\n')
for row in table_sorted:          #遍歷讀取排序後的巢狀列表
  row = [str(x) for x in row]       #轉換為字串格式,好寫入文字
  output_file.write("\t".join(row) + '\n')
  

input_file.close()
output_file.close()

以上就是用python給csv裡的資料排序的具體程式碼的詳細內容,更多關於用python給csv裡的資料如何排序的資料請關注我們其它相關文章!