Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write boolean dataframe to csv with 1s and 0s

Tags:

python

pandas

csv

I have a pandas dataframe with boolean values, i.e.

    col1   col2
1   True   False
2   False  True
3   True   True

when I use pandas' DataFrame.to_csv method, the resulting dataframe looks like

,col1,col2
1,True,False
2,False,True
3,True,True

is there a way to write the boolean variables as 1s and 0s (more space-efficient), i.e.

,col1,col2
1,1,0
2,0,1
3,1,1

without having to cast the entire dataframe first?

like image 508
jayelm Avatar asked Nov 09 '15 01:11

jayelm


People also ask

How do I convert a DataFrame to a CSV file?

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.

How do I write pandas DataFrame to CSV?

By using pandas. DataFrame. to_csv() method you can write/save/export a pandas DataFrame to CSV File. By default to_csv() method export DataFrame to a CSV file with comma delimiter and row index as the first column.

How do I append a DataFrame to a CSV file in Python?

To add a dataframe row-wise to an existing CSV file, we can write the dataframe to the CSV file in append mode by the parameter a using the pandas to_csv() function. Parameters: existing. csv: Name of the existing CSV file.


1 Answers

It's quite simple actually, just multiply the df by 1.

import pandas as pd
import io

data = """
    col1   col2
1   True   False
2   False  True
3   True   True
    """

df = pd.read_csv(io.StringIO(data), delimiter='\s+')

print(df*1)

This will change it to:

   col1  col2
1     1     0
2     0     1
3     1     1

From there you can either reassign the df from within the code by doing df = df*1 or df2 = df*1. The first will prevent duplicate copy.

like image 59
Leb Avatar answered Oct 28 '22 20:10

Leb