AttributeError: 'DataFrame' object has no attribute 'allah1__27' - python

I'm trying to solve this and I'm pretty sure the code is right but it keeps getting me the same Error.
I have tried this:
import datetime
from datetime import datetime as datet
test_df = shapefile.copy()
test_df['timestamp'] = prediction_time
test_df['allah1__27'] = shapefile.allah1__27.astype('int64')
test_df['hour'] = prediction_time.hour
test_df['weekday'] = prediction_time.weekday()
test_df['month'] = prediction_time.month
def add_join_key(df):
df['join_key'] = df.allah1__27.map(int).map(str)+df.timestamp.map(datetime.isoformat)
df = df.set_index('join_key')
return df
weath_df = wdf.loc[prediction_time]
test_df = add_join_key(test_df)
weath_df = add_join_key(weath_df.reset_index())
And I get this Error:
AttributeError: module 'datetime' has no attribute 'isoformat'
Also I tried:
def add_join_key(df):
df['join_key'] = df.allah1__27.map(int).map(str)+df.timestamp.map(datet.isoformat)
df = df.set_index('join_key')
return df
weath_df = wdf.loc[prediction_time]
test_df = add_join_key(test_df)
weath_df = add_join_key(weath_df.reset_index())
And I get this Error:
AttributeError: DataFrame' object has no attribute 'allah1__27'
Did I miss something?

For the first error: the method isoformat is from datetime that's a method of datetime.
You should:
import datetime
datetime.datetime.isoformat
Or:
from datetime import datetime as datet
datet.isoformat
As for the second error:
df is a dictionary, i think you should call it:
df['join_key'] = df['allah1__27'].map(int).....

Related

I am getting a "'NoneType' object is not subscriptable" when trying to bring in data from a URL

Here is my code:
#Import libraries
import os
import pandas as pd
import requests
import matplotlib.pyplot as plt
import numpy as np
from datetime import date
import matplotlib.ticker as ticker
# API Key from EIA
api_key = 'blah blah'
# api_key = os.getenv("EIA_API_KEY")
# PADD Names to Label Columns
# Change to whatever column labels you want to use.
PADD_NAMES = ['PADD 1','PADD 2','PADD 3','PADD 4','PADD 5']
# Enter all your Series IDs here separated by commas
PADD_KEY = ['PET.MCRRIP12.M',
'PET.MCRRIP22.M',
'PET.MCRRIP32.M',
'PET.MCRRIP42.M',
'PET.MCRRIP52.M']
# Initialize list - this is the final list that you will store all the data from the json pull. Then you will use this list to concat into a pandas dataframe.
final_data = []
# Choose start and end dates
startDate = '2009-01-01'
endDate = '2021-01-01'
# Pull in data via EIA API
for i in range(len(PADD_KEY)):
url = 'http://api.eia.gov/series/?api_key=' + api_key + PADD_KEY[i]
r = requests.get(url)
json_data = r.json()
if r.status_code == 200:
print('Success!')
else:
print('Error')
df = pd.DataFrame(json_data.get('series')[0].get('data'),
columns = ['Date', PADD_NAMES[i]])
df.set_index('Date', drop=True, inplace=True)
final_data.append(df)
Here is my error:
TypeError Traceback (most recent call last)
<ipython-input-38-4de082165a0d> in <module>
10 print('Error')
11
---> 12 df = pd.DataFrame(json_data.get('series')[0].get('data'),
13 columns = ['Date', PADD_NAMES[i]])
14 df.set_index('Date', drop=True, inplace=True)
TypeError: 'NoneType' object is not subscriptable
'NoneType' object is not subscriptable comes when you try to find value in a none object like df["key"] where df is None.
Do you have PADD_NAMES defined somewhere in your code. For me the error looks like the issue of your json data. have you tried printing your json data?
The API you are calling requires HTTPS protocol to access, try to change "http" to "https"
https://api.eia.gov/series/?api_key=
Consider adding some debug output to check for other errors, by changing if...else block like this
if r.status_code == 200:
print('Success!')
else:
print('Error')
print(json_data)

AttributeError: 'NoneType' object has no attribute 'date'

I have been working on a script for Google research but I have no previous experience using pandas.
I have been following a tutorial and written material to complete this but this part of my code doesn't seem to be working(maybe outdated syntax).
The error that I get is AttributeError: 'NoneType' object has no attribute 'date':
def get_search_console_data(webproperty, days=-365):
if webproperty is not None:
query = webproperty.query.range(start='today', days=days).dimension('date', 'query')
r = query.get()
df = pd.DataFrame(r.rows)
return df
print("Web property doesn't exist, please select a valid one from this list")
print(account.webproperties)
df = get_search_console_data(webproperty)
df["date"] = pd.to_datetime(df.date)
df[df["date"] > "2021-10-3"]
last_day_queries = df[df["date"] > "2021-10-3"]["query"]
rest_of_queries = df[df["date"] < "2021-10-3"]["query"]
Any help would be appreciated

Get object class datetime from sqlalchemy query result

I try go get datetime object class from sqlalchemy query like this:
curr_date = engine.execute("SELECT getdate() ").fetchall()
dt = [d.strptime('%d/%m/%y %H:%M:%S') for d in curr_date]
and get this error:
Traceback (most recent call last):
...
dt = [d.strptime('%d/%m/%y %H:%M:%S') for d in curr_date]
AttributeError: Could not locate column in row for column 'strptime'
Please, advise, how to fix it?
It seems like I solved:
curr_date = engine.execute("SELECT getdate() ").fetchone()
print(curr_date[0])

AttributeError: module 'pptx.chart' has no attribute 'data'

I'm trying to update the chart data on a PowerPoint slide using python-pptx but I keep getting this error:
Traceback (most recent call last):
File "<ipython-input-10-ef4a9899fa31>", line 1, in <module>
chart_data = pptx.chart.data.CategoryChartData()
AttributeError: module 'pptx.chart' has no attribute 'data'
I can't figure out why. Here is my code:
import pptx
import pandas as pd
df = pd.read_excel("data.xlsx")
overall_report = pptx.Presentation("pres.pptx")
pres_slide = overall_report.slides[1]
slide_chart = pres_slide.shapes[20].chart
#replace chart data with the data from the excel above
chart_data = pptx.chart.data.CategoryChartData()
chart_data.categories = df["Question"].values.tolist()
df1 = df.iloc[:,1:6].copy()
for col_idx, col in enumerate(df1.columns):
print(col_idx,col,df1.iloc[:, col_idx].values)
chart_data.add_series(col,(df1.iloc[:, col_idx].values))
#update data
slide_chart.replace_data(chart_data)
pptx.chart should have an attribute 'data', right?
You are confusing the computer by not using an import. Try:
from pptx.chart.data import CategoryChartData
# your code
chart_data = CategoryChartData()
# more code
The example here might be useful too!

Python - an identical line of code using datetime fails in one file but not another

I have the following lines of code in project A
#filename : mod_dates
#Handles date calculations etc
import datetime
class datecalcs:
def __init__(self):
self.__menuChoice = 0
self.__datemonth = "not set"
self.__effectivedate = ""
self.__year = 0
self.__month = 0
return None
#
def interestcouponpaydates(self,effectivedate,couponday):
self.__effectivedate = effectivedate
year, month, day = map(int,self.__effectivedate.split('-'))
print(year)
print(month)
return self.__effectivedate
When I call them from another file with
import mod_dates
import datetime
import modcalinputs
datesclass = mod_dates.datecalcs()
calcInputs = modcalinputs.calcinputs()
#Get the coupon date
interestdateeffective = calcInputs.interestdateffective()
interestdatecoupon = calcInputs.interestdatecoupon()
x = datesclass.interestcouponpaydates(interestdateeffective,interestdatecoupon)
print(x)
However this returns an error on the x = datesclass... line of
year, month, day = map(int,self.__effectivedate.split('-'))
raises:
> AttributeError: 'datetime.date' object has no attribute 'split'
When I run from a similar project to the same line with the same syntax it works fine. Any ideas on what I am doing wrong?
Looks like something is assigning a datetime.date object to __effectivedate. You can't call split() on that:
>>> import date
>>> d = d = datetime.date(2012,3,12)
>>> d.split('-')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'datetime.date' object has no attribute 'split'
You can convert it to a string and split:
>>>str(d).split('-')
['2012', '03', '12']

Categories

Resources