pandas 熊猫用字符串或整数替换布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39698672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:05:25  来源:igfitidea点击:

pandas replace boolean value with string or integer

pandasreplaceboolean

提问by Felix

This is snipett of my code with column values comparison:

这是我的代码与列值比较的片段:

import pandas as pd
df =pd.DataFrame({'coname1':['Apple','Yahoo','Gap Inc'],'coname2':['Apple', 'Google', 'Apple']})
df['eq'] =df.apply(lambda row: row['coname1'] == row['coname2'],axis=1)

The problem is that I am interested with Character (True='Y' or False = 'N')or Integer (True= 1 or False = 0)values.

问题是我对Character (True='Y' or False = 'N')Integer (True= 1 or False = 0)价值观感兴趣。

Option df.replace(['True', 'False'],[1,0])doesn't work Thank you

选项df.replace(['True', 'False'],[1,0])不起作用 谢谢

回答by piRSquared

When assigning the 'eq'column, use atype(int). The int conversion turns Trueinto 1and Falseinto 0

分配'eq'列时,请使用atype(int). 通过int转换转True1False0

df = pd.DataFrame({'coname1': ['Apple','Yahoo','Gap Inc'], 'coname2':['Apple', 'Google', 'Apple']})
df['eq'] = df.apply(lambda row: row['coname1'] == row['coname2'], axis=1).astype(int)


For characters

对于字符

df['eq'] = np.where(df['eq'], 'Y', 'N')
df

enter image description here

在此处输入图片说明