Good morning, I was having issues trying to assign values. Here’s the df:
data = {
"col1": ['a', 'b', 'c', 'd', 'e'],
"col2": [1, 1, 2, 2, 3],
"col3": [20, 3, 5, 4, 1],
"col4": [np.nan, np.nan, np.nan, np.nan, np.nan]
}
df = pd.DataFrame(data)
df
So what I want to do is if col2 is a 1, multiply col3’s value by 3 and assign that value to the same row on col4. If col2 is 2, multiply by 2 and do the same thing. If col2 is 1, multiply by 1.
Here’s what I tried to do:
for i, row in df.iterrows():
if row['col2'] == 1:
row['col4'] = row['col3'] * 3
if row['col2'] == 2:
row['col4'] = row['col3'] * 2
if row['col2'] == 3:
row['col4'] = row['col3'] * 1
df
However, my code didn’t seem to change the value.
I feel like my code was missing something small. I appreciate your help.
>Solution :
A possible solution, which uses a list to record the successive values of col4:
l = []
for _, row in df.iterrows():
if row['col2'] == 1:
l.append(row['col3'] * 3)
if row['col2'] == 2:
l.append(row['col3'] * 2)
if row['col2'] == 3:
l.append(row['col3'] * 1)
df['col4'] = l
Alternatively,
df['col4'] = (np.where(df['col2'] == 1, df['col3'] * 3,
np.where(df['col2'] == 2, df['col3'] * 2, df['col3'] * 1)))
Output:
col1 col2 col3 col4
0 a 1 20 60
1 b 1 3 9
2 c 2 5 10
3 d 2 4 8
4 e 3 1 1

