我使用下面的代码遍历数据帧的行
以下是示例数据集:
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”
尝试这种矢量化方法:
样品测向:
解决方案:
PS用
[:, :top_n]
替换[:, :3]
相关问题 更多 >
编程相关推荐