dimanche 2 mai 2021

Pandas: Cannot get the right result when iterating and applying a conditional statement in a DataFrame's column

I have a dataframe frame in which I need to iterate through one of the columns and apply certain conditional statements for using one or the other set of equations.

I've written the code below. However, I'm not getting the right result. In the code, the input_data variable is checked for positive values, but the condition is not met when encountering a negative value and always applies the equations for the case of positive values.

thanks in advance for any advice on this

import pandas as pd
x=[-1,1]
y=[2,3]

df=pd.DataFrame({'x':x, 'y':y})
print(df)

   x  y
0 -1  2
1  1  3

input_data=df['x']

for i in range(len(input_data)):
    
if input_data[i]>0:
    df['z']=input_data[i]+1
    df['z2']=df['z']+1
    df['z3']=1
else:
    df['z']=input_data[i]-1
    df['z2']=df['z']-1
    df['z3']=0
        
print(df)
   x  y  z  z2  z3
0 -1  2  2   3   1
1  1  3  2   3   1

Aucun commentaire:

Enregistrer un commentaire