I'm trying to run the below code
import requests
import pandas as pd
companies = requests.get(f'https://fmpcloud.io/api/v3/stock-screener? industry=Software§or=tech&marketCapLowerThan=10000000000&limit=100&apikey=c609af2465eb19e3c82f0c3c38cb51ea')
companies.json()
At this point it's working fine but when getting to the following part , I was receiving an error
technological_companies = []
for item in companies:
technological_companies.append(item['symbol'])
print(technological_companies)
The error was :
Traceback (most recent call last)
<ipython-input-8-61eef8b7699a> in <module>
1 technological_companies = []
2 for item in companies:
----> 3 technological_companies.append(item['symbol'])
4 print(technological_companies)
TypeError: byte indices must be integers or slices, not str
You are not storing the JSON value, use
import requests
import pandas as pd
companies = requests.get(f'https://fmpcloud.io/api/v3/stock-screener? industry=Software§or=tech&marketCapLowerThan=10000000000&limit=100&apikey=c609af2465eb19e3c82f0c3c38cb51ea')
companies = companies.json() # this is the line
Either store the json:
companies = companies.json()
Or loop over the json:
for item in companies.json():
Related
I'm trying to transfer strings into integers from the plans_data:
import pandas as pd
from bs4 import BeautifulSoup
import requests
plans_data = pd.DataFrame(columns = ['Country', 'Currency', 'Mobile', 'Basic', 'Standard', 'Premium'])
for index, row in countries_list.iterrows():
country = row['ID']
url = f'https://help.netflix.com/en/node/24926/{country}'
page = requests.get(url)
soup = BeautifulSoup(page.content, "html.parser")
results = soup.find("table", class_="c-table")
try:
plan_country = pd.read_html(results.prettify())[0] #creates a list(!) of dataframe objects
plan_country = plan_country.rename(columns = {'Unnamed: 0':'Currency'})
plan_country = pd.DataFrame(plan_country.iloc[0,:]).transpose()
plans_data = pd.concat([plans_data, plan_country], ignore_index=True)
except AttributeError:
country_name = row['Name']
print(f'No data found for {country_name}.')
plans_data.loc[index, 'Country'] = row['Name']
plans_data
Firstly, I atempted to transfer using function float:
# 1. Here we import pandas
import pandas as pd
# 2. Here we import numpy
import numpy as np
ans_2_1_ = float(plans_data['Basic', 'Standard', 'Premium'])
However, I always get the NameError:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_15368/3072127414.py in <module>
3 # 2. Here we import numpy
4 import numpy as np
----> 5 ans_2_1_ = float(plans_data['Basic', 'Standard', 'Premium'])
NameError: name 'plans_data' is not defined
How can I solve this problem?
If my code is not appropriate for my task "transfer strings into integers", can you advise me on how to convert?
The error indicates that the second piece of code does not know what plans_data is, so first make sure they plans_data is defined where you do that, ie in the same file or the same Jupyter notebook
second problem is that plans_data['Basic', 'Standard', 'Premium'] is not valid syntax
Thirdly, and probably is your real question, how to convert the values in those columns to floats.
Elements in columns 'Basic', 'Standard', 'Premium' are strings in currency format eg '£ 5.99'. You can convert them to floats as such (you need to do it for each column):
ans_2_1_ = plans_data['Basic'].str[1:].astype(float)
... # same for Standard and Premium
While running for loop in below code in python getting list index out of range error. Also, please let me know if the for loop can be written in a better way.
Error:- IndexError-Traceback (most recent call last)
<ipython-input-296-32d392aacb61> in <module>
---> 22 a = workbook.connections[0]
IndexError: list index out of range
Code:
import tableauserverclient as TSC
import pandas as pd
tableau_auth = TSC.PersonalAccessTokenAuth('{Token_Name}',
'{Token_Secret}' , site_id="{Site}")
server = TSC.Server('Site_url',use_server_version=True)
request_options = TSC.RequestOptions(pagesize=1000)
with server.auth.sign_in(tableau_auth):
all_workbooks_items = list(TSC.Pager(server.workbooks, request_options))
workbook_id=[workbook.id for workbook in all_workbooks_items]
connection2=pd.DataFrame({"Datasource_id":connection.datasource_id,
"Datasource_name":a.datasource_name,
"Workbook Name":workbook.name} , index=[0])
for wbk_ids in workbook_id:
workbook = server.workbooks.get_by_id(wbk_ids)
server.workbooks.populate_connections(workbook)
a = workbook.connections[0]
print({a.datasource_id,a.datasource_name,workbook.name})
connection2=connection2.append({"Datasource_id":a.datasource_id,
"Datasource_name":a.datasource_name,
"Workbook Name":workbook.name} ,ignore_index=True)
server.auth.sign_out()
Instead of
a = workbook.connections[0]
print({a.datasource_id,a.datasource_name,workbook.name})
connection2=connection2.append({"Datasource_id":a.datasource_id,
"Datasource_name":a.datasource_name,
"Workbook Name":workbook.name} ,ignore_index=True)
use
if workbook.connections:
a = workbook.connections[0]
print({a.datasource_id,a.datasource_name,workbook.name})
connection2=connection2.append({"Datasource_id":a.datasource_id,
"Datasource_name":a.datasource_name,
"Workbook Name":workbook.name} ,ignore_index=True)
I am new in python. I have a data frame with a column, named 'Name'. The column contains different type of accents. I am trying to remove those accents. For example, rubén => ruben, zuñiga=zuniga, etc. I wrote following code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import re
import unicodedata
data=pd.read_csv('transactions.csv')
data.head()
nm=data['Name']
normal = unicodedata.normalize('NFKD', nm).encode('ASCII', 'ignore')
I am getting error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-41-1410866bc2c5> in <module>()
1 nm=data['Name']
----> 2 normal = unicodedata.normalize('NFKD', nm).encode('ASCII', 'ignore')
TypeError: normalize() argument 2 must be unicode, not Series
The reason why it is giving you that error is because normalize requires a string for the second parameter, not a list of strings. I found an example of this online:
unicodedata.normalize('NFKD', u"Durrës Åland Islands").encode('ascii','ignore')
'Durres Aland Islands'
Try this for one column:
nm = nm.str.normalize('NFKD').str.encode('ascii', errors='ignore').str.decode('utf-8')
Try this for multiple columns:
obj_cols = data.select_dtypes(include=['O']).columns
data.loc[obj_cols] = data.loc[obj_cols].apply(lambda x: x.str.normalize('NFKD').str.encode('ascii', errors='ignore').str.decode('utf-8'))
Try this for one column:
df[column_name] = df[column_name].apply(lambda x: unicodedata.normalize(u'NFKD', str(x)).encode('ascii', 'ignore').decode('utf-8'))
Change the column name according to your data columns.
I am looking to find the total number of players by counting the unique screen names.
# Dependencies
import pandas as pd
# Save path to data set in a variable
df = "purchase_data.json"
# Use Pandas to read data
data_file_pd = pd.read_json(df)
data_file_pd.head()
# Find total numbers of players
player_count = len(df['SN'].unique())
TypeError Traceback (most recent call last)
<ipython-input-26-94bf0ee04d7b> in <module>()
1 # Find total numbers of players
----> 2 player_count = len(df['SN'].unique())
TypeError: string indices must be integers
Without access to the original data, this is guess work. But I think you might want something like this:
# Save path variable (?)
json_data = "purchase_data.json"
# convert json data to Pandas dataframe
df = pd.read_json(json_data)
df.head()
len(data_file_pd['SN'].unique())
simply if you are getting this error while connecting to schema. then at that time close the web browser and kill the Pg Admin Server and restart it. then it will be work perfectly
I am trying to print unique values of the column ADO_name in my data set. Following is the example data set and code I tried (which gives error):
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
data = {'ADO_name':['car1','car1','car1','car2','car2','car2'],
'Time_sec':[0,1,2,0,1,2],
'Speed.kph':[50,51,52,0,0,52]}
dframe = DataFrame(data)
for ado in dframe.groupby('ADO_name'):
ado_name = ado["ADO_name"]
adoID = ado_name.unique()
print(adoID)
Traceback (most recent call last):
File "C:\Users\Quinton\AppData\Local\Temp\Rtmp88ifpB\chunk-code-188c39fc7de8.txt", line 14, in <module>
ado_name = ado["ADO_name"]
TypeError: tuple indices must be integers or slices, not str
What am I doing wrong and how to fix it? Please help.
You can do: dframe["ADO_name"].unique().
You may want to correct your code or use the correct way.
Here is what you need to correct in your code.
for ado in dframe.groupby('ADO_name'):
ado_name = ado[1]["ADO_name"]
adoID = ado_name.unique()
print(adoID)