尝试对医疗数据进行简单的线性分类。样本数据全部由字符串组成,大多数值为’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'])
我尝试在将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
方法,比逐元素映射要快得多。