luka
luka

Reputation: 529

If statement that checking value in current row and column

I would check if in the 'A' column current row is equal to red. Here the code that I tried, the original Dataframe and Expected output.

Dataframe


     A      B     Value
0   red     blue    1.2
1   black   red     1.3
2   green   red     2.2
3   red     brown   0.3
4   red     white   0.9
5   violet  red     1.1
for index, row in df.iterrows():
    if row['A'] == 'red':
        df['Value1'] = df['Value']
    else:
        df['Value2'] = df['Value']

Output


    A      B       Value    Value1  Value2
0   red    blue    1.2      1.2     1.2
1   black  red     1.3      1.3     1.3
2   green  red     2.2      2.2     2.2
3   red    brown   0.3      0.3     0.3
4   red    white   0.9      0.9     0.9
5   violet red     1.1      1.1     1.1

Expected Output


    A       B       Value   Value1  Value2
0   red     blue    1.2     1.2     NaN
1   black   red     1.3     NaN     1.3
2   green   red     2.2     NaN     2.2
3   red     brown   0.3     0.3     NaN
4   red     white   0.9     0.9     NaN
5   violet  red     1.1     NaN     1.1

The df_iterrows() method does not return the expected output. Is there a faster method that can do this task?

Upvotes: 1

Views: 1336

Answers (2)

F. Nielsen
F. Nielsen

Reputation: 77

If you want to check each row of the column to make after this some #code:

for row in df.iterrows():
   if t==row['A']:
     #code

If you only want to know in which rows of df['A'] the value of the element is t:

df.loc[df['A']==t, 'A']

or

df['A'].astype(str).str.contains('t')

EDIT

Check if it works for you:

df.loc[df['A']=='red','Value1']=df['Value']
df.loc[df['A']!='red','Value2']=df['Value']

Upvotes: 1

Aryerez
Aryerez

Reputation: 3495

You can not use if statements on pandas dataframe as it has different results for different rows. You need to do:

df.loc[df['A'] == t, some_col] = some_value

And it will change the value in some_col to some_value, in the lines where the value in column A is t.

Upvotes: 0

Related Questions