Skip to content
Advertisement

Is there a function to write certain values of a dataframe to a .txt file in Python?

I have a dataframe as follows:

JavaScript

Basically I would like to write the dataframe to a txt file, such that every row consists of the index and the subsequent column name only, excluding the zeroes.

For example:

JavaScript

The dataset is quite big, about 1k rows, 16k columns. Is there any way I can do this using a function in Pandas?

Advertisement

Answer

Take a matrix vector multiplication between the boolean matrix generated by “is this entry "0" or not” and the columns of the dataframe, and write it to a text file with to_csv (thanks to @Andreas’ answer!):

JavaScript

where we right strip the spaces at the end due to the added " " to the last entries.

If you don’t want the name Index appearing in the text file, you can chain a rename_axis(index=None) to get rid of it i.e.,

JavaScript

and then to_csv as above.

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