簡體   English   中英

從 DataFrame 中選擇第 n 個最低值(每一行!)

[英]Select n-th lowest value from DataFrame (Every Row!)

我正在尋找一種從 Dataframe 中選擇值(按行)的解決方案。 這是我已經擁有的:

np.random.seed(1)
df = pd.DataFrame(np.random.randint(1,10, (10, 10)))
df.columns = list('ABCDEFGHIJ')

N = 2
idx = np.argsort(df.values, 1)[:, 0:N]

df= pd.concat([pd.DataFrame(df.values.take(idx), index=df.index), pd.DataFrame(df.columns[idx], index=df.index)],keys=['Value', 'Columns']).sort_index(level=1)

現在我有每個值的索引/位置,但是如果我嘗試從數據框中獲取值,它只會從第一行獲取值。 我必須在代碼中更改什么?

df 看起來像:

   A  B  C  D  E  F  G  H  I  J
0  6  9  6  1  1  2  8  7  3  5
1  6  3  5  3  5  8  8  2  8  1
2  7  8  7  2  1  2  9  9  4  9
....

我的輸出應該是這樣的:

0  D E
0  1 1
1  J H
1  1 2

您可以使用np.take_along_axis從數據np.take_along_axis獲取值。 使用np.insert篩選采用的值和相應的列名稱。

# idx is the same as the one used in the question.

vals = np.take_along_axis(df.values, idx, axis=1)
cols = df.columns.values[idx]
indices = np.r_[: len(vals)] # same as np.arange(len(vals))

out = np.insert(vals.astype(str), indices , cols, axis=0)
index = np.repeat(indices, 2)
df = pd.DataFrame(out, index=index)

   0  1
0  D  E
0  1  1
1  J  H
1  1  2
2  E  D
2  1  2
3  E  I
3  2  2
4  A  D
4  1  1
5  I  J
5  1  3
6  E  I
6  1  2
7  B  H
7  1  3
8  G  I
8  1  1
9  E  A
9  1  2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM