有没有一种简单的方法可以将 Pandas 数据框中的一列是/否更改为 1/0? [英] Is there a simple way to change a column of yes/no to 1/0 in a Pandas dataframe?
本文介绍了有没有一种简单的方法可以将 Pandas 数据框中的一列是/否更改为 1/0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将一个 csv 文件读入一个 Pandas 数据帧,并希望将带有二进制答案的列从是/否字符串转换为 1/0 的整数.下面,我展示了其中一列(sampleDF"是熊猫数据框).
I read a csv file into a pandas dataframe, and would like to convert the columns with binary answers from strings of yes/no to integers of 1/0. Below, I show one of such columns ("sampleDF" is the 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
非常感谢您的帮助!
推荐答案
方法一
sample.housing.eq('yes').mul(1)
方法二
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)
<小时>
所有收益
All yield
0 0
1 0
2 1
3 0
4 0
5 0
6 0
7 0
8 1
9 1
<小时>
时间
给定样本
timing
given sample
时间
长样本sample = pd.DataFrame(dict(housing=np.random.choice(('yes', 'no'), size=100000)))
这篇关于有没有一种简单的方法可以将 Pandas 数据框中的一列是/否更改为 1/0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文