Python Forum
Sorting columns from text file help - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Sorting columns from text file help (/thread-22512.html)



Sorting columns from text file help - nickglobal101 - Nov-15-2019

Hello! I'm very new to Python and need help figuring out how to sort by columns from a text file which is being throw off by the Date column (which has single white spaces, so trying to separate by tabs is not working).

Text file (sample) contents is below (actual text file is several thousand lines long).

Date           	   		Num1    Num2   
Sat. Aug 10, 2019              41          59          
Wed. Aug 07, 2019              47          8              
Sat. Aug 03, 2019               45          68  



The CODE I tried:

df = pd.read_csv('columns_test.txt', names=['Date','Num1','Num2'], skiprows=1, sep='\s+', engine='python')
df
The OUTPUT I get is:

Date	Num1	Num2
Sat.	Aug	10,	2019	41	59
Wed.	Aug	07,	2019	47	8
Sat.	Aug	03,	2019	45	68
I have also tried other parameters such as sep='\t' , delim_whitespace=True , etc. But it's the Date column with the single white spaces between that is throwing off the columns being separated under the right heading. My goal is to import the data from the text file for data analysis but they need to be sorted under the right columns.

Any advice on how I can achieve this would be greatly appreciated!


RE: Sorting columns from text file help - newbieAuggie2019 - Nov-15-2019

(Nov-15-2019, 05:10 PM)nickglobal101 Wrote: The CODE I tried:

df = pd.read_csv('columns_test.txt', names=['Date','Num1','Num2'], skiprows=1, sep='\s+', engine='python')
df

Hi!

Have you tried this?:

df = pd.read_csv('columns_test.txt', names=['Weekday','Date','Num1','Num2'], skiprows=1, sep='\s+', engine='python')
df
All the best,