繁体   English   中英

排序没有标题的CSV文件

[英]Sort CSV file that has no headers

如果没有标题,如何对csv文件排序? 我的数据如下,我想按日期排序

14/09/2018      Manchester      Manchester United    Chelsea             
06/09/2018      Manchester      Manchester United    Tottenham Hotspur   
05/09/2018      Manchester      Manchester United    Liverpool           
13/09/2018      Chelsea         Chelsea              Manchester United   
10/09/2018      Chelsea         Chelsea              Tottenham Hotspur   
09/09/2018      Chelsea         Chelsea              Liverpool           
12/09/2018      Tottenham       Tottenham Hotspur    Manchester United   
08/09/2018      Tottenham       Tottenham Hotspur    Chelsea             
07/09/2018      Tottenham       Tottenham Hotspur    Liverpool           
11/09/2018      Liverpool City  Liverpool            Manchester United   
15/09/2018      Liverpool City  Liverpool            Chelsea             
04/09/2018      Liverpool City  Liverpool            Tottenham Hotspur 

您可以为此使用熊猫:

import pandas as pd
from datetime import datetime

df = pd.read_csv('dummy.csv', names=['Date', 'City', 'Home', 'Away']) # read in csv with header assignment to columns
df['Date'] = pd.to_datetime(df.Date) #convert 'Dates' column to datetime
df = df.sort_values(by='Date').reset_index() # sort by date and reindex

输出:

         Date            City               Home               Away
0       2018-04-09  Liverpool City          Liverpool  Tottenham Hotspur
1       2018-05-09      Manchester  Manchester United          Liverpool
2       2018-06-09      Manchester  Manchester United  Tottenham Hotspur
3       2018-07-09       Tottenham  Tottenham Hotspur          Liverpool
4       2018-08-09       Tottenham  Tottenham Hotspur            Chelsea
5       2018-09-09         Chelsea            Chelsea          Liverpool
6       2018-09-13         Chelsea            Chelsea  Manchester United
7       2018-09-14      Manchester  Manchester United            Chelsea
8       2018-09-15  Liverpool City          Liverpool            Chelsea
9       2018-10-09         Chelsea            Chelsea  Tottenham Hotspur
10      2018-11-09  Liverpool City          Liverpool  Manchester United
11      2018-12-09       Tottenham  Tottenham Hotspur  Manchester United

如果您的日期是唯一的,则可以打开文件并将其读入字典。 如果不是,那么您将要查找要排序的辅助键。

def read_from_file(file_name):
    data = {}
    with open(file_name, 'r') as f:
        for line in f.readlines():
            datum = extract_data(line)
            data[get_key(datum)] = datum

def sort(data):
    return [data[key] for key in sort(data.iterkeys())]

在此示例中,您将要实现两种方法: extract_data()将采用文件的一行(作为字符串)并将其放入您要使用的表单中(类或字典或等等)和get_key ,它将提取您的唯一键(可以是您的日期或您的日期以及其他内容)。 请注意,表中的每个元素的get_key必须是唯一的,因此您应该确保它是唯一的。 否则,字典排序将无法正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM