Pandas将正数转换为1,将负数转换为-1

时间:2018-03-02 06:17:44

标签: python pandas

我有一列正数和负数。如何将此列转换为新列以实现将正数转换为1并将负数转换为-1?

3 个答案:

答案 0 :(得分:7)

您需要numpy.sign

df['new'] = np.sign(df['col'])

<强>示例

df = pd.DataFrame({ 'col':[-1,3,-5,7,1,0]})
df['new'] = np.sign(df['col'])
print (df)

   col  new
0   -1   -1
1    3    1
2   -5   -1
3    7    1
4    1    1
5    0    0

答案 1 :(得分:3)

df[df < 0] = -1
df[df > 0] = 1

//no behaviour defined for df = 0

答案 2 :(得分:3)

通过 -

执行此任务非常容易

对于整个数据框 -

    df[df < 0] = -1
    df[df > 0] = 1

对于特定列 -

   df['column_name'][df['column_name'] < 0] = -1
   df['column_name'][df['column_name'] > 0] = 1