I get the following error:
NameError Traceback (most recent call last)
in
81 writer.save()
82
---> 83 write_excel(res)
84
NameError: name 'res' is not defined
Could you please help? :)
def read_merge(file):
"""" read files and merge the data """
username = pd.read_csv('file.csv', delimiter = ';')
merged_output = pd.read_excel('file-1.xlsx')
merged_output = pd.merge(merged_output, username, how='left', left_on=['h'], right_on=['h2'])
merged_output = merged_output.drop(columns=['h2'])
return(merged_output)
def remove_string(merged_output):
"""" remove rows containing strings from list_string """
list_string = ["obj-1", "obj-2"]
res = merged_output[~merged_output['Rule'].isin(list_string)]
return res
def add_agg_columns(res):
""""aggregate columns"""
res = res.groupby('Entity_Name').agg({'Rule': ', '.join,
'Name':'first',
'Area': 'first',
'Summary': 'first'}).reset_index()
def write_excel(res):
""""Write Excel document"""
writer = pd.ExcelWriter(r"C:\PATH\output.xlsx", engine = 'xlsxwriter')
workbook=writer.book
worksheet=workbook.add_worksheet('SHEET')
writer.sheets['SHEET'] = worksheet
res.to_excel(writer, sheet_name='SHEET', startcol = 0, startrow = 0)
writer.save()
write_excel(res)
The last line of code write_excel(res) references variable res which is not defined in your code.
The error message NameError: name 'res' is not defined should give you some clue at to what is going on
Related
I try to make excel file with Python. For that I use win32com because that seem the best way to make pivot table (pandas is not a good solution), but I have some troubles.
First when I try to make a pivot table on Sheet where there is already a pivot table i have that error message:
Traceback (most recent call last):
File "<ipython-input-55-62ca0c0e21ec>", line 1, in <module>
PivotTable = PivotCache.CreatePivotTable(TableDestination=PivotTargetRange, TableName=PivotTableName, DefaultVersion=win32c.xlPivotTableVersion14)
File "C:\Users\LPLOUV~1\AppData\Local\Temp\gen_py\3.7\00020813-0000-0000-C000-000000000046x0x1x9\PivotCache.py", line 45, in CreatePivotTable
, TableName, ReadData, DefaultVersion)
com_error: (-2147352567, 'Une exception s’est produite.', (0, None, None, None, 0, -2146827284), None)
Second I need to remake some pivot table that exist already, so I need to delete some pivote table from sheet but I don't know how I can make that.
Until there I use this code:
import os
import win32com.client
import time
time_first = time.time()
os.chdir(r'C:\Users\msmith\Desktop')
Excel = win32com.client.gencache.EnsureDispatch('Excel.Application') # Excel = win32com.client.Dispatch('Excel.Application')
win32c = win32com.client.constants
wb = Excel.Workbooks.Open('excel_file.xlsx')
Sheet1 = wb.Worksheets("Sheet1")
Sheet2 = wb.Worksheets("Sheet2")
xldata = Sheet1.UsedRange.Value
data_pivot = xldata[:24291]
cl1 = Sheet1.Cells(1,1)
cl2 = Sheet1.Cells(1+len(data_pivot)-1,1+len(data_pivot[0])-1)
PivotSourceRange = Sheet1.Range(cl1,cl2)
cl3=Sheet2.Cells(200,200)
PivotTargetRange= Sheet2.Range(cl3,cl3)
PivotTableName = 'ReportPivotTable'
PivotCache = wb.PivotCaches().Create(SourceType=win32c.xlDatabase, SourceData=PivotSourceRange, Version=win32c.xlPivotTableVersion14)
PivotTable = PivotCache.CreatePivotTable(TableDestination=PivotTargetRange, TableName=PivotTableName, DefaultVersion=win32c.xlPivotTableVersion14)
PivotTable.PivotFields('A').Orientation = win32c.xlRowField
PivotTable.PivotFields('A').Position = 1
PivotTable.PivotFields('B').Orientation = win32c.xlPageField
PivotTable.PivotFields('B').Position = 1
PivotTable.PivotFields('B').CurrentPage = 'b'
PivotTable.PivotFields('C').Orientation = win32c.xlPageField
PivotTable.PivotFields('C').Position = 2
PivotTable.PivotFields('C').CurrentPage = 5
PivotTable.PivotFields('D').Orientation = win32c.xlPageField
PivotTable.PivotFields('D').Position = 1
PivotTable.PivotFields('D').CurrentPage = 'd'
PivotTable.PivotFields('E').Orientation = win32c.xlPageField
PivotTable.PivotFields('E').Position = 3
PivotTable.PivotFields('E').CurrentPage = "(All)"
PivotTable.PivotFields('D').Orientation = win32c.xlColumnField
PivotTable.PivotFields('D').Position = 1
DataField = PivotTable.AddDataField(PivotTable.PivotFields('F'), Function = win32c.xlSum)
DataField = PivotTable.AddDataField(PivotTable.PivotFields('G'), Function = win32c.xlSum)
wb.SaveAs('excel_file.xlsx')
Excel.Application.Quit()
I think you have a blank field in your data. For example:
This will give you the error.
This will not.
I am trying to access Salesforce through their API. I am trying to run the preliminary code but I get a NameError which doesn't make any sense to me at the moment.
This is my first time taking the previous developers code and trying to run it. I keep getting an error after error.
l=[]
for p in products:
query = 'SELECT '
for c in columns[:-1]:
query += c+','
if (p=='Sigma Upgrade to Insight'):
query += columns[-1] + ' FROM Implementation__c WHERE Imp_Type__c = \''+p+'\''
else:
query += columns[-1] + ' FROM Implementation__c WHERE Imp_Type__c INCLUDES (\''+p+'\') AND Implementation_Status__c != \'PE Trial Ended\''
df_temp = pd.DataFrame(sf.query(query))
l.append(df_temp)
runthrough = ('nextRecordsUrl' in df_temp.columns)
while runthrough:
df_temp = pd.DataFrame(sf.query_more(nextRecord,True))
l.append(df_temp)
runthrough = ('nextRecordsUrl' in df_temp.columns)
I am expecting to run this without any errors but I keep getting a NameError
NameError Traceback (most recent call last)
<ipython-input-4-7b44b14c79ff> in <module>
14 runthrough = ('nextRecordsUrl' in df_temp.columns)
15 while runthrough:
---> 16 df_temp = pd.DataFrame(sf.query_more(nextRecord,True))
17 l.append(df_temp)
18 runthrough = ('nextRecordsUrl' in df_temp.columns)
NameError: name 'nextRecord' is not defined
You need to set nextRecord to the value of the nextRecordsUrl element of df_temp.
df_temp = pd.DataFrame(sf.query(query))
l.append(df_temp)
while 'nextRecordsUrl' in df_temp.columns:
nextRecord = df_temp['nextRecordsUrl']
df_temp = pd.DataFrame(sf.query_more(nextRecord,True))
l.append(df_temp)
I am using this function to pull data from the Cryptocompare website into a pandas dataframe:
def daily_price_historical(symbol, comparison_symbol='USD', limit=1, aggregate=1, exchange='', allData='true'):
url = 'https://min-api.cryptocompare.com/data/histoday?fsym={}&tsym={}&limit={}&aggregate={}&allData={}'\
.format(symbol.upper(), comparison_symbol.upper(), limit, aggregate, allData)
if exchange:
url += '&e={}'.format(exchange)
page = requests.get(url)
data = page.json()['Data']
df = pd.DataFrame(data)
df['timestamp'] = [datetime.datetime.fromtimestamp(d) for d in df.time]
df.set_index('timestamp', inplace=True)
df['symbol'] = symbol
df['1dret'] = 100* df['close'].pct_change()
return df
This works fine for most symbols I pass in, but when I loop over a longer list of symbols I get the error: AttributeError: 'DataFrame' object has no attribute 'time'
I assume this is due to the API returning an error for certain symbols, e.g.:
https://min-api.cryptocompare.com/data/histoday?fsym=FAKE&tsym=USD
returns "Response":"Error" with no further data
I'm afraid I'm not very experienced with url requests/APIs. Is there code I can add to the function to skip the symbols that are causing the issue?
Thanks for your help!
Additional information:
Code used to loop over coins (which is a list of 130 symbols):
price_columns = ['close', 'high', 'low', 'open', 'time',
'volumefrom','volumeto', 'symbol', '1dret']
top_coin_prices = pd.DataFrame(columns=price_columns)
for coin in coins:
output = daily_price_historical(coin)
top_coin_prices = top_coin_prices.append(output)
Full Traceback:
AttributeError Traceback (most recent call last)
<ipython-input-277-126f5d1686b2> in <module>()
8 # populate df with data for all coins
9 for coin in coins:
---> 10 output = daily_price_historical(coin)
11 top_coin_prices = top_coin_prices.append(output)
12
<ipython-input-111-65b3fa76b4ab> in daily_price_historical(symbol, comparison_symbol, limit, aggregate, exchange, allData)
7 data = page.json()['Data']
8 df = pd.DataFrame(data)
----> 9 df['timestamp'] = [datetime.datetime.fromtimestamp(d) for d in df.time]
10 df.set_index('timestamp', inplace=True)
11 df['symbol'] = symbol
/anaconda/lib/python3.6/site-packages/pandas/core/generic.py in __getattr__(self, name)
2968 if name in self._info_axis:
2969 return self[name]
-> 2970 return object.__getattribute__(self, name)
2971
2972 def __setattr__(self, name, value):
AttributeError: 'DataFrame' object has no attribute 'time'
Python: 3.4
So for some reason the following code throws an error in python console.
But the append is working and I get the correct(replace process completed) values in the new list.
mobile = []
for col in ws.iter_cols():
for cell in col:
if cell.value == 'Mobile':
x=column_index_from_string(cell.column)
for row in ws.iter_rows(min_col = x, min_row = 2, max_col = x):
for cell in row:
mobile.append(cell.value)
mob_f = []
for i in mobile:
h = i
h = h.replace(" ","")
h = h.replace("+(91)-",",")
h = h.replace("+91","")
h = h.replace("-","")
mob_f.append(h)
Error:
Traceback (most recent call last):
File "", line 3, in
AttributeError: 'NoneType' object has no attribute 'replace'
This is the portion of the code that's causing trouble:
import pandas as pd
import re
df
df.columns = ['Campaigns', 'Impressions', 'Attempts', 'Spend']
Campaigns = df['Campaigns']
IDs = []
for c in Campaigns:
num = re.search(r'\d{6}',c).group()
IDs.append(num)
pieces = [df,pd.DataFrame(IDs)]
frame = pd.concat(pieces, axis=1, join='outer',ignore_index=False)
frame['ID'] = frame[0]
del frame[0]
frame
This is the error:
Error: 'NoneType' object has no attribute 'group'
When I try things individually in ipython everything works, for example:
in>> test = 'YP_WON2_SP8_115436'
in>> num = re.search(r'\d{6}',test)
in>> num.group()
out>> '115436'
I've tried splitting up the code as above and it still throws the same error.
Fixed the code:
df
df.columns = ['Campaigns', 'Impressions', 'Attempts', 'Spend']
Campaigns = df['Campaigns']
ID = []
for c in Campaigns:
m = re.search(r'\d{6}',c)
if m:
num = re.search(r'\d{6}',c).group()
ID.append(num)
else:
ID.append('No ID')
pieces = [df,pd.DataFrame(ID)]
frame = pd.concat(pieces, axis=1, join='outer',ignore_index=False)
frame['ID'] = frame[0]
del frame[0]
frame