为 pandas 中的每一列获取非零值 [英] Get non zero values for each column in pandas

查看:79
本文介绍了为 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,其中包含列名称作为元素

I also have a list L which consist columns names as elements

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

所有我想基于pandas dataframe提取这些列表元素的非零值.

All I want to extract non zero values of these list elements based on pandas dataframe.

预期输出:-

dictionary={'accel':0.13,'afp':0.34,'publish':0.13}

推荐答案

使用 DataFrame.loc ,具有dict理解和 iat (如果始终存在至少一个非0值:

Use DataFrame.loc with dict comprehension and iat if always exist at least one non 0 value:

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列:

More general working with only 0 columns too:

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}

这篇关于为 pandas 中的每一列获取非零值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆