the following code:

df ['weight'] = 1
for feature in df.fclass:
    if feature == 'bus_stop':
        df.weight = 150
    elif feature == 'taxi':
        df.weight = 100
        df.weight = 50  

results in the following dataframe:

enter image description here

I expected that the value of the 'weight' column to be 100 in the second column because df.fclass == taxi. Is there something wrong with the for loop or with my 'elif' request?


1 Answer 1


Instead of just setting values for specific rows (i.e. rows where fclass is equal to the feature), you are setting the whole column (df.weight) with the value. Given that the last feature of df.class is probably bus_stop, which has a weight of 150 based on your logic, the final output will have a weight column filled with only values of 150.

There are multiple ways of getting to the output you want: (1) you can use .apply with a function containing the logic you want, (2) use the .loc method to set values for just the rows you want (so just the rows where the fclass column has a specific value) in combination with a loop, or even better, (3) use numpy.where/numpy.select to set all values at once without looping over the different features.

# method 1
def weight_function(row):
    if row["fclass"] == "bus_stop":
        return 150
    elif row["fclass"] == "taxi":
        return 100
        return 50
df["weight"] = df.apply(weight_function, axis=1)

# method 2
for feature in df["fclass"].unique():
    if feature == "bus_stop":
        df.loc[df["fclass"] == feature, "weight"] = 150
    elif feature == "taxi":
        df.loc[df["fclass"] == feature, "weight"] = 100
        df.loc[df["fclass"] == feature, "weight"] = 50
# method 3
import numpy as np

conditions = [df["fclass"] == "bus_stop", df["fclass"] == "taxi", ~df["fclass"].isin(["bus_stop", "taxi"])]
choices = [150, 100, 50]
df["weight"] = np.select(conditions, choices)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.