pandas 数据帧将INT64列转换为布尔值 [英] pandas data frame transform INT64 columns to boolean
本文介绍了 pandas 数据帧将INT64列转换为布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
数据帧df中的某些列df.column存储为数据类型int64.
Some column in dataframe df, df.column, is stored as datatype int64.
值全为1或0.
是否可以用布尔值替换这些值?
Is there a way to replace these values with boolean values?
推荐答案
df['column_name'] = df['column_name'].astype('bool')
例如:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.random_integers(0,1,size=5),
columns=['foo'])
print(df)
# foo
# 0 0
# 1 1
# 2 0
# 3 1
# 4 1
df['foo'] = df['foo'].astype('bool')
print(df)
收益
foo
0 False
1 True
2 False
3 True
4 True
给出column_names
的列表,您可以使用以下方法将多列转换为bool
dtype:
Given a list of column_names
, you could convert multiple columns to bool
dtype using:
df[column_names] = df[column_names].astype(bool)
如果您没有列名列表,但希望转换例如所有数字列,则可以使用
If you don't have a list of column names, but wish to convert, say, all numeric columns, then you could use
column_names = df.select_dtypes(include=[np.number]).columns
df[column_names] = df[column_names].astype(bool)
这篇关于 pandas 数据帧将INT64列转换为布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文