python处理csv数据排序-用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" + " ")

for row in table_sorted: #遍历读取排序后的嵌套列表

row = [str(x) for x in row] #转换为字符串格式,好写入文本

output_file.write(" ".join(row) + " ")

input_file.close()

output_file.close()

以上就是用python给csv里的数据排序的具体代码的详细内容,更多关于用python给csv里的数据如何排序的资料请关注脚本之家其它相关文章!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值