用python給csv里的數(shù)據(jù)排序的具體代碼
1、使用argparse組件,獲取命令行參數(shù);使用re組件,獲取需要查找的字符串所在行
2、使用pandas組件,對(duì)文件進(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對(duì)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ù)如何排序的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. IntelliJ IDEA恢復(fù)刪除文件的方法2. IntelliJ IDEA配置Tomcat服務(wù)器的方法3. docker鏡像完全卸載的操作步驟4. 使用Maven 搭建 Spring MVC 本地部署Tomcat的詳細(xì)教程5. idea刪除項(xiàng)目的操作方法6. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法7. IntelliJ IDEA導(dǎo)入jar包的方法8. idea導(dǎo)入maven項(xiàng)目的方法9. idea重置默認(rèn)配置的方法步驟10. Docker 部署 Prometheus的安裝詳細(xì)教程

網(wǎng)公網(wǎng)安備