Reputation: 1264
When iterating through the rows of a DataFrame, how do I change the value of one element based on the value on another element in the same row?
I have the following code:
for index, row in df.iterrows():
if (row["A"] in mult):
row["B"] = row["B"] * mult[row["A"]]
This iterates through each row and sees if the value in "A" is present in a key in the dictionary (mult
). If it is in the dictionary, series "B" is multiplied by the floating point value coming from the dictionary.
The code runs without reporting an error - but when I examine the df it hasn't changed in the DataFrame.
Thanks - Steve
Upvotes: 2
Views: 6087
Reputation: 3232
First of all, you are trying to reinitialise local variable row
.
The correct code could be as follows:
for index,row in df.iterrows():
if row["A"] in mult:
df["B"].iloc[index] = row["B"] * mult[row["A"]]
However, that is an ugly way to handle middle-size or large DataFrames. The more pythonic solution could be as follows:
df["B"] = df.apply(lambda x: x["B"] * mult[x["A"]] if x["A"] in mult else x["B"], axis=1)
Upvotes: 4