将字符串转换为

尝试对医疗数据进行简单的线性分类。样本数据全部由字符串组成,大多数值为’yes’和’no’格式,我希望将这些数据转换为整数值1和0,以便进行一些统计分析。

以下是我的代码

import pandas as pdfrom sklearn.cross_validation import train_test_splitfrom sklearn import preprocessingdf = pd.read_csv('sample-data.csv',encoding='utf-16', header=None, sep=',',names=['Temp','Occurrence','Lumbar-pain','Urine-pushing','Micturition-pains','Burning-of-urethra-swelling-of-urethra-outlet','Outcome1-Urinary-bladder','Outcome2-Nephritis-of-renal'])

点击此处查看Sample-data.csv

我尝试在将csv数据移动到数据框后进行转换,尝试对特定列使用map()方法,但我想对所有值为’yes’和’no’的列进行此操作。在运行read_csv时,是否有任何直接将所有’yes’和’no’字符串转换为整数1和0的通用方法?

d = {'yes': 1, 'no': 0}print df['Outcome1-Urinary-bladder'].map(d) 

查看了这个解决方案,但它不适合我的需求。

请帮助我,提前感谢。


回答:

您可以使用.replace方法。

df = pd.DataFrame(np.random.choice(['yes', 'no'], size=(5,3)), columns=list('ABC'))df     A    B    C0   no  yes   no1   no  yes  yes2  yes  yes   no3  yes   no   no4  yes  yes  yesdf.replace(['yes', 'no'], [1, 0])   A  B  C0  0  1  01  0  1  12  1  1  03  1  0  04  1  1  1

或者

pd.DataFrame(np.where(df=='yes', 1, 0), columns=df.columns, index=df.index)

这是一种向量化的numpy方法,比逐元素映射要快得多。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注