用python給csv里的數(shù)據(jù)排序的具體代碼
1、使用argparse組件,獲取命令行參數(shù);使用re組件,獲取需要查找的字符串所在行
2、使用pandas組件,對文件進(jìn)行排序。
3、命令行執(zhí)行數(shù)據(jù)獲取及排序,寫入文件;
以下是完整代碼:
#coding:utf-8
import re
import argparse
import pandas as pd
parser = 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.type
f1=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 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] #轉(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)注腳本之家其它相關(guān)文章!
相關(guān)文章
python mongo 向數(shù)據(jù)中的數(shù)組類型新增數(shù)據(jù)操作
這篇文章主要介紹了python mongo 向數(shù)據(jù)中的數(shù)組類型新增數(shù)據(jù)操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12
使用django的objects.filter()方法匹配多個(gè)關(guān)鍵字的方法
今天小編就為大家分享一篇使用django的objects.filter()方法匹配多個(gè)關(guān)鍵字的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
Python 2.6.6升級到Python2.7.15的詳細(xì)步驟
這篇文章主要介紹了Python 2.6.6升級到Python2.7.15的詳細(xì)步驟,本文分步驟給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12
python numpy之np.random的隨機(jī)數(shù)函數(shù)使用介紹
這篇文章主要介紹了python numpy之np.random的隨機(jī)數(shù)函數(shù)使用介紹,需要的朋友可以參考下2019-10-10
解決pycharm無法識別本地site-packages的問題
今天小編就為大家分享一篇解決pycharm無法識別本地site-packages的問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10

