How to convert true false values in dataframe as 1 for true and 0 for false(如何将数据框中的真假值转换为 1 为真,0 为假)
问题描述
如何将Dataframe中的真假值转换为1为真,0为假
How to convert true false values in Dataframe as 1 for true and 0 for false
COL1 COL2 COL3 COL4
12 TRUE 14 FALSE
13 FALSE 13 TRUE
OUTPUT
12 1 14 0
13 0 13 1
推荐答案
首先,如果你有字符串 'TRUE' 和 'FALSE',你可以将它们转换像这样布尔 True 和 False 值:
First, if you have the strings 'TRUE' and 'FALSE', you can convert those to boolean True and False values like this:
df['COL2'] == 'TRUE'
这会给你一个 bool 列.可以使用 astype 转换为 int (因为 bool 是整数类型,其中 True 表示 1 和 False 表示 0,这正是你想要的):
That gives you a bool column. You can use astype to convert to int (because bool is an integral type, where True means 1 and False means 0, which is exactly what you want):
(df['COL2'] == 'TRUE').astype(int)
要用这个新的 int 列替换旧的字符串列,只需分配它:
To replace the old string column with this new int column, just assign it:
df['COL2'] = (df['COL2'] == 'TRUE').astype(int)
要同时对两列执行此操作,只需使用列列表进行索引:
And to do that to two columns at one, just index with a list of columns:
df[['COL2', 'COL4']] = (df[['COL2', 'COL4']] == 'TRUE').astype(int)
这篇关于如何将数据框中的真假值转换为 1 为真,0 为假的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将数据框中的真假值转换为 1 为真,0 为假
基础教程推荐
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
