我正在嘗試將DataFrame
的列score
分段。過濾出np.percentile中的零
我使用下面的代碼:
np.percentile(df['score'], np.arange(0, 100, 10))
我的問題是在score
,有很多零。我怎樣才能過濾出這些0值並且只剩下其餘的值呢?
我正在嘗試將DataFrame
的列score
分段。過濾出np.percentile中的零
我使用下面的代碼:
np.percentile(df['score'], np.arange(0, 100, 10))
我的問題是在score
,有很多零。我怎樣才能過濾出這些0值並且只剩下其餘的值呢?
與布爾索引篩選它們:
df.loc[df['score']!=0, 'score']
或
df['score'][lambda x: x!=0]
並傳遞到百分功能。
np.percentile(df['score'][lambda x: x!=0], np.arange(0,100,10))
你可以簡單地掩蓋零,然後從列刪除它們使用boolean indexing:
score = df['score']
score_no_zero = score[score != 0]
np.percentile(score_no_zero, np.arange(0,100,10))
或一步到位:
np.percentile(df['score'][df['score'] != 0], np.arange(0,100,10))
考慮數據框df
df = pd.DataFrame(
dict(score=np.random.rand(20))
).where(
np.random.choice([True, False], (20, 1), p=(.8, .2)),
0
)
score
0 0.380777
1 0.559356
2 0.103099
3 0.800843
4 0.262055
5 0.389330
6 0.477872
7 0.393937
8 0.189949
9 0.571908
10 0.133402
11 0.033404
12 0.650236
13 0.593495
14 0.000000
15 0.013058
16 0.334851
17 0.000000
18 0.999757
19 0.000000
使用pd.qcut
以等分
pd.qcut(df.loc[df.score != 0, 'score'], 10, range(10))
0 4
1 6
2 1
3 9
4 3
5 4
6 6
7 5
8 2
9 7
10 1
11 0
12 8
13 8
15 0
16 3
18 9
Name: score, dtype: category
Categories (10, int64): [0 < 1 < 2 < 3 ... 6 < 7 < 8 < 9]
或一起
df.assign(decile=pd.qcut(df.loc[df.score != 0, 'score'], 10, range(10)))
score decile
0 0.380777 4.0
1 0.559356 6.0
2 0.103099 1.0
3 0.800843 9.0
4 0.262055 3.0
5 0.389330 4.0
6 0.477872 6.0
7 0.393937 5.0
8 0.189949 2.0
9 0.571908 7.0
10 0.133402 1.0
11 0.033404 0.0
12 0.650236 8.0
13 0.593495 8.0
14 0.000000 NaN
15 0.013058 0.0
16 0.334851 3.0
17 0.000000 NaN
18 0.999757 9.0
19 0.000000 NaN
@MSeifert由於他們最近增加了它,我認爲這將是有效的,但從來沒有真正測試過它(我一直在使用它時,我有很長DataFrame名稱)。讓我環顧一下。 :) – ayhan
你說得對。它在整個列上運行,因此它的運行速度與屏蔽一樣快。 – MSeifert