Home > database >  Is there any python-Dataframe function in which I can iterate over rows of certain columns?
Is there any python-Dataframe function in which I can iterate over rows of certain columns?

Time:03-15

Want to solve this kind of problem in python:

tran_df['bad_debt']=train_df.frame_apply(lambda x: 1 if (x['second_mortgage']!=0 and x['home_equity']!=0) else x['debt'])

I want be able to create a new column and iterate over index row for specific columns.

in excel it's really easy I did:

if(AND(col_name1<>0,col_name2<>0),1,col_name5)

Any help will be very appreciated.

CodePudding user response:

To iterate over rows only for certain columns:

for rowIndex, row in df[['col1','col2']].iterrows(): #iterate over rows

To create a new column:

df['new'] = 0  # Initialise as 0

CodePudding user response:

As a rule, iterating over rows in pandas is wrong. Use the np.where function from NumPy to select the right values for the rows:

tran_df['bad_debt'] = np.where(
         (tran_df['second_mortgage'] != 0) & (tran_df['home_equity'] != 0),
         1, tran_df['debt'])
  • Related