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!
Related
I have imported the libraries, connected the multimeter, but I encounter an error related to a writer function
# =============================================================================
# VISA SETUP
# =============================================================================
import pyvisa as visa
rm = visa.ResourceManager()
rList = rm.list_resources()
my_instrument = rm.open_resource(rList[0])
idn_info = (my_instrument.query('*IDN?'))
print(idn_info)
# =============================================================================
# ============================================================================
import time
import matplotlib.pyplot as plt
import pandas as pd
DMM = my_instrument
#set parameters here:
xInc = 15 #number of seconds between samples
samples = 50 #number of samples you want overall
updateInc = 30 #how often the program reminds you it's running (in seconds)
xValues = []
yValues = []
for i in range(samples):
if (i*xInc) % updateInc == 0:
print("Acquiring data...")
time.sleep(xInc)
xValues.append(i * xInc)
yValues.append(float(DMM.query(':MEASure:VOLTage:DC?')))
#create simple reference plot
print("Plotting...")
xLabel = "Time (s)"
yLabel = "Voltage (V)"
plt.xlabel(xLabel)
plt.ylabel(yLabel)
plt.title('DM3058E Monitoring')
plt.plot(xValues, yValues)
#export to CSV in current directory
print("Exporting to CSV...")
df = pd.DataFrame({xLabel:xValues, yLabel:yValues})
df.to_csv('DM3058_Monitoring.csv')
print("Done!")
This is the code I receive:
Traceback (most recent call last):
File "C:\Users\rrashid\Desktop\py\QR_code\multimeter.py", line 4, in
import pyvisa as visa
File "C:\Users\rrashid\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pyvisa_init_.py", line 14, in
from importlib.metadata import version, PackageNotFoundError
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\importlib\metadata_init_.py", line 4, in
import csv
File "C:\Users\rrashid\Desktop\py\QR_code\csv.py", line 4, in
writer = csv.writer(file)
AttributeError: partially initialized module 'csv' has no attribute 'writer' (most likely due to a circular import)
PS C:\Users\rrashid\Desktop\py\QR_code>
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?
I am using the package rpy2 to use R language in Python environment. I am using the MSGARCH package which is only on R. The package is clearly suppose to come with the attribute predict.
https://rdrr.io/cran/MSGARCH/man/predict.html
I don't understand why I have this error. Do you have an idea please?
the full error message is :
Traceback (most recent call last):
File "markov.py", line 165, in <module>
pred = ms.predict(object = fitMCMC, newdata = None, nahead = '30L')
AttributeError: module 'MSGARCH' has no attribute 'predict'
The code is:
ms = importr('MSGARCH')
from rpy2.robjects import r, pandas2ri, numpy2ri, vectors
pandas2ri.activate()
numpy2ri.activate()
base = importr('base')
stats = importr('stats')
pred = ms.predict(object = fitMCMC, newdata = None, nahead = '30L')
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
plt.style.use('ggplot')
columns = ['user_id','order_dt','order_products','order_amount']
df = pd.read_csv('CDNOW_master.txt',names = columns,sep = '\s+')
df['order_date'] = pd.to_datetime(df.order_dt,format='%Y%m%d')
df['month'] = df.order_date.values.astype('datetime64[M]')
f = df.groupby('user_id')['month'].min().value_counts()
print(f)
Above is my code,my purpose is to get the value_counts of the users purchased in their first month, but only got the result of 'NoneType' object has no attribute 'fileno'.
any ideas? much appreciate
here are the traceback
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\practice\CDNOW.py", line 19, in <module>
print(f)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-packages\pandas\core\base.py", line 51, in __str__
return self.__unicode__()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-packages\pandas\core\series.py", line 982, in __unicode__
width, height = get_terminal_size()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-packages\pandas\io\formats\terminal.py", line 33, in get_terminal_size
return shutil.get_terminal_size()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 1071, in get_terminal_size
size = os.get_terminal_size(sys.__stdout__.fileno())
AttributeError: 'NoneType' object has no attribute 'fileno'
I am seeing this as well.
>>> type(sys.__stdout__)
<class 'NoneType'>
I get NoneType when calling dunder stdout while I am using idle. I assume that pandas wants to determine how much to display in the results and is looking for the sys output information. In the documentation, it mentions what this is, but not how to reset it.
I did this:
sys.__stdout__ = sys.stdout
and it fixed the problem, but I have not idea if I caused problems down the line.
You may wish to try out the following.
df = pd.read_csv('CDNOW_master.txt',usecols = columns,sep = '\s+')
instead of
df = pd.read_csv('CDNOW_master.txt',names = columns,sep = '\s+')
This solved my problem. Hope it solves yours too.
I am trying to save map and its legends using QGis Map composer. I have already template .
Here is code in python.
layers =iface.legendInterface().layers()
canvas=iface.mapCanvas()
for layer in layers:
# myFile = r"C:\Users\craj\Downloads\GraduatedTheme.qpt"
myFile = r"C:\Users\craj\Downloads\GraduatedTheme.qpt"
myTemplateFile = file(myFile, 'rt')
myTemplateContent = myTemplateFile.read()
myTemplateFile.close()
myDocument = QDomDocument()
myDocument.setContent(myTemplateContent, False)
newcomp = iface.createNewComposer()
newcomp.composition().loadFromTemplate(myDocument)
newcomp.composition().refreshItems()
for a in iface.mapCanvas().layers():
iface.legendInterface().setLayerVisible(a, False)
iface.legendInterface().setLayerVisible(layer, True)
newcomp.composition().refreshItems()
map_item = newcomp.composition()
map_item.getComposerItemById('map')
map_item.setMapCanvas(canvas)
map_item.zoomToExtent(canvas.extent())
newcomp.composition().refreshItems()
legend_item = newcomp.composition().getComposerItemById('legend')
legend_item.updateLegend()
newcomp.composition().refreshItems()
imagePath ='C:/Users/craj/Downloads/'+layer.name()+'.png'
image = newcomp.composition().printPageAsRaster(0)
image.save(imagePath,'png')
An error has occurred while executing Python code:
AttributeError: 'QgsComposition' object has no attribute 'setMapCanvas'
Traceback (most recent call last):
File "C:/Users/craj/.qgis2/python/plugins\JoinAttribute\Join_Attribute.py", line 436, in run
map_item.setMapCanvas(canvas)
AttributeError: 'QgsComposition' object has no attribute 'setMapCanvas'
If you look at the docs there is no setMapCanvas on QgsComposition. This method is in several other classes, such as QgsComposerMap. So based on the code calling getComposerItemById() what you likely need is this:
composition = newcomp.composition()
map_item = composition.getComposerItemById('map')
map_item.setMapCanvas(canvas)