精华内容
下载资源
问答
  • I'm trying to order a .csv file with just over 300 entries and output it all back out ordered by the numerical values in one specific column under a dialect.Here's the code I've written so far but it ...

    I'm trying to order a .csv file with just over 300 entries and output it all back out ordered by the numerical values in one specific column under a dialect.

    Here's the code I've written so far but it just seems to output the data as it went in

    import csv

    import itertools

    from itertools import groupby as gb

    reader = csv.DictReader(open('Full_List.csv', 'r'))

    groups = gb(reader, lambda d: d['red label'])

    result = [max(g, key=lambda d: d['red label']) for k, g in groups]

    writer = csv.DictWriter(open('output.csv', 'w'), reader.fieldnames)

    writer.writeheader()

    writer.writerows(result)

    There's only 50 rows in the whole file that contain a value under the dialect "red label" and all the others are left blank.

    It's in the Z column on the .csv(but not that last one) so I'd assume the index of the column is 25(0 being the first).

    Any help would be greatly appreciated.

    解决方案

    How about using pandas?

    import pandas as pd

    df = pd.read_csv('Full_List.csv')

    df = df.sort('red label')

    df.to_csv('Full_List_sorted.csv', index=False)

    You may need to adjust the options to read_csv and to_csv to match the format of your CSV file.

    展开全文
  • with open('room2.csv') as csvfile: readCSV = csv.reader(csvfile) srt = sorted((sum(map(int,row)) for row in readCSV), reverse=True) If you want to write to a file: with open('room2.csv','r') as csv...

    I want to get the scores which the user has to input then order the scores in ascending order however I am struggling to do so. Below is my code so far and it doesn't display the scores in order.Thanks in advance and your help is very much appreciated.

    classa = input("what class are you in?")

    if classa == "1":

    file=open("class 1.csv", "a+")

    if classa == "2":

    file=open("room2.csv", "a+")

    if classa == "3":

    file=open("class3.csv", "a+")

    score1= int(input("Enter the score 1 results: "))

    score2= int(input("Enter the score 2 results: "))

    score3= int(input("Enter the score 3 results: "))

    newrecord =score1,",",score2,",",score3

    file.write(newrecord)

    file.write("\n")

    file.close()

    import csv

    import operator

    with open('room2.csv','r') as csvfile:

    readCSV = csv.reader(csvfile, delimiter=',')

    for row in readCSV:

    print (row)

    解决方案

    You also cannot write a tuple to the file which is what newrecord = score1,",",score2,",",score is creating. You need to make a string from the scores and write that:

    newrecord = "{},{},{}\n".formmat(score1,score2,score3)

    file.write(newrecord)

    To sort existing scores you just need to call sorted on each row, using int as the key to sorted so you values are compared as integers not strings, set reverse=True to order from highest to lowest.

    with open('room2.csv','r') as csvfile:

    readCSV = csv.reader(csvfile)

    for row in readCSV:

    srt_row = sorted(row,key=int,reverse=True)

    To sum each row and then sort, sum the values after mapping to ints again setting reverse=True to sort from high to low:

    with open('room2.csv') as csvfile:

    readCSV = csv.reader(csvfile)

    srt = sorted((sum(map(int,row)) for row in readCSV), reverse=True)

    If you want to write to a file:

    with open('room2.csv','r') as csvfile, open("out.csv","w") as out:

    readCSV = csv.reader(csvfile)

    for scre in sorted((sum(map(int, row)) for row in readCSV), reverse=True):

    out.write(str(scre))

    展开全文
  • python读取文件csv数值列排序

    千次阅读 2020-03-16 12:31:45
    python读取文件csv数值列排序 最近用python弄三张表格的合并,期间对文件列进行排序,发现一个不错的代码: from operator import itemgetter input_file = open("PDBhaemoglobinReport.csv") output_file = ...

    python读取文件csv,按数值列排序

    最近用python弄三张表格的合并,期间对文件列进行排序,发现一个不错的代码:

    from operator import itemgetter
    
    input_file = open("PDBhaemoglobinReport.csv")
    output_file = open("PDBhaemoglobinSorted.csv","w")
    
    table = []
    header = input_file.readline() #读取并弹出第一行
    for line in input_file:
        col = line.split(',') #每行分隔为列表,好处理列格式
        col[3] = float(col[3][1:-1])
        col[4] = int(col[4][1:-2]) #各行没有先strip 末位是\n
        table.append(col) #嵌套列表table[[8,8][*,*],...]
    
    table_sorted = sorted(table, key=itemgetter(3, 4))#先后按列索引3,4排序
    
    output_file.write(header + '\t')
    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()
    

    附数据如下:

    =
    PDBhaemoglobinReportcsv内容

    PDB ID,Chain ID,Exp. Method,Resolution,Chain Length
    “1A4F”,“A”,“X-RAY DIFFRACTION”,“2.00”,“141”
    “1C7C”,“A”,“X-RAY DIFFRACTION”,“1.80”,“283”
    “1CG5”,“A”,“X-RAY DIFFRACTION”,“1.60”,“141”
    “1FAW”,“A”,“X-RAY DIFFRACTION”,“3.09”,“141”
    “1HDA”,“A”,“X-RAY DIFFRACTION”,“2.20”,“141”
    “1IRD”,“A”,“X-RAY DIFFRACTION”,“1.25”,“141”
    “1KFR”,“A”,“X-RAY DIFFRACTION”,“1.85”,“147”
    “1QPW”,“A”,“X-RAY DIFFRACTION”,“1.80”,“141”
    “1SPG”,“A”,“X-RAY DIFFRACTION”,“1.95”,“144”
    “1UX8”,“A”,“X-RAY DIFFRACTION”,“2.15”,“132”

    PDBhaemoglobinSorted.csv :

    PDB ID,Chain ID,Exp. Method,Resolution,Chain Length
    “2W72” “A” “X-RAY DIFFRACTION” 1.07 141
    “1IRD” “A” “X-RAY DIFFRACTION” 1.25 141
    “2H8F” “A” “X-RAY DIFFRACTION” 1.3 143
    “2WY4” “A” “X-RAY DIFFRACTION” 1.35 140
    “2D5X” “A” “X-RAY DIFFRACTION” 1.45 141
    “4ESA” “A” “X-RAY DIFFRACTION” 1.45 143
    “3VRG” “A” “X-RAY DIFFRACTION” 1.5 141
    “1CG5” “A” “X-RAY DIFFRACTION” 1.6 141
    “4HBI” “A” “X-RAY DIFFRACTION” 1.6 146
    “1QPW” “A” “X-RAY DIFFRACTION” 1.8 141

    ######本人AI小白,希望各位多多指教!

    原文链接:https://www.cnblogs.com/koujiaodahan/p/8047109.html

    展开全文
  • I have a csv file that looks like this:Tom,10Jack,10Alice,10Ben,9I need to be able to sort by the second column from highest to lowest.I have tried the following code:import csvfile = open("bestscores...

    I have a csv file that looks like this:

    Tom,10

    Jack,10

    Alice,10

    Ben,9

    I need to be able to sort by the second column from highest to lowest.

    I have tried the following code:

    import csv

    file = open("bestscores.csv","r")

    reader = csv.reader(file, delimiter = ' ')

    sort = sorted(reader,key=lambda x: int(x[1]), reverse=True)

    print(sort)

    This results in the following error:

    ValueError: invalid literal for int() with base 10: 'Tom,10'

    How can I solve this?

    解决方案

    You are using the wrong delimiter and sorting the wrong index. This should work for you:

    import csv

    with open("bestscores.csv","r") as fh

    reader = csv.reader(fh, delimiter = ',')

    sort = sorted(reader, key=lambda x: int(x[1]), reverse=True)

    print(sort)

    展开全文
  • with open('C:\\Users\\lys\\Desktop\\countries_zh .csv','r') as f:#打开文件地址我的地址是这个别人的还得改一下 table=[]#开个列表 No1=f.readline()#读取一行因为我的第一行是目录所有先读取了就不用计算了 ...
  • python对csv文件的处理

    千次阅读 2015-12-11 13:37:10
    Python对csv文件的处理
  • 我的input.csv看起来是这样的: day,month,year,lat,long01,04,2001,45.00,120.0002,04,2003,44.00,118.00 我试图删除“year”栏及其所有条目。 总共有40多个条目,从1960年到2010年不等...我有以下标...
  • 使用re组件,获取需要查找的字符串所在行2、使用pandas组件,对文件进行排序。3、命令行执行数据获取及排序,写入文件;以下是完整代码:#coding:utf-8import reimport argparseimport pandas as pdparser = ...
  • python切分csv文件

    2021-06-29 19:55:28
    ## python按列将一个大csv文件划分为多个小csv 有时候从数据库导出的文件会非常大,而且各种类型的数据会混杂在一起,在进行数据分析时会比较麻烦,我们需要将大文件某种规律分为几个小文件,便于处理,这里用到了...
  • #用python绘制工件的图像import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dcsv_data = np.loadtxt(open('/home/yifei/Proj/PythonProj/getboundary/...
  • 2、使用pandas组件,对文件进行排序。 3、命令行执行数据获取及排序,写入文件; 以下是完整代码: #coding:utf-8 import re import argparse import pandas as pd parser = argparse.ArgumentParser...
  • python 对csv文件的一些操作

    千次阅读 2018-03-24 10:27:19
    本文只是为了方便自己下次编程所做的记录,可能所写您来说没有帮助,不喜勿喷。     with open(filepath_poi, encoding='gbk') as f: reader = csv.reader(f) # first_row = reader.__next__() # second_...
  • 使用python读取csv文件,转成字典存储,支持int,str,float等
  • pandas把csv文件数据按列排序

    千次阅读 2020-03-14 16:18:09
    原本的数据类型凌乱不按照日期排序,不利于数据分析 import pandas as pd df = pd.read_csv('clientinfo-截止2019-1...
  • pythoncsv文件读取

    2019-07-25 19:37:29
    csv文件读取 csv csv文件(Comma-Separated Values)是一种以逗号作为分隔符(当然也可以以其他字符作为分隔符)、以行为数据单位的纯文本数据文件. 如果发现中文是乱码,那是因为data.csv文件的编码格式是utf-8...
  • 我导入一个包含以下内容的CSV文件:Id; PartNrInt; Some; other; stuff;R1; 1234-5678; x1; y1; z1;R2; 1234-6789; x2; y2; z2;R3; 1234-5678; x3; y3; z3;然后我有一个数据库,其中包含每个PartNrInt的附加数据.我...
  • Python批量处理csv文件(筛选

    千次阅读 2020-12-09 16:59:27
    批量读取同一文件夹下的csv文件,进行数据处理(这里是挑选需要的向量,生成新文件),保存到新文件夹(csv文件同名) 代码 #!/user/bin/env python3 # -*- coding: utf-8 -*- import os import re import ...
  • The name of a user and their score from a quiz is entered in a csv file. I want to sort the name of the user alphabetically, however I don't know how to do this. Thanks in advance. Here are snippets o...
  • 文章目录前言一、处理需求二、处理过程1.代码分析过程2....图中,黄色是读取到的文件中的csv文件,但是排序就很尴尬,序号排序是1,10,11…2,20,22… csv文件是个嵌套的列表,故用list[0][0]得到第一
  • python进阶练习题:排序CSV文件【难度:2级】: Sort一个CSV文件 你得到一个CSV文件的内容的字符串.由分号分隔.结果 第一行包含的名字.结果 编写出列的字母和incasesensitive名称排序列的方法. 一个例子: ...
  • 处理csv文件时,经常用到多级或者多属性排序,我们可以使用如下方式轻松搞定多级排序Python 2.x使用如下代码:先按照第一即x[0]升序排序,再按照第二即x[0]升序排序。如需降序排列,需在sorted函数体内...
  • 整理了一些个人在利用python处理csv文件时经常用到的一些自定义方法,放在这里主要方便自己查阅,也可以给其他人做参考 目录 输出CSV文件的匹配/不匹配的记录 调整csv文件的顺序 CSV转换器 抽取特定 ...
  • # -*- coding: utf-8 -*-#python 27#xiaodeng#CSV文件的写入(行写入)import csv#csv文件,是一种常用的文本格式,用以存储表格数据,很多程序在处理数据时会遇到csv格式文件#csv文件的写入(行写入)def ...
  • csv.DictReader()读取和加载文件,然后根据一的值处理另外一的值。 代码很简单,看看就知道啥意思了。 # -*- coding:utf-8 -*- #author:zgd import pandas import csv with open("url_features_3_zgd....
  • how to sort xls file column wise and write it to another file with entire row using python ? the xls file has to be sorted column wise. And after sorting it has to be writen into another file.解决方案...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 16,146
精华内容 6,458
关键字:

python对csv文件按列排序

python 订阅