Home > database >  How to access a single element of a series in python
How to access a single element of a series in python

Time:03-16

I'm new to python, I normally use c or Java. I'm trying to access one element of a series to compare it to others. When I run the code it says there's an error because the truth value of a series is ambiguous. I know the problem is in the very last part of the code, specifically the "var" component in the for loop. "var" is a series apparently, but I tried to make it a int with the value of the ith element of the St series. I'm sorry for my messy code and confusing variable names, I'm not good with that stuff.

from yahoo_fin import stock_info as si
from yahoo_fin import options
import numpy as np
from scipy.stats import norm
import pandas as pd
from datetime import *
import matplotlib.pyplot as plt

stock1 = input("Enter 1 stock symbol: Ex:QQQ ")
#stock2 = input("Enter 2 stock symbol: Ex:QQQ ")
Day = int(input("Enter start day: Ex:8 "))
month = int(input("Enter start month: Ex:11 "))
year = int(input("Enter start year: Ex:2021 "))
today = date.today()
past = date(year,month,Day)
t = float((today - past).days)
future = date(2022,3,18)

options.get_options_chain(stock1)
chain = options.get_options_chain(stock1,future)

def interval(t):
        if float(t) > 600:
            interval = '1m'
        if float(t) < 600 and float(t) > 200: 
            interval = '1wk'
        else:
            interval = '1d'
        return interval

plt_1 = plt.figure(figsize=(6, 9))
df1 = data1[['open']]#/data1[['close']]
pdf1 = plt.plot(df1,color = 'red')
print(stock1 , "is red")

s = chain["calls"]['Implied Volatility'] 
St = chain["calls"].Strike

min = data1[['open'][0]]
absg = 0

for i in range(0, len(St)):    
    var =  int (St[i])
    if abs(min - var) < min:
        min = abs(min - var)

CodePudding user response:

min = data1[['open'][0]]

What you are doing here is accessing

data1['open']

since

>>> ['open'][0]
'open'

What's more you are overwriting the built-in function min.

CodePudding user response:

If your datatype from type(VariableName) is pandas.Series, then you can use the below code to access a particular element by index:

 ser = pd.Series(data)   
    
    # retrieve the first element
    print(ser[0])

You can use this link as a reference:
https://www.geeksforgeeks.org/accessing-elements-of-a-pandas-series/
Kindly you can check the error along with the line number so that it is easier to pinpoint.
<------------------------------------------------------------------------------------------>
Also, tip for that For Loop:
If you don't really need the indexing, just stick to:

for i in (0,St):
   var = int(i) #Converting type to int
  • Related