Mus*_*909 25 python series dataframe pandas
我将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
Run Code Online (Sandbox Code Playgroud)
非常感谢帮助!
piR*_*red 48
方法1
sample.housing.eq('yes').mul(1)
Run Code Online (Sandbox Code Playgroud)
方法2
pd.Series(np.where(sample.housing.values == 'yes', 1, 0),
sample.index)
Run Code Online (Sandbox Code Playgroud)
方法3
sample.housing.map(dict(yes=1, no=0))
Run Code Online (Sandbox Code Playgroud)
方法4
pd.Series(map(lambda x: dict(yes=1, no=0)[x],
sample.housing.values.tolist()), sample.index)
Run Code Online (Sandbox Code Playgroud)
方法5
pd.Series(np.searchsorted(['no', 'yes'], sample.housing.values), sample.index)
Run Code Online (Sandbox Code Playgroud)
全部收益
0 0
1 0
2 1
3 0
4 0
5 0
6 0
7 0
8 1
9 1
Run Code Online (Sandbox Code Playgroud)
定时
给定样本
定时
长样本
sample = pd.DataFrame(dict(housing=np.random.choice(('yes', 'no'), size=100000)))
试试这个:
sampleDF['housing'] = sampleDF['housing'].map({'yes': 1, 'no': 0})
Run Code Online (Sandbox Code Playgroud)
# produces True/False
sampleDF['housing'] = sampleDF['housing'] == 'yes'
Run Code Online (Sandbox Code Playgroud)
上面的返回True / False值分别基本上为1/0。布尔值支持求和函数等。如果确实需要将其设为1/0值,则可以使用以下内容。
housing_map = {'yes': 1, 'no': 0}
sampleDF['housing'] = sampleDF['housing'].map(housing_map)
Run Code Online (Sandbox Code Playgroud)
小智 5
%timeit
sampleDF['housing'] = sampleDF['housing'].apply(lambda x: 0 if x=='no' else 1)
Run Code Online (Sandbox Code Playgroud)
每个循环1.84 ms±56.2 µs(平均±标准偏差,共运行7次,每个循环1000个)
对于指定的df列,将“是”替换为1,将“否”替换为0。
使用sklearn的LabelEncoder
from sklearn.preprocessing import LabelEncoder
lb = LabelEncoder()
sampleDF['housing'] = lb.fit_transform(sampleDF['housing'])
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
36357 次 |
最近记录: |