问题描述
如何将Dataframe中的true假值转换为1表示true和0表示false
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)
这篇关于如何将数据帧中的true假值转换为1表示true和0表示false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!