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

xxy*_*yao 3 python pandas

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

jez*_*ael 7

你需要 numpy.sign

df['new'] = np.sign(df['col'])
Run Code Online (Sandbox Code Playgroud)

样品:

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
Run Code Online (Sandbox Code Playgroud)