将布尔数据帧以1和0写入csv [英] Write boolean dataframe to csv with 1s and 0s

查看:64
本文介绍了将布尔数据帧以1和0写入csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有布尔值的熊猫数据框,即

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

    col1   col2
1   True   False
2   False  True
3   True   True

当我使用pandas的DataFrame.to_csv方法时,结果数据框看起来像

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

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

有没有一种方法可以将布尔变量写为1和0(更节省空间),即

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?

推荐答案

实际上很简单,只需将df乘以1.

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)

这会将其更改为:

   col1  col2
1     1     0
2     0     1
3     1     1

您可以在其中通过执行df = df*1df2 = df*1在代码中重新分配df.第一个将防止重复复制.

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.

这篇关于将布尔数据帧以1和0写入csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆