首页 > 解决方案 > 在python中为对象赋值

问题描述

我正在尝试将 1 和 0 分配给数据框中的列,该列实际上是一个字符串。在下面的日期集中,'abc' 为 1,其余为 0

以下是样本数据集:

type={'type':['abc','abc','kk','arr','yg','np']}
df=pd.DataFrame(type,columns=['type'])

我的代码:

df['new']=np.where(df['type']=='abd',1,0)
df['new'].value_counts()

输出:

0    6
Name: new, dtype: int64

标签: pythonpython-3.xpandas

解决方案


试试这个,而不是 np.where:

df['new'] = df['type'] == 'abc'

顺便说一句:你写的是 'abd' 而不是 'abc' 所以你有 6 - 0 :)


推荐阅读