Write a logical csv data frame with 1s and 0s

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

    col1   col2
1   True   False
2   False  True
3   True   True

when i use the pandas' method DataFrame.to_csv, the resulting framework looks like

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

Is there a way to write boolean variables as 1s and 0s (more economical in area), i.e.

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

don't you need to pour the entire data frame first?

+4
source share
2 answers

It's quite simple, just multiply 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 reassign df from the code by doing df = df*1or df2 = df*1. The first will prevent a duplicate copy.

+4
source

dtype df int, True 1 False 0:

In [16]:
df.astype(int)

Out[16]:
   col1  col2
1     1     0
2     0     1
3     1     1
+2

Source: https://habr.com/ru/post/1614978/


All Articles