给定 pd.DataFrame
与 0.0 < values < 1.0
,我想将其转换为二进制值 0
/1
根据定义的阈值 eps = 0.5
,
0 1 2
0 0.35 0.20 0.81
1 0.41 0.75 0.59
2 0.62 0.40 0.94
3 0.17 0.51 0.29
现在,我只有这个
for loop
对于大型数据集,这需要很长时间:
import numpy as np
import pandas as pd
data = np.array([[.35, .2, .81],[.41, .75, .59],
[.62, .4, .94], [.17, .51, .29]])
df = pd.DataFrame(data, index=range(data.shape[0]), columns=range(data.shape[1]))
eps = .5
b = np.zeros((df.shape[0], df.shape[1]))
for i in range(df.shape[0]):
for j in range(df.shape[1]):
if df.loc[i,j] < eps:
b[i,j] = 0
else:
b[i,j] = 1
df_bin = pd.DataFrame(b, columns=df.columns, index=df.index)
有人知道转换为二进制值的更有效方法吗?
0 1 2
0 0.0 0.0 1.0
1 0.0 1.0 1.0
2 1.0 0.0 1.0
3 0.0 1.0 0.0
谢谢,
最佳答案
df.round
>>> df.round()
np.round
>>> np.round(df)
astype
>>> df.ge(0.5).astype(int)
所有产生的
0 1 2
0 0.0 0.0 1.0
1 0.0 1.0 1.0
2 1.0 0.0 1.0
3 0.0 1.0 0.0
注:
round
在这里工作是因为它会自动设置 .5
的阈值两个整数之间。对于自定义阈值,请使用第三个解决方案