栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

用python给csv里的数据排序的具体代码

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用python给csv里的数据排序的具体代码

1、使用argparse组件,获取命令行参数;使用re组件,获取需要查找的字符串所在行

2、使用pandas组件,对文件进行排序。

3、命令行执行数据获取及排序,写入文件;

以下是完整代码:

#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)

实例扩展:

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里的数据如何排序的资料请关注考高分网其它相关文章!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/18034.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号