我有一个数据框,大约有100列,有一些布尔列和一些字符。我想用1/0替换所有值为True/False和-1的布尔值。我想将它应用于整个数据帧而不是单个列。
我在这里看到了一些解决方案,比如将列转换为整数。但我想避免穿过100个柱子的练习。
以下是我试过但没有成功的东西:
test.applymap(lambda x: 1 if x=='True' else x)
test.applymap(lambda x: 0 if x=='False' else x)
但是dataframe测试仍然有True/False
Tags:
默认情况下,
applymap
不在适当位置,它将返回一个新的数据帧。正确的方法:
或者
或者只是
尽管
replace
似乎是实现这一目标的最佳方法:定义一个函数,该函数在数据帧的每一列中循环.replace():
对于单个列,目前最简单的方法是转换列类型。Pandas足够聪明,能够正确映射布尔值以进行int。
如果df.column_name以
Boolean
开头,则在转换为类型int
后,它将变为零和一相关问题 更多 >
编程相关推荐