簡體   English   中英

如何在python中將列轉換為數值以進行排序

[英]How to convert the column to numeric in python for sorting

我是python(學習者)的新手。 請檢查我的問題,並幫助我解決問題。

我有以下內容的csv文件

test,cycle,date,status
func,2,09/07/17,pass
func,10,09/08/17,fail
func,3,09/08/17,pass
func,1,09/08/17,no run
func,22,09/08/17,in progress
func,11,09/08/17,on hold

當我對第二列(循環)進行排序時,它顯示以下輸出

['func', '1', '09/08/17', 'no run']
['func', '10', '09/08/17', 'fail']
['func', '11', '09/08/17', 'on hold']
['func', '2', '09/07/17', 'pass']
['func', '22', '09/08/17', 'in progress']
['func', '3', '09/08/17', 'pass']

我在這里遇到的問題是它按字符串排序,因此它顯示輸出為1、10、11、2、22、3。但是我想按數字(整數/浮點數)對輸出進行排序,以便我將獲得輸出1,2,3,10,11,22

下面是我的小腳本。 您能幫我修改腳本,以便在排序之前將其列更改為數字嗎?

with open ('C:\Automation\sample.csv') as csvfile:

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

for row in readCSVfile:
sort = sorted(readCSVfile, key=operator.itemgetter(1), reverse = False)
 for eachline in sort:
print eachline`

您可以在閱讀以下內容時對其進行預處理:

#!python2
import csv
import operator

with open ('sample.csv','rb') as csvfile:
    readCSVfile = csv.reader(csvfile)
    header = next(readCSVfile)
    rows = []
    for row in readCSVfile:
        test,cycle,date,status = row
        rows.append([test,int(cycle),date,status])
rows.sort(key=operator.itemgetter(1))
for row in rows:
    print row

輸出:

['func', 1, '09/08/17', 'no run']
['func', 2, '09/07/17', 'pass']
['func', 3, '09/08/17', 'pass']
['func', 10, '09/08/17', 'fail']
['func', 11, '09/08/17', 'on hold']
['func', 22, '09/08/17', 'in progress']

您還可以使用其他排序鍵,將列保留為字符串:

#!python2
import csv
import operator

with open ('sample.csv','rb') as csvfile:
    readCSVfile = csv.reader(csvfile)
    header = next(readCSVfile)
    rows = [row for row in readCSVfile]
rows.sort(key=lambda row: int(row[1]))
for row in rows:
    print row

輸出:

['func', '1', '09/08/17', 'no run']
['func', '2', '09/07/17', 'pass']
['func', '3', '09/08/17', 'pass']
['func', '10', '09/08/17', 'fail']
['func', '11', '09/08/17', 'on hold']
['func', '22', '09/08/17', 'in progress']

然后,您必須將其轉換為數字。 Python csv模塊無法自動識別數據類型。

您可以通過類似的方法來做到這一點:

numberedCSV = []
for row in readCSVfile:
    row[1] = int(row[1])
    numberedCSV.append(row)

然后對numberedCSV進行排序。

順便說一句,我不明白您打算發布的代碼。 為什么需要兩個循環?

這可能是您要尋找的。

    # take second element for sort
def takeSecond(elem):
    return int(elem[1])

# random list
stuff = [['func', '1', '09/08/17', 'no run'],
 ['func', '10', '09/08/17', 'fail'],
 ['func', '11', '09/08/17', 'on hold'],
 ['func', '2', '09/07/17', 'pass'],
 ['func', '22', '09/08/17', 'in progress'],
 ['func', '3', '09/08/17', 'pass']]

# sort list with key
sortedList = sorted(stuff, key=takeSecond)

# print list
print('Sorted list:', sortedList)

干杯。

正如其他答案所說,您可以

  • 在排序時使用不是operator.itemgetter另一個函數將值轉換為int
  • 或使用for循環在排序之前轉換數組數據。

但是,如果經常使用這種表格數據,最好使用pandas 您需要安裝它,但是再次:如果經常執行此操作,那是值得的。

import pandas as pd

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

df['cycle'] = df['cycle'].astype(int)

print(df.sort_values(by='cycle'))

# or reverse
print(df.sort_values(by='cycle', ascending=False))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM