溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python對csv里的數(shù)據(jù)排序的代碼詳解

發(fā)布時間:2020-07-18 09:20:58 來源:億速云 閱讀:189 作者:小豬 欄目:開發(fā)技術(shù)

這篇文章主要講解了python對csv里的數(shù)據(jù)排序的代碼詳解,內(nèi)容清晰明了,對此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會有幫助。

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)

實例擴(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()

看完上述內(nèi)容,是不是對python對csv里的數(shù)據(jù)排序的代碼詳解有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI