Python - 每次 A 列等于 0 时从 B 列返回值

标签 python pandas numpy dataframe

每当 A 列等于 0 时,我想返回 B 列的值。我当前的代码:

for i in df:
    checkfornulls = df.ix[(df['A'][i] == 0).idxmin(),'B']
    if checkfornulls is None:
        print "Column A Pass!"
    else:
        print checkfornulls

如果我自己运行它:

checkfornulls = df.ix[(df['A'][i] == 0).idxmin(),'B']
    if checkfornulls is None:
        print "Column A Pass!"
    else:
        print checkfornulls

然后它带回它找到的第一个 0。有谁知道如何使 for 循环工作,以便返回 A 等于 0 的每个实例?

最佳答案

pandas 提供了大量方法来完成此任务。关于哪个是最好的、最 pythonic 的(不管那是什么意思)还是 pandantic(另一个虚构的词)是完全个人的决定。

使用查询
df.query('A == 0').B
或者
df.query('A == 0')['B']

关于Python - 每次 A 列等于 0 时从 B 列返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41711377/

相关文章:

python - 使用ctypes从python调用C函数

python - 如何使用 Python 比较 2 个非常大的矩阵

python - 如何在循环中追加多个 pandas DataFrame?

python - pandas在ubuntu上安装错误代码1 in/tmp/pip-build-FM0q5o/pandas/

python - 从 numpy 矩阵中查找值列表的行索引

python - Django url参数传递

python - 无法从 'StandardScalar' 导入名称 'sklearn.preprocessing'

python - 为 Pandas 更新 iterrow 中的值

python - flask : 'Token' object has no attribute 'test' | render_template error

python - 从 Meshgrid reshape pandas DataFrame