I have a dataframe that looks like this:
length code1 code2 code3
4 0 1 1
8 1 1 0
7 1 0 0
I want to write a function that checks the value in length. If the value is >= 7, I want to add 1 to the value present in code2 and code3. What is the best way to do this? So far, I have:
def char_count_pred(df):
if df.length >= 7:
df.code2 += 1
df.code3 += 1
return df
master_df = char_count_pred(master_df)
I understand I need to build a loop to iterate over each row, but I am confused on the most efficient way to loop through rows of and performing tasks on multiple columns.
edit
When trying the solutions below, I get the same errors:
When I try the script as is....
---------------------------------------------------------------------------
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
When I set the script to = a variable...
File "<ipython-input-140-9f2f40a5bb96>", line 3
df = df.loc[df.length>=7]+=1
^
SyntaxError: invalid syntax