使用Python为每一行选择前三个列,并将结果以及索引保存在一个字典中

2024-10-05 14:29:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用下面的代码遍历数据帧的行

df

以下是示例数据集:

device_id   s2  s41 s47 s14 s24 s36 s4  s23 s10
3           0   0   0   0.002507676 0   0   0   0   0
5           0   0   0   0   0   0   0   0   0
23          0   0   0   0   0   0   0   0   0
42          0   0   0   0   0   0   0   0   0
61          0   0   0   0   0   0   0   0   0
49          0   0   0   0   0   0   0   0   7.564063476
54          0   0   0   0   0   0   0   0.001098988 0

并对每行的前3个值进行排序

for index, row in df.iterrows():

    row_sorted = row.sort_values(ascending=False)
    print (index,row_sorted)

下面是一个示例输出

123 s16    1.054018
    s17    0.000000
    s26    0.000000

我还尝试了以下代码:

top_n = 3
    pd.DataFrame({n: df.T[col].nlargest(top_n).index.tolist() 
                  for n, col in enumerate(df.T)}).T

一次完成,但输出如下:

49 s16 s1 s37--49是这里的行号

如您所见,输出不匹配,第一个输出是正确的

我要找的是一个最终字典,其中包含索引作为键,前3列作为值:

{123 : 's16','s17','s26'}

这些将用于进一步向下遍历另一个字典到具有以下结构的\u映射: ID": ["s26", "International", "E", "B_TV"]在这里我将选择“E”和“B\u TV”


Tags: 数据代码in示例dfforindex字典
1条回答
网友
1楼 · 发布于 2024-10-05 14:29:19

尝试这种矢量化方法:

样品测向:

In [80]: df = pd.DataFrame(np.random.randint(10, size=(5,7)), columns=['id']+list('abcdef'))
    ...: df = df.set_index('id')
    ...:

In [81]: df
Out[81]:
    a  b  c  d  e  f
id
4   4  0  8  8  4  8
0   2  4  7  3  1  4
9   3  6  5  7  3  4
5   7  6  3  8  9  1
6   3  7  6  1  7  9

解决方案:

In [82]: idx = np.argsort(df.values, axis=1)[:, ::-1][:, :3]

In [83]: pd.DataFrame(np.take(df.columns, idx), index=df.index).T.to_dict('l')
Out[83]:
{0: ['c', 'f', 'b'],
 4: ['f', 'd', 'c'],
 5: ['e', 'd', 'a'],
 6: ['f', 'e', 'b'],
 9: ['d', 'b', 'c']}

PS用[:, :top_n]替换[:, :3]

相关问题 更多 >