NameError: name " " is not defined - python

New to python programming,While I was analysing spotify Datasets I got this error.
What I was doing was Plot a Line Graph to Show the Duration of the Songs for Each Year.
Any idea how do i fix this?
enter image description here
sns.displot(years,discrete=True,aspect=2,heights=5,kind="hist").set(title="Number of songs per year")
NameError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_12628\3904715389.py in
----> 1 sns.displot(years,discrete=True,aspect=2,heights=5,kind="hist").set(title="Number of songs per year")
NameError: name 'years' is not defined
This is the Sample spotify datasets
enter image description here
I expecting solution for the Error.

the data years which you are trying to visualize through distplot may not be defined. Make sure to store in the variable first like , years = Your_Sample_spotify_data["year"] and than you can defined it as the first argument of distplot().

Related

Issues with re and TypeError: expected string or bytes-like object

I'm using the Teleport API to produce heatmaps of different stats about cities when searched, but I'm having trouble with the whole using re to get something from what I got. So here's what I'm trying to search.
So once I put in the city, I would get something like this:
{'_embedded': {'city:search-results': [{'_links': {'city:item': {'href': 'https://api.teleport.org/api/cities/geonameid:5809844/'}},
So my entire code, including the re, which is causing my computer issues, is:
area = input("What's the city you'd like to see? ")
area = area.lower()
area = area.replace(' ','-')
if area == 'new-york-city':
area = 'new-york'
with urllib.request.urlopen('https://api.teleport.org/api/cities/?search='+area) as url:
#This brings in the info from the API.
api = json.loads(url.read().decode()) #This decodes the info coming in.
id = re.search('^geonameid:',api)
id = str(id)
api
And the error is that was the type error I got in the beginning. I think I just figured it out that it was coming from the search itself, because I tried coercing it to a string in the second line, but I got an error even when I commented out that line.
My second question is I'm not sure if I'm using the right code but I'm trying to find the first instance of the geonameid, as with common names, there could be others.
Any suggestions? Thanks!

How can I work around a KeyError in Python? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to create a Forecasting tool, which analyses historical passenger traffic at a given airport. The anylysis will be based on a linear regression with various GDPs (Gross Domestic Product) of countries related to the airport.
A person can type in the name of the independant variable, which then gets selected from the Excel file.
Once a person gets the question "Which Country's GDP would you like to set as the independant variable for the Regression Analysis?", there is the possibility of typing a country wrong. In that case I receive a KeyError.
I am trying to work around that with "try / except", but I still receive a KeyError (See lines 36-49). I would really appreciate some help!
Thank you!
If it helps, here is the GitHub Link: https://github.com/DR7777/snowflake
(See lines 36-49 of main_file.py)
Here is my code:
Ive tried with while loops, for / except, but it seems I am too new to understand.
# This part saves the first row of the Excel as a list,
# so I can give the user a list of all the countries,
# if the person types in a country, that's not on the list.
loc = ("IMF_Country_GDP_Data.xlsx")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)
list_of_countries = sheet.row_values(0)
possible_selection = (list_of_countries[1:]) #This is the list with all the possible countries, without the Excel cell A1
#Introduction
print("Hello, welcome to the Air Traffic Forecasting Tool V0.1!")
print("Which Country's GDP would you like to set as the independant variable for the Regression Analysis?")
Country_GDP = input("Please type your answer here: ")
#here we check, if the typed Country is in the list
try:
possible_selection == Country_GDP
print("Your country is on the list.")
except KeyError:
print("Oh no! You typed a country, which is not in our database!")
print("Please select one of the countries listed below and try again")
print(possible_selection)
#now continuing with the previous code
print("Ok, I will conduct the analysis based on the GDP of " + str(Country_GDP) + "!")
print("Here are your results: ")
#here is the rest of the code
What I want to achieve is:
If a person types a name, which is on the list of countries, the program runs the regression.
If the country is not on the list, I dont want to receive a KeyError. I would like the program to say:
Oh no! You typed a country, which is not in our database!
Please select one of the countries listed below and try again
And then print the possible_selection variable, so the user can see which selection he has.
Thank you very much!
No need to get a key error at all. Just use in.
while True:
selection = input('Which country?')
if selection in list_of_countries:
print('Your country is on the list')
break
else:
print('You typed an invalid entry, lets try again')

Need to understand my error message to move forward

I am trying to use the following to retrieve stock data from Yahoo. can anyone tell me why this is not working? I would be super grateful for reply
here is my input
import pandas_datareader as pdweb
from pandas_datareader import data, wb
import datetime
prices = pdweb.get_data_yahoo(['CVX', 'XOM','BP'], start=datetime.datetime(2010,1,1), end=datetime.datetime(2013,1,1)) ,
['Adj Close']
prices.head()
here is the error message
AttributeError Traceback (most recent call last)
<ipython-input-9-95b02a209848> in <module>()
----> 1 prices = pdweb.get_data_yahoo(['CVX', 'XOM','BP'], start=datetime.datetime(2010,1,1), end=datetime.datetime(2013,1,1)) ,
2 ['Adj Close']
3
4 prices.head()
AttributeError: 'tuple' object has no attribute 'head'
It looks like the function you are calling is returning a tuple. And it looks like you want to access an instance of the class pdweb. To do this do:
P = pdweb()
Tuple = p.get_data_yahoo()
P.head()
Just a suggestion, I don't know how this library works, but I hope that this helps!
Edit:
Actually, as inspectorg4det said, since it's a tuple and not a list you would use tuple[index] to get an element. I do not know what I was thinking when I saw this question.

Cannot loop over an array [duplicate]

This question already has an answer here:
Access specific information within worklogs in jira-python
(1 answer)
Closed 5 years ago.
I'm trying to insert the following worklog JSON fields that are part of an array using Python however I don't seem to be able to loop over an array in Python.
See code snippet below:
try:
worklogs_to_insert = []
for i in issue.fields.worklog["worklogs"]:
worklogs_to_insert.append(i)
except AttributeError as e:
log.info("Something went wrong when processing worklogs. :(")
log.info(e)
I am getting the following error when script is run:
Something went wrong when processing worklogs. :(
type object 'PropertyHolder' has no attribute 'worklog'
try using
for i in issue.fields.worklog.raw["worklogs"]

"Invalid slice" when ploting using matplotlib

Python 2.7.5 and OSX 10.8 here
I'm trying to plot some datas I get from a file.
I'm trying to code a function where the user is able to plot from the point he wants, and have come to this part of code :
firstPoint = raw_input("1st point to be displayed is n° : ")
tbdata3 = hdulist[3].data
print(hdulist[3].header['TTYPE24'])
print tbdata3.field('DDL_FT_OPL')
print(hdulist[3].header['TTYPE23'])
print tbdata3.field('DDL_SC_OPL')
dataFT=tbdata3.field('DDL_FT_OPL')
plt.subplot(211)
plot(dataFT[firstPoint:400,:])
dataSC=tbdata3.field('DDL_SC_OPL')
plt.subplot(212)
plot(dataSC[firstPoint:400,:])
show()
I get this error :
Traceback (most recent call last):
File "/Users/geoffroysarrazin/Desktop/stage_observatoire/testEkki.py", line 52, in essai
plot(dataFT[firstPoint:400,:])
IndexError: invalid slice
And it seems weird to me, cause I got this with
firstPoint=10
and just before, I had a constant value instead of this input from the user, which was equal to 200 (or whatever <400) and it worked...
Simple - you're not converting your input!
firstPoint = int(raw_input("1st point to be displayed is n° : "))
You can add some exception handling to re-prompt the user if he doesn't provide a number, if you so wish.

Categories

Resources