假設我有一個串列a = [2, 1, 4, 3, 5]。我想做以下事情:
我定義了一個百分比值r%。我想選擇r%具有低值的樣本并獲取它們的索引。
例如,如果r=80- 輸出將是1, 2, 3, 4ie的索引1, 0, 3, 2
uj5u.com熱心網友回復:
使用np.percentile和np.where
a = np.array([2, 1, 4, 3, 5])
r = 80
np.where(a < np.percentile(a, r))
> (array([0, 1, 2, 3]),)
注意:在您的示例中,您回傳索引的順序,就像元素已排序一樣。目前尚不清楚這對您是否重要,但在 NumPy 中是否很容易!只需將最后一行替換為
np.argsort(a)[a < np.percentile(a, r)]
> array([1, 0, 3, 2])
uj5u.com熱心網友回復:
def perc(r, number_list):
# Find number of samples based on the percentage (rounding to closest integer)
number_of_samples = len(number_list) * (r/ 100)
number_list.sort()
return [number_list[index] for index in range(number_of_samples)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/380561.html
上一篇:R到Python的隨機程序轉換
下一篇:當行名和列名彼此相等時用零替換值
