简体   繁体   中英

how to sort CSV columns files with Python

I really need your help here: I am attaching an Excel file - and trying to sort its second column ("Time") in the right way (taking under consideration seconds). I am embarrassed to confess how much time I've been wasting on this..

PAPER   TIME    ACTION  PRICE   AMOUNT

1026    01/12/2013 9:03 BID 124 84,888

1026    18/04/2013 9:01 BID 120.5   14,888

1026    19/01/2013 9:02 BID 121 24,888

1026    21/04/2013 9:05 BID 122 44,888

1026    20/04/2013 9:04 BID 121.5   34,888

1026    15/10/2013 9:06 BID 123.5   74,888

1026    17/04/2013 9:00 BID 120 4,888

1026    22/04/2013 9:07 BID 122.5   54,888

1026    27/04/2013 9:08 BID 123 64,888

This data stored in a CSV file called yaniv123.csv and the columns are between A to E (only 10 rows). How do I import this file and sort the B column (TIME) in the right way.. PLEASE HELP ME OUT :-) many many thanks !

As @Edwin van Mierlo mentioned, the headers need to adjust. You can use comma separated but you need to make sure amount comma is removed. If not, then use semicolon instead:

PAPER;TIME;ACTION;PRICE;AMOUNT

1026;01/12/2013 9:03;BID;124;84,888

1026;18/04/2013 9:01;BID;120.5;14,888

1026;19/01/2013 9:02;BID;121;24,888

1026;21/04/2013 9:05;BID;122;44,888

1026;20/04/2013 9:04;BID;121.5;34,888

1026;15/10/2013 9:06;BID;123.5;74,888

1026;17/04/2013 9:00;BID;120;4,888

1026;22/04/2013 9:07;BID;122.5;54,888

1026;27/04/2013 9:08;BID;123;64,888

However if everything is adjusted correctly, then you can use python panda library.

import pandas as pd    
df = pd.read_csv('sample.csv', parse_dates=True, delimiter=";")
df['TIME'] = pd.to_datetime(df.TIME)
print(df.head())
print(df.sort('TIME'))

The output should be: PAPER TIME ACTION PRICE AMOUNT

1026 01/12/2013 9:03 BID 124.0 84,888

1026 15/10/2013 9:06 BID 123.5 74,888

1026 17/04/2013 9:00 BID 120.0 4,888

1026 18/04/2013 9:01 BID 120.5 14,888

1026 19/01/2013 9:02 BID 121.0 24,888

1026 20/04/2013 9:04 BID 121.5 34,888

1026 21/04/2013 9:05 BID 122.0 44,888

1026 22/04/2013 9:07 BID 122.5 54,888

1026 27/04/2013 9:08 BID 123.0 64,888

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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