I am trying to write a df to a Word document by the following code:
import win32api
import win32
# data frame
wordApp = win32.gencache.EnsureDispatch('Word.Application')
wordApp.Visible = False
doc = wordApp.Documents.Open(os.getcwd()+'\\template.docx')
rng = doc.Bookmarks("PUTTABLEHERE").Range
# creating Table
# add one more row in table at word because you want to add column names as header
Table=rng.Tables.Add(rng,NumRows=df.shape[0]+1,NumColumns=df.shape[1])
for col in range(df.shape[1]):
# Writing column names
Table.Cell(1,col+1).Range.Text=str(df.columns[col])
for row in range(df.shape[0]):
# writing each value of data frame
Table.Cell(row+1+1,col+1).Range.Text=str(df.iloc[row,col])
I however get the following error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-32-b3ea6c24ddfe> in <module>
1 # data frame
----> 2 wordApp = win32.gencache.EnsureDispatch('Word.Application')
3 wordApp.Visible = False
4 doc = wordApp.Documents.Open(os.getcwd()+'\\template.docx')
5 rng = doc.Bookmarks("PUTTABLEHERE").Range
AttributeError: module 'win32' has no attribute 'gencache'
What am I doing wrong?
Related
import requests # get connection
import pandas as pd
import json
def get_info(data):
data=[]
source=[]
published_date=[]
adx_keywords=[]
byline=[]
title=[]
abstract=[]
des_facet=[]
per_facet=[]
media=[]
Api_Key=''
url='https://api.nytimes.com/svc/mostpopular/v2/viewed/7.json?api-key=' # key redacted
response=requests.get(url).json()
for i in response['results']:
source.append(i['source'])
published_date.append(i['published_date'])
adx_keywords.append(i['adx_keywords'])
byline.append(i['byline'])
title.append(i['title'])
abstract.append(i['abstract'])
des_facet.append(i['des_facet'])
per_facet.append(i['per_facet'])
media.append(i['media'])
data=data.append({'source':source,'published_date':published_date,'adx_keywords':adx_keywords,byline':byline, 'title':title,'abstract':abstract,'des_facet':des_facet,
'per_facet':per_facet,'media':media})
df=df.append(d)
return df
df NameError
Traceback (most recent call last)
<ipython-input-292-00cf07b74dcd> in <module>()
----> 1 df
NameError: name 'df' is not defined
your hyphens are in the the wrong place
before:
data=data.append({'source':source,'published_date':published_date,'adx_keywords':adx_keywords,byline':byline, 'title':title,'abstract':abstract,'des_facet':des_facet,
'per_facet':per_facet,'media':media})
after:
data=data.append({'source':source,'published_date':published_date,'adx_keywords':adx_keywords,'byline':byline, 'title':title, 'abstract':abstract,'des_facet':des_facet,
'per_facet':per_facet,'media':media})
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)
I am trying to read a npz folder. My zipped folder (cora.npz) has npy files in an array format. When I try to load a sparse graph from a numpy binary file, I get this error:
AttributeError Traceback (most recent call last)
<ipython-input-19-e58ac31009ee> in <module>
----> 1 _A_obs, _X_obs, _z_obs = utils.load_npz('data/cora.npz')
2 _A_obs = _A_obs + _A_obs.T
3 _A_obs[_A_obs > 1] = 1
4 lcc = utils.largest_connected_components(_A_obs)
5
~/Jupyter_Projects/NETTACK ALGORITHM/nettack/utils.py in load_npz(file_name)
28
29 if 'attr_data' in loader:
---> 30 attr_matrix = sp.csr_matrix((loader['attr_data'], loader['attr_indices'],
31 loader['attr_indptr']), shape=loader['attr_shape'])
32 else:
My code looks like this:
if not file_name.endswith('.npz'):
file_name += '.npz'
with np.load(file_name) as loader:
loader = dict(loader)
adj_matrix = sp.csr_matrix((loader['adj_data'], loader['adj_indices'],
loader['adj_indptr']), shape=loader['adj_shape'])
if 'attr_data' in loader:
attr_matrix = sp.csr_matrix((loader['attr_data'], loader['attr_indices'],
loader['attr_indptr']), shape=loader['attr_shape'])
else:
attr_matrix = None
labels = loader.get('labels')
#print(labels)
return adj_matrix, attr_matrix, labels
When I try to read my files with np.load('adj_indptr.npy',allow_pickle = True) the reading part finishes successfully and prints the numbers inside it in an array format.
This program is supposed to emit sound based on a CSV file.
There is a frequency range in the dataset of 37-32677. In the beginning I didn't add this in and got this same error message. I tried adding in this range and I am still getting the same error.
import winsound
import csv
winsound.Beep(261,100)
def preload(filename):
file = open(filename)
data = csv.reader(file)
return data
def getNote(sensorVal):
return int(sensorVal * 75)
def setup():
cleanedData = {}
notes = []
data = preload("data1.csv")
for row in data(range(36,32677)):
print(row)
if row[1] != "trial number":
sensorVal = float(row[4])
channel = int(row[7])
if channel not in cleanedData:
cleanedData[channel] = []
cleanedData[channel].append({"sensorVal":sensorVal})
notes.append(getNote(sensorVal))
return cleanedData,notes
def play(notes,time):
for note in notes:
winsound.Beep(note,time)
data, notes = setup()
play(notes, 200)
Error message:
Traceback (most recent call last):
File "C:/Users/clair/PycharmProjects/winSound/main.py", line 32, in <module>
data, notes = setup()
File "C:/Users/clair/PycharmProjects/winSound/main.py", line 16, in setup
for row in data(range(36,32677)):
TypeError: '_csv.reader' object is not callable
Process finished with exit code 1
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!