在Pandas数据框中,有没有一种简单的方法将一个yes/no列更改为1/0列?

76

我将一个csv文件读入pandas dataframe中,并希望将二元回答的列从yes/no字符串转换为1/0整数。下面是其中一列的示例("sampleDF"是pandas dataframe)。

In [13]: sampleDF.housing[0:10]
Out[13]:
0     no
1     no
2    yes
3     no
4     no
5     no
6     no
7     no
8    yes
9    yes
Name: housing, dtype: object

非常感谢您的帮助!


31
sampleDF.housing.replace(('yes', 'no'), (1, 0), inplace=True) - AChampion
注意:Python有bools类型,NumPy也有。请使用它们,而不是0/1或'0'/'1'。 - AMC
19个回答

126

方法1

sample.housing.eq('yes').mul(1)

方法二

pd.Series(np.where(sample.housing.values == 'yes', 1, 0),
          sample.index)

方法三

sample.housing.map(dict(yes=1, no=0))

第四种方法

pd.Series(map(lambda x: dict(yes=1, no=0)[x],
              sample.housing.values.tolist()), sample.index)

第五种方法

pd.Series(np.searchsorted(['no', 'yes'], sample.housing.values), sample.index)
所有的屈服
0    0
1    0
2    1
3    0
4    0
5    0
6    0
7    0
8    1
9    1

时间
给定样本

输入图像描述

时间
长样本
sample = pd.DataFrame(dict(housing=np.random.choice(('yes', 'no'), size=100000)))

输入图像描述



8
这是一篇深入的回答。我甚至没想到其中一些点。 - gold_cy
1
你能否处理一个完整的由“是”和“否”组成的数据框?我正在查看这个国会投票数据集:http://archive.ics.uci.edu/ml/datasets/Congressional+Voting+Records - mLstudent33

41

试试这个:

sampleDF['housing'] = sampleDF['housing'].map({'yes': 1, 'no': 0})

17
# produces True/False
sampleDF['housing'] = sampleDF['housing'] == 'yes'
上述返回的是True/False值,它们分别等同于1/0。布尔变量支持sum函数等操作。如果你确实需要得到1/0的值,可以使用以下方法。
housing_map = {'yes': 1, 'no': 0}
sampleDF['housing'] = sampleDF['housing'].map(housing_map)

8
%timeit
sampleDF['housing'] = sampleDF['housing'].apply(lambda x: 0 if x=='no' else 1)

每个循环的平均值为1.84毫秒±56.2微秒(7次运行,每次1000个循环的标准偏差)

将指定的df列中的'yes'替换为1,'no'替换为0。


5

使用sklearn的LabelEncoder

from sklearn.preprocessing import LabelEncoder

lb = LabelEncoder() 
sampleDF['housing'] = lb.fit_transform(sampleDF['housing'])

Source


4

是的,你可以通过以下代码片段将你的列中的yes/no值更改为1/0

sampleDF = sampleDF.replace(to_replace = ['yes','no'],value = ['1','0'])
sampleDF

通过使用第一行,您可以将值替换为1/0 通过使用第二行,您可以通过打印它来查看更改


3

3
对于一个名为"数据(data)"且包含一列名为"Paid"的数据集;
data = data.replace({'Paid': {'yes': 1, 'no': 0}})

所有的yes将更改为1,所有的no将被替换为0


1
使用 pandas.Series.map

sampleDF.map({'yes':1,'no':0})


1

简单的方法是使用以下pandas:

housing = pd.get_dummies(sampleDF['housing'],drop_first=True)

之后从主数据框中删除此字段。
sampleDF.drop('housing',axis=1,inplace=True)

现在把新的合并到你的数据框中。
sampleDF= pd.concat([sampleDF,housing ],axis=1)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接