[英]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.