1

I am a newcomer to python. I want to implement a "For" loop on the elements of a dataframe, with an embedded "if" statement.

Code:

import numpy as np
import pandas as pd

#Dataframes
x = pd.DataFrame([1,-2,3])
y = pd.DataFrame()

for i in x.iterrows():
    for j in x.iteritems():
        if x>0:
            y = x*2
        else:
            y = 0

With the previous loop, I want to go through each item in the x dataframe and generate a new dataframe y based on the condition in the "if" statement. When I run the code, I get the following error message.

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Any help would be much appreciated.

6
  • 1
    Do you perhaps mean if j>0? Commented Sep 28, 2018 at 10:54
  • Could you add an example of expected output? Commented Sep 28, 2018 at 10:54
  • If your data is one dimensional, as in your example, consider using a series instead. Commented Sep 28, 2018 at 10:58
  • @DanielRoseman when I do as you suggested, I get the error TypeError: '>' not supported between instances of 'tuple' and 'int' Commented Sep 28, 2018 at 10:58
  • @zipa The expected output would be a populated "y" dataframe with the same dimension as the "x" dataframe, but with values 2, 0, 6. Commented Sep 28, 2018 at 11:00

2 Answers 2

3

In pandas is best avoid loops if exist vectorized solution:

x = pd.DataFrame([1,-2,3], columns=['a'])

y = pd.DataFrame(np.where(x['a'] > 0, x['a'] * 2, 0), columns=['b'])
print (y)
   b
0  2
1  0
2  6

Explanation:

First compare column by value for boolean mask:

print (x['a'] > 0)
0     True
1    False
2     True
Name: a, dtype: bool

Then use numpy.where for set values by conditions:

print (np.where(x['a'] > 0, x['a'] * 2, 0))
[2 0 6]

And last use DataFrame constructor or create new column:

x['new'] = np.where(x['a'] > 0, x['a'] * 2, 0)
print (x)
   a  new
0  1    2
1 -2    0
2  3    6
Sign up to request clarification or add additional context in comments.

Comments

0

You can try this:

y = (x[(x > 0)]*2).fillna(0)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.