Python: import calendar error gives unexpected result - python-3.x

Some other things are asked which is not in my code after execution
import calendar
y = int(input("Input the year : "))
m = int(input("Input the month : "))
print(calendar.month(y, m))
Filename I write it as calen.py
E:\pyprogs>python calen.py
Enter a string: df
fd
Traceback (most recent call last):
File "calen.py", line 1, in <module>
import calendar
File "F:\Anaconda\lib\calendar.py", line 10, in <module>
import locale as _locale
File "F:\Anaconda\lib\locale.py", line 180, in <module>
_percent_re = re.compile(r'%(?:\((?P<key>.*?)\))?'
AttributeError: module 're' has no attribute 'compile'
I expected the calendar to be printed.

Related

TypeError: float() argument must be a string or a number, not 'datetime.timedelta'

I want to make a plot with the data am fetching from the database, voltage(float), and time(time), I was getting the error now am stack. please help or is there a best way I can go about it.?
import matplotlib.pyplot as plt
import numpy as np
import serial as ser
import time
import datetime
import mysql.connector
my_connect = mysql.connector.connect(host="localhost", user="Kennedy", passwd="Kennerdol05071994", database="ecg_db", auth_plugin="mysql_native_password")
mycursor = my_connect.cursor()
voltage_container = []
time_container = []
def fetch_voltage():
pat_id = 1
query = "SELECT voltage, time FROM ecg_data_tbl where patient_id = 1 "
mycursor.execute(query)
result = mycursor .fetchall()
voltage, time = list(zip(*result))
for volts in voltage:
voltage_container.append(volts)
voltage_data = np.array(voltage_container)
for tim in time:
time_container.append(tim)
time_data = np.array(time_container)
plt.plot(time_data, voltage_data)
fetch_voltage()
I was told to convert them to arrays which I did but nothing is changing. The error am getting is:
Traceback (most recent call last):
File "C:\Users\Kennedy Mulenga\Desktop\Level 5\18136709_BIT_280_Arduino_ECG_Project\fetch_all.py", line 31, in <module>
fetch_voltage()
File "C:\Users\Kennedy Mulenga\Desktop\Level 5\18136709_BIT_280_Arduino_ECG_Project\fetch_all.py", line 28, in fetch_voltage
plt.plot(time_data, voltage_data)
File "C:\Users\Kennedy Mulenga\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\pyplot.py", line 3019, in plot
return gca().plot(
File "C:\Users\Kennedy Mulenga\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\axes\_axes.py", line 1607, in plot
self.add_line(line)
File "C:\Users\Kennedy Mulenga\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\axes\_base.py", line 2101, in add_line
self._update_line_limits(line)
File "C:\Users\Kennedy Mulenga\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\axes\_base.py", line 2123, in _update_line_limits
path = line.get_path()
File "C:\Users\Kennedy Mulenga\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\lines.py", line 1022, in get_path
self.recache()
File "C:\Users\Kennedy Mulenga\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\lines.py", line 663, in recache
x = _to_unmasked_float_array(xconv).ravel()
File "C:\Users\Kennedy Mulenga\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\cbook\__init__.py", line 1333, in _to_unmasked_float_array
return np.asarray(x, float)
TypeError: float() argument must be a string or a number, not 'datetime.timedelta'
Your time data is not a type matplotlib is familiar with so it's trying to convert it itself and it can't. Instead make it a type it can handle yourself.
A common choice, for example, would be
for tim in time:
time_container.append(tim.total_seconds())
time_data = np.array(time_container)
Now you are using the total number of seconds in your datetime.timedelta object (that is the result of your query). This is a float so matplotlib can plot it. If you don't want total seconds you can look at the docs for other options.
https://docs.python.org/3/library/datetime.html

Sqlite3 - pandas module 'time' has no attribute 'clock'

I want to turn my database into sqlite3 for pandas df
I'm using this piece of code:
con = sqlite3.connect('\path\db.db')
df = pd.read_sql('select * from db', con)
Trackback what I got:
Traceback (most recent call last):
df = pd.read_sql('select * from db', con)
File "PATH\pandas\io\sql.py", line 403, in read_sql
pandas_sql = pandasSQL_builder(con)
File "PATH\pandas\io\sql.py", line 578, in pandasSQL_builder
if _is_sqlalchemy_connectable(con):
File "PATH\pandas\io\sql.py", line 43, in _is_sqlalchemy_connectable
import sqlalchemy
File "PATHPython38-32\lib\site-packages\sqlalchemy\__init__.py", line 12, in <module>
from sqlalchemy.sql import (
File "PATHPython38-32\lib\site-packages\sqlalchemy\sql\__init__.py", line 7, in <module>
from sqlalchemy.sql.expression import (
File "PATHPython38-32\lib\site-packages\sqlalchemy\sql\expression.py", line 32, in <module>
from sqlalchemy import util, exc
File "PATHPython38-32\lib\site-packages\sqlalchemy\util\__init__.py", line 7, in <module>
from .compat import callable, cmp, reduce, defaultdict, py25_dict, \
File "PATHPython38-32\lib\site-packages\sqlalchemy\util\compat.py", line 202, in <module>
time_func = time.clock
AttributeError: module 'time' has no attribute 'clock'
Is there something wrong with this code? What is the reason for this error?
SQLALchemy 0.7.10 is really really old. Like 6.5 years old. It used time.clock which ...
:1: DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead

Why import of regular expressions falling a traceback error?

Having assignment "Extracting Data With Regular Expressions". For this I'm importing regex, but the code is not working. what is my mistake?
I checked the code without "import", it does work. Lines 2-7 are working. But it got a traceback error on "import re" line 1.
import re
fname = input('Enter file: ')
if len(fname) < 1 : fname = "sample.txt"
hand = open(fname)
hd = hand.read()
for line in hand:
line = line.rstrip()
nm = re.findall('[0-9]+',line)
print(nm)
C:\Users\Desktop\new>re.py
Enter file:
Traceback (most recent call last):
File "C:\Users\Desktop\new\re.py", line 1, in <module>
import re
File "C:\Users\Desktop\new\re.py", line 9, in <module>
[enter image description here][1]nm = re.findall('[0-9]+',line)
AttributeError: module 're' has no attribute 'findall'
Because you have called your file re.py, the import will actually import this file instead of the built-in module for regular expressions.
Just rename your file to something different and it should work as expected.

Pandas Series.strids deprecated, and pandas groupby error

Here are a few lines of code:
import pandas as pd
import numpy as np
from mlxtend.frequent_patterns import apriori
from mlxtend.frequent_patterns import association_rules
def encode_c(x):
if x <= 0:
return 0
if x >= 1:
return 1
return 0
def get_product_consequents():
all_transactions_df = get_dataframe()
basket = (all_transactions_df.groupby(['a', 'b'])['c']
.sum().unstack().reset_index().fillna(0)
.set_index('a'))
basket = basket.applymap(encode_c)
frequent_itemsets = apriori(basket, min_support=0.07, use_colnames=True)
rules = association_rules(frequent_itemsets, metric="lift",
min_threshold=1)
rules['antecedants_length'] = rules['antecedents'].str.len()
rules['consequents_length'] = rules['consequents'].str.len()
rules = rules[(rules['lift'] >= 4) & # 6
(rules['confidence'] >= 0.4)] # 0.8
rules = rules[(rules['antecedants_length'] == 1) &
(rules['consequents_length'] == 1)]
rules = (rules.groupby(['antecedants'])['consequents'])
IMAGE 1
IMAGE 2
When I DO: learning apriori from
rules["antecedant_len"] = rules["antecedents"].apply(lambda x: len(x))
I GET:
IMAGE 1
C:\Program Files\JetBrains\PyCharm 2018.1.4\helpers\pydev\_pydevd_bundle
\pydevd_resolver.py:71:
FutureWarning: Series.strides is deprecated
and will be removed in a future version
return getattr(var, attribute)
I was doing it from: mlxtend association_rules and apriori docs
As the error says: Series.strides are deprecated.
So how can I find the length of each frozenset in series? i.e. do same as above?
MAIN ERROR
IMAGE 2
rules = (rules.groupby(['antecedants'])['consequents'])
After I evaluate above line:
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm
2018.1.4\helpers\pydev\_pydevd_bundle\pydevd_vars.py", line 376, in
evaluate_expression compiled = compile(expression, '<string>', 'eval')
File "<string>", line 1
rules = (rules.groupby(['antecedants'])['consequents'])
^
SyntaxError: invalid syntax
-----WHY Syntax error, though works fine on JUPYTER NOTEBOOK?
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm
2018.1.4\helpers\pydev\_pydevd_bundle\pydevd_comm.py", line 1159, in do_it
result = pydevd_vars.evaluate_expression(self.thread_id, self.frame_id,
self.expression, self.doExec)
File "C:\Program Files\JetBrains\PyCharm
2018.1.4\helpers\pydev\_pydevd_bundle\pydevd_vars.py", line 378, in
evaluate_expression
Exec(expression, updated_globals, frame.f_locals)
File "C:\Program Files\JetBrains\PyCharm
2018.1.4\helpers\pydev\_pydevd_bundle\pydevd_exec2.py", line 3, in Exec
exec(exp, global_vars, local_vars)
File "<string>", line 1, in <module>
File "C:\ProjcetPath\venv\lib\site-
packages\pandas\core\generic.py", line 6659, in groupby
observed=observed, **kwargs)
File "C:\ProjcetPath\venv\lib\site-
packages\pandas\core\groupby\groupby.py", line 2152, in groupby
return klass(obj, by, **kwds)
File "C:\ProjcetPath\venv\lib\site-
packages\pandas\core\groupby\groupby.py", line 599, in __init__
mutated=self.mutated)
File "C:\ProjcetPath\venv\lib\site-
packages\pandas\core\groupby\groupby.py", line 3291, in _get_grouper
raise KeyError(gpr)
KeyError: 'antecedants'
--- At last it says key error, during handling syntax error key error occurred, For sure it is not key error as I can see column in sciView, also am able to access it this was as done in above code lines.
OTHER INFO: I am using Django as well.

pandas-datareade and AttributeError: NoneType object has no attribute 'fileno'

I tried the following code:
import pandas_datareader.data as web import datetime
start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2017, 10, 26)
f = web.DataReader("F", 'yahoo', start, end)
and got the following error:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
f.Close
File "C:\Python34\lib\idlelib\rpc.py", line 611, in displayhook
text = repr(value)
File "C:\Python34\lib\site-packages\pandas\core\base.py", line 72, in __repr__
return str(self)
File "C:\Python34\lib\site-packages\pandas\core\base.py", line 51, in __str__
return self.__unicode__()
File "C:\Python34\lib\site-packages\pandas\core\series.py", line 982, in __unicode__
width, height = get_terminal_size()
File "C:\Python34\lib\site-packages\pandas\io\formats\terminal.py", line 33, in get_terminal_size
return shutil.get_terminal_size()
File "C:\Python34\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 use Python 3.4 [wrong: 3.5] with pandas 0.2 when the error occured. The same code on Python 3.6 with pandas 0.2 runs without problems on another work station. Anybody any idea how I can fix the error.
I allready tried to uninstall and to reinstall pandas and pandas-datareader but it didn't helped.

Resources