首页 > 解决方案 > 逐行有条件地修改熊猫数据框中的列的有效方法

问题描述

我有一个看起来像这样的数据框:

length      code1    code2    code3
4            0         1        1
8            1         1        0
7            1         0        0

我想编写一个检查长度值的函数。如果值 >= 7,我想将 1 添加到 code2 和 code3 中存在的值。做这个的最好方式是什么?到目前为止,我有:

def char_count_pred(df):
    
    
    if df.length >= 7:
           df.code2 += 1
           df.code3 += 1

    return df


master_df = char_count_pred(master_df)

我知道我需要构建一个循环来遍历每一行,但我对循环遍历行和在多列上执行任务的最有效方法感到困惑。

编辑

尝试以下解决方案时,我得到相同的错误:

当我按原样尝试脚本时......


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
C:\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2889             try:
-> 2890                 return self._engine.get_loc(key)
   2891             except KeyError:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()

KeyError: True

当我将脚本设置为 = 一个变量时......


  File "<ipython-input-140-9f2f40a5bb96>", line 3
    df = df.loc[df.length>=7]+=1
                                                                                   ^
SyntaxError: invalid syntax

标签: pythonpandas

解决方案


df.loc[df.length >=7, ['code1','code2']]+=1

推荐阅读