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?
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.
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.
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.
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.
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