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
pandas replace boolean value with string or integer
提问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 True
into 1
and False
into 0
分配'eq'
列时,请使用atype(int)
. 通过int转换转True
成1
和False
成0
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