2017-08-13 143 views
2

說我有一個數據幀如下,如何用1代替大於0.6的值,用0代替小於0.3的值,用0替換所有的值-1如何有條件地替換熊貓數據幀

 aaa  bbb  ccc 
0 0.953893 0.977473 0.034157 
1 0.693851 0.587930 0.584268 
2 0.357185 0.429399 0.937016 
3 0.384505 0.670054 0.657566 
4 0.782799 0.479501 0.196721 
5 0.548724 0.487478 0.277674 
6 0.019224 0.426555 0.047267 
7 0.746972 0.569147 0.973555 
8 0.755425 0.885270 0.825515 
9 0.427994 0.013501 0.982629 

回答

5

我認爲你可以使用numpy.selectDataFrame構造:

m1 = df.values > .6 
m2 = df.values < .3 
df = pd.DataFrame(np.select([m1,m2], [1,0], default=-1), index=df.index, columns=df.columns) 
print (df) 
    aaa bbb ccc 
0 1 1 0 
1 1 -1 -1 
2 -1 -1 1 
3 -1 1 1 
4 1 -1 0 
5 -1 -1 0 
6 0 -1 0 
7 1 -1 1 
8 1 1 1 
9 -1 0 1 

numpy.where另一種解決方案:

df = pd.DataFrame(np.where(m1, 1, np.where(m2, 0, -1)), index=df.index, columns=df.columns) 
print (df) 
    aaa bbb ccc 
0 1 1 0 
1 1 -1 -1 
2 -1 -1 1 
3 -1 1 1 
4 1 -1 0 
5 -1 -1 0 
6 0 -1 0 
7 1 -1 1 
8 1 1 1 
9 -1 0 1