I need to insert commas between the values, remove all unnecessary spaces and enclose the alpha field on the right in quotes. I can’t see how to do this with pandas to_csv. Please can someone tell me how to do this.
Thanks
to_csv is for creating a CSV from already loaded data in a Pandas DataFrame.
The natural way to approach the problem is to load the file into a DataFrame first. Assuming that the file you have is indeed fixed width (and it doesn’t merely look fixed width due to clever use of tabs), the appropriate tool is pandas.read_fwf.
See here for a more detailed guide, which I found by putting pandas constant width field into a search engine:
After you have created the DataFrame, you can use its to_csv method normally. The format that you describe should already be the default.
The first thing wrong is showing us an image of the data. Instead, please copy and paste data and format it like the code.
The second thing wrong is that you say that you tried doing it a different way and couldn’t get it to work, and seem to want to know why it didn’t work, but you don’t show us the code for the different way that you tried. If you mean that you think there is something wrong with the code you’re showing now, then you need to explain the actual issue. As far as I can tell, from what I can read in the image, you are getting a result that matches what you asked for originally.
I don’t see how to upload the data, only image is authorized.
Yes the code I posted works, what I said was that I couldn’t get your code to work, and was wondering why 'cause it’s far more concise and shows the power of python.
It’s not uploading. It’s copying and pasting out of the screen that you took that screenshot from, and putting in some formatting markup - the same way that you add code to your posts. If that doesn’t work for some reason, then you’ll need to explain exactly how you are running the code and where/how you see the output.
I N P U T: open("S285IBUD.PRN", encoding='ISO-8859-1') as the_file
4240.13 4240.13 3 13034.71 13034.71 3 4240.13 99 19/09/21 DONALD DUCK 6181
4000.00 4000.00 90 421574.91 421574.91 90 4000.00 99 5/07/17 MICKY MOUSE 82556
659.24 659.24 71 137428.05 137428.05 71 659.24 99 27/06/17 MARKS AND SPENCER 125198
O U T P U T: outfile = open(filename, 'w', encoding='ISO-8859-1')
4240.13,4240.13,3,,,,13034.71,13034.71,3,4240.13,99,19/09/21,"DONALD DUCK",6181
4000.00,4000.00,90,,,,421574.91,421574.91,90,4000.00,99,5/07/17,"MICKY MOUSE",82556
659.24,659.24,71,,,,137428.05,137428.05,71,659.24,99,27/06/17,"MARKS AND SPENCER",125198