我有一个pd.DataFrame看起来像:
我想在值上创建一个截止值,将它们推入二进制数字,在这种情况下我的截止值是0.85.我希望结果数据框看起来像:
我写的脚本很容易理解,但对于大型数据集来说效率很低.我敢肯定Pandas可以通过某种方式来处理这些类型的转换.
有没有人知道使用阈值将一列浮点数转换为整数列的有效方法?
我非常天真地做这样的事情:
DF_test = pd.DataFrame(np.array([list("abcde"),list("pqrst"),[0.12,0.23,0.93,0.86,0.33]]).T,columns=["c1","c2","value"])
DF_want = pd.DataFrame(np.array([list("abcde"),list("pqrst"),[0,0,1,1,0]]).T,columns=["c1","c2","value"])
threshold = 0.85
#Empty dataframe to append rows
DF_naive = pd.DataFrame()
for i in range(DF_test.shape[0]):
#Get first 2 columns
first2cols = list(DF_test.ix[i][:-1])
#Check if value is greater than threshold
binary_value = [int((bool(float(DF_test.ix[i][-1]) > threshold)))]
#Create series object
SR_row = pd.Series( first2cols + binary_value,name=i)
#Add to empty dataframe container
DF_naive = DF_naive.append(SR_row)
#Relabel columns
DF_naive.columns = DF_test.columns
DF_naive.head()
#the sample DF_want
Run Code Online (Sandbox Code Playgroud)