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

问题描述 投票:22回答:9

我将csv文件读入pandas数据帧,并希望将带有二进制答案的列从yes / no字符串转换为1/0的整数。下面,我展示了一个这样的列(“sampleDF”是pandas数据帧)。

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

非常感谢帮助!

python pandas dataframe series
9个回答
41
投票

方法1

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

方法2

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

方法3

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

方法4

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

方法5

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

定时 给出样本

enter image description here

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

enter image description here


0
投票

将整个数据帧转换为0和1的简单直观方法可能是:

sampleDF = sampleDF.replace(to_replace = "yes", value = 1)
sampleDF = sampleDF.replace(to_replace = "no", value = 0)

7
投票

试试这个:

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

6
投票
# produces True/False
sampleDF['housing'] = sampleDF['housing'] == 'yes'

以上返回的True / False值基本上分别为1/0。布尔值支持求和函数等。如果你真的需要它是1/0值,你可以使用以下。

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

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

每回路1.84 ms±56.2μs(平均值±标准偏差,7次运行,每次1000次循环)

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


2
投票

通用方式:

import pandas as pd
string_data = string_data.astype('category')
numbers_data = string_data.cat.codes

参考:https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.astype.html


1
投票

您可以显式地将系列从布尔值转换为整数:

sampleDF['housing'] = sampleDF['housing'].eq('yes').astype(int)

1
投票

使用sklearn的LabelEncoder

from sklearn.preprocessing import LabelEncoder

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

Source


0
投票

请尝试以下方法:

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

0
投票

使用pandas的简单方法如下:

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

之后从主df中删除此字段

sampleDF.drop('housing',axis=1,inplace=True)

现在合并你的新df

sampleDF= pd.concat([sampleDF,housing ],axis=1)
© www.soinside.com 2019 - 2024. All rights reserved.