Skip to content
Advertisement

converting a key value text file into a CSV file

I have a text file that needs to be converted into CSV file using pandas. A piece of it is presented in the following:

JavaScript

Rows are cod,10, and cod,18 and the columns are 1, 2, 3,…, 15. Any idea? Regards, Ali

Advertisement

Answer

I use pandas to deal with the conversion, but vanilla Python to deal with some of aspects of the data, I hope that is alright.

One issue we need to deal with is the fact that there are a different number of columns per row. So I just put NaN in columns that are missing for a row. For instance, row 1 is shorter than row 2, so the missing columns in row 1 are given values as “NaN”.

Here is my idea:

JavaScript

Output (the printed DataFrame):

JavaScript

CSV File Output:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement