用python給csv里的數(shù)據(jù)排序的具體代碼
1、使用argparse組件,獲取命令行參數(shù);使用re組件,獲取需要查找的字符串所在行
2、使用pandas組件,對文件進(jìn)行排序。
3、命令行執(zhí)行數(shù)據(jù)獲取及排序,寫入文件;
以下是完整代碼:
#coding:utf-8import reimport argparseimport pandas as pdparser = argparse.ArgumentParser(description=’manual to this script’)parser.add_argument(’--ip’, type=str, default = None)parser.add_argument(’--type’, type=str, default=None)args = parser.parse_args()filterStr = args.ip + ' ' + args.typef1=file(’perf.csv’,’r’)perfdata=f1.readlines()f1.close()results = []f2 = open(’filter.csv’, ’w’)f2.writelines(perfdata[0])for i in perfdata: n = re.findall(filterStr, i) if n: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)
實(shí)例擴(kuò)展:
Python對csv排序
#/usr/bin/evn python# -*- coding: utf-8 -*-import sysfrom operator import itemgetter# input_file = open(sys.argv[1])input_file = open('D:tmpa.csv')output_file = open('D:tmpasorted.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] #轉(zhuǎn)換為字符串格式,好寫入文本 output_file.write('t'.join(row) + ’n’) input_file.close()output_file.close()
以上就是用python給csv里的數(shù)據(jù)排序的具體代碼的詳細(xì)內(nèi)容,更多關(guān)于用python給csv里的數(shù)據(jù)如何排序的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)2. 將properties文件的配置設(shè)置為整個Web應(yīng)用的全局變量實(shí)現(xiàn)方法3. 在JSP中使用formatNumber控制要顯示的小數(shù)位數(shù)方法4. 得到XML文檔大小的方法5. ASP.NET Core實(shí)現(xiàn)中間件的幾種方式6. 如何在jsp界面中插入圖片7. jsp實(shí)現(xiàn)textarea中的文字保存換行空格存到數(shù)據(jù)庫的方法8. 利用CSS3新特性創(chuàng)建透明邊框三角9. XML入門的常見問題(二)10. ASP常用日期格式化函數(shù) FormatDate()
