Skip to content
Advertisement

What is the difference between “df[‘Good Quality’] = [1 if x>=7 else 0 for x in df[‘quality’]]” and expand lined given below?

What is the difference between

df['Good Quality'] = [1 if x>=7 else 0 for x in df['quality']]

and

for x in df['quality']:
    if x>=7:
        df['Good Quality'] = 1
    else:
        df['Good Quality'] = 0

data frame is not changing for x>=7 if I used the second one? What is the logical error happening here?

Advertisement

Answer

You need to mention that for loop in the pythonic style syntax

for x in df['quality']:
    if x>=7:
        df['Good Quality'] = 1
    else:
        df['Good Quality'] = 0
Edit : I forgot about list result
result = []
for x in df['quality']:
    if x>=7:
         result.append(1)
    else:
         result.append(0)

df['Good Quality'] = result

You may test this.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement