[英]Write boolean dataframe to csv with 1s and 0s
I have a pandas dataframe with boolean values, ie 我有一个带有布尔值的pandas数据帧,即
col1 col2
1 True False
2 False True
3 True True
when I use pandas' DataFrame.to_csv
method, the resulting dataframe looks like 当我使用pandas的
DataFrame.to_csv
方法时,结果数据DataFrame.to_csv
看起来像
,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), ie 有没有办法将布尔变量写为1和0(更节省空间),即
,col1,col2
1,1,0
2,0,1
3,1,1
without having to cast the entire dataframe first? 无需先抛出整个数据帧?
You can just convert the dtype
of the df to int
this will convert True
to 1
and False
to 0
: 你可以将df的
dtype
转换为int
这会将True
转换为1
,将False
转换为0
:
In [16]:
df.astype(int)
Out[16]:
col1 col2
1 1 0
2 0 1
3 1 1
It's quite simple actually, just multiply the df by 1. 实际上它非常简单,只需将df乘以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
. 从那里你可以通过
df = df*1
或df2 = df*1
从代码中重新分配df。 The first will prevent duplicate copy. 第一个将防止重复复制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.