Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Issue Assigning Values With Iterrows

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

enter image description here

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

enter image description here

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading