Sam c21
Sam c21

Reputation: 253

why do I keep getting the same answer with this conditional, python pandas

This might be a really dumb problem but I've been stuck on it for awhile.

Here's the csv

DATE,TIME,OPEN,HIGH,LOW,CLOSE,VOLUME
02/03/1997,09:30:00,3045.00,3045.00,3045.00,3045.00,28 
02/04/1997,09:30:00,3077.00,3078.00,3077.00,3077.50,280
02/05/1997,09:30:00,3094.00,3094.50,3094.00,3094.00,50 
02/06/1997,09:30:00,3106.00,3107.50,3106.00,3107.50,53
02/07/1997,09:30:00,3144.00,3144.00,3143.50,3143.50,15 
02/06/1997,16:20:00,3126.50,3126.50,3126.00,3126.00,24           
02/06/1997,16:21:00,3126.50,3128.00,3126.50,3128.00,169          
02/06/1997,16:22:00,3128.00,3128.00,3126.00,3126.00,243          
02/06/1997,16:23:00,3125.50,3126.50,3125.50,3125.50,26           

This is just example i made from the original cause the original is really long. I moved all the "09:30:00" to the top to make it easier.

But here's my code.

 df = pd.read_csv('example.txt', parse_dates = [["DATE", "TIME"]], index_col=0)

b930 = df.HIGH.at_time("09:30:00")

a=0
if 'b930 < 3044.00':
  a = 7
else:
  a = 10

print a 

If I run it this way i get a 7 which i probably shouldn't be.

a=0
if 'b930 > 3044.00':
   a = 7
else:
   a = 10

print a

And if I run it this way i get a 7 which is good.

I've honestly tried a bunch of other things but I erase them.

Upvotes: 0

Views: 39

Answers (2)

jezrael
jezrael

Reputation: 863351

You works with Series, so you have to use all or any:

b930 = df.HIGH.at_time("09:30:00")
print b930
DATE_TIME
1997-02-03 09:30:00    3045.0
1997-02-04 09:30:00    3078.0
1997-02-05 09:30:00    3094.5
1997-02-06 09:30:00    3107.5
1997-02-07 09:30:00    3144.0

#ValueError: The truth value of a Series is ambiguous. 
# Use a.empty, a.bool(), a.item(), a.any() or a.all().
if b930 < 3044.00:
  a = 7
else:
  a = 10
print a 

Check if all values are True:

print b930 < 3046.00
DATE_TIME
1997-02-03 09:30:00     True
1997-02-04 09:30:00    False
1997-02-05 09:30:00    False
1997-02-06 09:30:00    False
1997-02-07 09:30:00    False
Name: HIGH, dtype: bool

a=0
if (b930 < 3046.00).all():
  a = 7
else:
  a = 10
print a
10

Check if any values is True:

if (b930 < 3046.00).any():
  a = 7
else:
  a = 10
print a
7

Another example:

print b930 > 3044.00
DATE_TIME
1997-02-03 09:30:00    True
1997-02-04 09:30:00    True
1997-02-05 09:30:00    True
1997-02-06 09:30:00    True
1997-02-07 09:30:00    True
Name: HIGH, dtype: bool
a=0
if (b930 > 3044.00).all():
  a = 7
else:
  a = 10
print a
7

if (b930 > 3044.00).any():
  a = 7
else:
  a = 10
print a
7

Upvotes: 2

user764357
user764357

Reputation:

This is a non-empty string and will always be cast to True:

'b930 < 3044.00'

change it to:

b930 < 3044.00

Upvotes: 1

Related Questions