Python 熊猫–;将是:否转换为真:假失败

Python 熊猫–;将是:否转换为真:假失败,python,pandas,Python,Pandas,将值为“是”“否”的列转换为True、False或1、0的最大努力失败。该列为“已订阅” df.subscribed.unique() returns array(['no', 'yes'], dtype=object) 尝试了以下方法。他们没有一个成功: df.subscribed = df.subscribed.astype(int) df.subscribed.map(dict(yes=1, no=0)) df.replace({'subscribed': {'yes': 1, 'no'

将值为“是”“否”的列转换为True、False或1、0的最大努力失败。该列为“已订阅”

df.subscribed.unique() returns
array(['no', 'yes'], dtype=object)
尝试了以下方法。他们没有一个成功:

df.subscribed = df.subscribed.astype(int)
df.subscribed.map(dict(yes=1, no=0))
df.replace({'subscribed': {'yes': 1, 'no': 0}})
d = {'yes': True, 'no': False}
df['subscribed'].map(d)

正如EdChum指出的,您需要重新分配给df

df = pd.DataFrame({'subscribed':np.random.choice(['yes','no'], 10)})
print(df)
输入:

  subscribed
0        yes
1        yes
2        yes
3         no
4         no
5        yes
6         no
7         no
8         no
9        yes

df =df.replace({'subscribed': {'yes': True, 'no': False}})
print(df)
输出:

   subscribed
0        True
1        True
2        True
3       False
4       False
5        True
6       False
7       False
8       False
9        True

你可以在一行中使用它


df.col.map(dict(yes=1,no=0))

感叹。。。。您需要分配回:
df['subscribed']=df['subscribed']]。映射(d)
大多数操作返回一个副本,一些方法具有
inplace
param,您需要将其设置为
True
,因此操作在placesign中执行。。。谢谢EdChum。