I have a data frame which I want to write to tow files, one that contains all of the columns and one that has only a subset of the columns So for this data frame:
Out_data
Out[9]:
A B C D E F
0 354 49985400 10 07 7.140899 0.212044
1 738 49985400 10 07 7.140899 0.212044
2 738 49985277 11 09 4.024423 0.098387
3 246 49985279 10 07 7.140899 0.212044
I want to have it exported to two csv files, one that has all the data, and the second one that has only data from columns A,B, C and D, so that the csv would look like this:
A,B,C,D,E,F
354,49985400,10,07,7.140899,0.212044
738,49985400,10,07,7.140899,0.212044
738,49985277,11,09,4.024423,0.098387
246,49985279,10,07,7.140899,0.212044
And the second one will look like:
A,B,C,D
354,49985400,10,07
738,49985400,10,07
738,49985277,11,09
246,49985279,10,07
I am able to get the first file using:
Out_data.to_csv(filename, mode = 'w', index=False)
I tried using
Out_data.to_csv(filename, mode = 'w', cols = ['A','B','C','D'] ,index=False)
But I still go the exact same output file? How can I get to_csv to export but drop some of the columns?
In order to drop Pandas columns of a specific data type, you can use the . select_dtypes() method. This method allows you to pass in a list of data types that you want to drop from the DataFrame.
Pandas DataFrame to_csv() function converts DataFrame into CSV data. We can pass a file object to write the CSV data into a file. Otherwise, the CSV data is returned in the string format.
You should be using columns
as the keyword argument, not cols
.
Out_data.to_csv(filename, mode='w', columns=['A','B','C','D'], index=False)
Have you tried:
Out_data[["A", "B", "C", "D"]].to_csv(filename, mode = 'w' ,index=False)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With