我目前有一个 pandas 数据框,其中保存了 0 到 1 之间的值。我正在寻找一个函数,它可以为我提供列的前 5 个值,以及列的名称和值的关联索引。
Sample Input: data frame with column names a:z, index 1:23, entries are values between 0 and 1
Sample Output: array of 5 highest entries in each column, each with column name and index
编辑: 对于以下数据框:
np.random.seed([3,1415])
df = pd.DataFrame(np.random.randint(10, size=(10, 4)), list('abcdefghij'), list('ABCD'))
df
A B C D
a 0 2 7 3
b 8 7 0 6
c 8 6 0 2
d 0 4 9 7
e 3 2 4 3
f 3 6 7 7
g 4 5 3 7
h 5 9 8 7
i 6 4 7 6
j 2 6 6 5
我想得到如下输出(例如第一列):
[[8,b,A], [8, c, A], [6,i,A], [5, h, A], [4,g,A]].
最佳答案
考虑数据帧df
np.random.seed([3,1415])
df = pd.DataFrame(
np.random.randint(10, size=(10, 4)), list('abcdefghij'), list('ABCD'))
df
A B C D
a 0 2 7 3
b 8 7 0 6
c 8 6 0 2
d 0 4 9 7
e 3 2 4 3
f 3 6 7 7
g 4 5 3 7
h 5 9 8 7
i 6 4 7 6
j 2 6 6 5
我将使用np.argpartition
将每一列分成 5 个最小的列和 10 - 5
(也 5
)最大的列
v = df.values
i = df.index.values
k = len(v) - 5
pd.DataFrame(
i[v.argpartition(k, 0)[-k:]],
np.arange(k), df.columns
)
A B C D
0 g f i i
1 b c a d
2 h h f h
3 i b d f
4 c j h g
关于python-3.x - 列名和最大值索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42932109/