尝试对医疗数据执行简单的线性分类。示例数据由所有字符串组成,大部分值都是'yes','no'格式,我希望将此数据转换为整数值 1 和 0,以便我可以进行一些统计分析。
以下是我的代码
import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn import preprocessing
df = 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'])
Click here to view Sample-data.csv
我尝试在将 csv 数据移动到数据帧后进行转换,尝试使用 map() 对特定列进行转换,但我希望对值为"is"、“否”字符串的所有列执行此操作。 在运行 read_csv 时,是否有任何一揽子方法可以直接将所有"is"、“否”字符串转换为整数 1 和 0
d = {'yes': 1, 'no': 0}
print df['Outcome1-Urinary-bladder'].map(d)
查看了 this solution , 但它不适合我的要求。
请帮助我,在此先感谢。
最佳答案
您可以使用.replace
方法。
df = pd.DataFrame(np.random.choice(['yes', 'no'], size=(5,3)), columns=list('ABC'))
df
A B C
0 no yes no
1 no yes yes
2 yes yes no
3 yes no no
4 yes yes yes
df.replace(['yes', 'no'], [1, 0])
A B C
0 0 1 0
1 0 1 1
2 1 1 0
3 1 0 0
4 1 1 1
或者
pd.DataFrame(np.where(df=='yes', 1, 0), columns=df.columns, index=df.index)
这是向量化的 numpy
方法,比逐元素映射快得多。
关于python - 将字符串转换成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31860702/