python-3.x - 列名和最大值索引

标签 python-3.x pandas numpy dataframe

我目前有一个 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/

相关文章:

python - 如何在python中合并两个数据框,其中包含长度不等的列中的文本?

python - 如何(有效地)检查任何两个元素是否相差 10

Python 线程字符串参数

python - Pandas Series 获取多个区间的平均值

python-3.x - 使用 unicode 在 hdf5 中存储字符串数据集

python - 防止 pandas 在系列操作期间将 datetime.timedelta 强制为 numpy.timedelta64?

python - 输入图像的小波二维散射变换

python - 索引超出尺寸 100 的轴 0 的范围

python - 将所有 pcap 文件转换为包含所需列的 csv python

string - 无法在 Python-3 中连接字符串