简体   繁体   English

如何将一些字符串编码为 pandas 数据帧中所有列的数字? 例如在整个数据框中将“是”更改为 1

[英]How to code some strings to numbers across all columns in a pandas data frame? For example changing “yes” to 1 in the entire data frame

I normally use the following code to encode strings to numbers within a specific columns:我通常使用以下代码将字符串编码为特定列中的数字:

data['column name'] = data['column name'].map({'Yes': 1, 'No': 0})

How do we replace all 'Yes' to 1 and 'No' to 0 in the whole data frame without having to write the above code for every column.我们如何将整个数据框中的所有“是”替换为 1,将“否”替换为 0,而无需为每一列编写上述代码。

Thank you!谢谢!

Simply use a for loop to iterate through all the columns:只需使用 for 循环遍历所有列:

for column in df.columns():
    data[column] = data[column].map({'Yes': 1, 'No': 0})

Or use the replace method:或者使用replace方法:

data = data.replace({'Yes': 1, 'No': 0})

You mean this:你是这个意思:

data = data.replace({'Yes': 1, 'No': 0})

This will replace the values in the entire dataframe.这将替换整个 dataframe 中的值。

Check查看

data = data.apply(lambda x :x.map({'Yes': 1, 'No': 0}))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 pandas python 中的整个数据框中通用替换一个值? - How to replace a value universally across the entire data frame in pandas python? 在熊猫数据框中使用正则表达式将所有数字(0和1除外)更改为0 - changing all numbers (except 0 and 1) to 0 using regular expression in pandas data frame 如何在 pandas 中跨多个数据框列“选择不同”? - How to "select distinct" across multiple data frame columns in pandas? 如何仅对熊猫数据框中的某些列进行排序? - how to sort only some of the columns in a data frame in pandas? 使用python在数据框中比较和查找重复值(不是整个列) - Compare and find Duplicated values (not entire columns) across data frame with python 如何在数据框某些行的所有列上使用熊猫套用功能 - How to use pandas apply function on all columns of some rows of data frame 如何使用 Python 过滤 Pandas 数据帧中所有或部分行值大于 0 的列? - How to filter columns whose all or some rows values are greater than 0 in Pandas data-frame using Python? 检查整个熊猫数据框的电子邮件和电话号码 - Check entire pandas data frame for emails and phone numbers 如何只在dype bool列的pandas数据框中将True和False映射为“是”和“否”? - How to map True and False to 'Yes' and 'No' in a pandas data frame for columns of dtype bool only? Pandas:如何将新列附加到数据框中的所有行 - Pandas: How to append new columns to all rows in data frame
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM