+-
python – 为pandas中的每一列获取非零值
我有pandas数据帧为df:

accel access adviser afpif  afp   publish  afraid verizon
0.00  0.14    0.00   0.00   0.00   0.13    0.00   0.44
0.13  0.00    0.00   0.77   0.00   0.00    0.22   0.00
0.00  0.00    0.87   0.00   0.34   0.00    0.00   0.00
......................................................
.....................................................

我还有一个列表L,它包含列名作为元素

L=['accel','afp','publish']

我只想基于pandas数据帧提取这些列表元素的非零值.

预期产出: –

dictionary={'accel':0.13,'afp':0.34,'publish':0.13}
最佳答案
使用 DataFrame.loc与dict理解和 iat如果始终存在至少一个非0值:

d = {c: df.loc[df[c] ! =0, c].iat[0] for c in L }
print (d)
{'accel': 0.13, 'afp': 0.34, 'publish': 0.13}

更常见的是只使用0列:

d = {c: next(iter(df.loc[df[c] != 0, c]), 'no value') for c in L }
print (d)
{'accel': 0.13, 'afp': 0.34, 'publish': 0.13}
点击查看更多相关文章

转载注明原文:python – 为pandas中的每一列获取非零值 - 乐贴网