0

I should check if status is 'Yes' in column 'Bad_loan', if true, check other names in 'client_name', if client has another loans set value 'Yes' for all his loans

def bad_loan(df):
    for row in df:
        status = row['bad_loan']
        name = row['name_client']
        if status == 'Yes':
            for n in df:
                name_client = df['name_client']
                if name == name_client:
                    df['bad_loan'] = 'Yes'
                else:
                    df['bad_loan'] = 'No'

bad_loan(df)

it returns TypeError: string indices must be integers

Tom Ron
  • 5,906
  • 3
  • 22
  • 38
Mika
  • 75
  • 1
  • 8
  • 2
    Welcome to SO. provide a sample dataframe with expected output. use this as a guide : https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples. It is quite possible that there is a vectorized solution to ur problem. – sammywemmy Feb 05 '20 at 08:18

2 Answers2

0
for row in df:

You can't iterate this way with pandas

Try iloc like this

def bad_loan(df):
    for i in range(len(df)):
        row = df.iloc[i]
        status = row['bad_loan']
        name = row['name_client']
        if status == 'Yes':
            for n in df:
                name_client = df['name_client']
                if name == name_client:
                    df['bad_loan'] = 'Yes'
                else:
                    df['bad_loan'] = 'No'

bad_loan(df)
ikibir
  • 456
  • 4
  • 12
  • I tried it, and result ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). – Mika Feb 05 '20 at 08:55
  • probably you have NaN values inyour csv. Try adding "df.fillna(0)" before your for loop. (Chance 0 to whatever value you want) – ikibir Feb 05 '20 at 10:15
0
import numpy as np
import pandas as pd

#make a list of all the names with bad loans:

names = df[df["bad_loan"]=="Yes"]["name_client"]

#set bad loan to yes if name in list

df["bad_loan"] = np.where(df["name_client"].isin(names),"Yes","No")
Bendik Knapstad
  • 1,409
  • 1
  • 9
  • 18