Y = churn.iloc[:, 18].values - python-3.x

Trying to import my dataset(18 columns counting from 0) i got this error:
File "C:/Users/ASUS/PycharmProjects/PA/BestAcc.py", line 23, in
Y = churn.iloc[:, 18].values File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 1472, in
getitem
return self._getitem_tuple(key) File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 2013, in
_getitem_tuple
self._has_valid_tuple(tup) File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 222, in
_has_valid_tuple
self._validate_key(k, i) File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 1957, in
_validate_key
self._validate_integer(key, axis) File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 2009, in
_validate_integer
raise IndexError("single positional indexer is out-of-bounds") IndexError: single positional indexer is out-of-bounds
Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
churn = pd.read_csv("HR.csv")
#import colums except the first one in the dataset
X = churn.iloc[:, 1:18].values
Y = churn.iloc[:, 18].values

iloc has been deprecated in later versions of pandas - I would suggest using loc instead -
X = churn.loc[:, churn.columns[1:18]]
Y = churn.loc[:, churn.columns[18]]

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

tensorflow 2 guide Consuming sets of files throws slice index out of bounds

trying the code (please see below) from consuming sets of files throws a slice index -1 of dimension 0 out of bounds (please see output below).
has anyone gotten this code to work?
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import pathlib
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
def process_path(file_path):
label = tf.strings.split(file_path, '/')[-2]
return tf.io.read_file(file_path), label
flowers_root = tf.keras.utils.get_file(
'flower_photos',
'https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz',
untar=True)
flowers_root = pathlib.Path(flowers_root)
for item in flowers_root.glob("*"):
print(item.name)
list_ds = tf.data.Dataset.list_files(str(flowers_root/'*/*'))
for f in list_ds.take(5):
print(f.numpy())
labeled_ds = list_ds.map(process_path)
for image_raw, label_text in labeled_ds.take(1): #this line throws
print(repr(image_raw.numpy()[:100]))
print()
print(label_text.numpy())
$ py consume.py
daisy
dandelion
LICENSE.txt
roses
sunflowers
tulips
b'C:\\Users\\ray\\.keras\\datasets\\flower_photos\\dandelion\\5024965767_230f140d60_n.jpg'
b'C:\\Users\\ray\\.keras\\datasets\\flower_photos\\dandelion\\6012046444_fd80afb63a_n.jpg'
b'C:\\Users\\ray\\.keras\\datasets\\flower_photos\\roses\\2677417735_a697052d2d_n.jpg'
b'C:\\Users\\ray\\.keras\\datasets\\flower_photos\\tulips\\8677713853_1312f65e71.jpg'
b'C:\\Users\\ray\\.keras\\datasets\\flower_photos\\tulips\\14235021006_dd001ea8ed_n.jpg'
2019-11-16 18:06:05.468670: W tensorflow/core/framework/op_kernel.cc:1622] OP_REQUIRES failed at strided_slice_op.cc:108 : Invalid argument: slice index -1 of dimension 0 out of bounds.
2019-11-16 18:06:05.481203: W tensorflow/core/framework/op_kernel.cc:1622] OP_REQUIRES failed at iterator_ops.cc:929 : Invalid argument: {{function_node __inference_Dataset_map_process_path_106}} slice index -1 of dimension 0 out of bounds.
[[{{node strided_slice}}]]
Traceback (most recent call last):
File "consume.py", line 21, in <module>
for image_raw, label_text in labeled_ds.take(1):
File "d:\Anaconda3\lib\site-packages\tensorflow_core\python\data\ops\iterator_ops.py", line 622, in __next__
return self.next()
File "d:\Anaconda3\lib\site-packages\tensorflow_core\python\data\ops\iterator_ops.py", line 666, in next
return self._next_internal()
File "d:\Anaconda3\lib\site-packages\tensorflow_core\python\data\ops\iterator_ops.py", line 651, in _next_internal
output_shapes=self._flat_output_shapes)
File "d:\Anaconda3\lib\site-packages\tensorflow_core\python\ops\gen_dataset_ops.py", line 2672, in iterator_get_next_sync
_six.raise_from(_core._status_to_exception(e.code, message), None)
File "<string>", line 3, in raise_from
tensorflow.python.framework.errors_impl.InvalidArgumentError: {{function_node __inference_Dataset_map_process_path_106}} slice index -1 of dimension 0 out of bounds.
[[{{node strided_slice}}]] [Op:IteratorGetNextSync]
I think this is because you are running on Windows. Try switch the following line
label = tf.strings.split(file_path, '/')[-2]
to
label = tf.strings.split(file_path, '\\')[-2]

matplotlib is now giving an 'Unknown property' AttributeError since update to Python 3:

I am using astroplan to set up some astronomical observations. Previously, when I ran my code using Python 2.7, it plotted the target on the sky properly. Now, I have moved to Python 3.7 and I get an AttributError on the same code.
I took my larger code and stripped out everything that did not seem to trigger the error. Here below is code that will generate the complaint.
from astroplan import Observer, FixedTarget
import astropy.units as u
from astropy.time import Time
import matplotlib.pyplot as plt
from astroplan.plots import plot_sky
import numpy as np
time = Time('2015-06-16 12:00:00')
subaru = Observer.at_site('subaru')
vega = FixedTarget.from_name('Vega')
sunset_tonight = subaru.sun_set_time(time, which='nearest')
vega_rise = subaru.target_rise_time(time, vega) + 5*u.minute
start = np.max([sunset_tonight, vega_rise])
plot_sky(vega, subaru, start)
plt.show()
Expected result was a simple plot of the target, in this case, the star Vega, on the sky as seen by the Subaru telescope in Hawaii. The astroplan docs give a tutorial that shows how it was to look at the very end of this page:
https://astroplan.readthedocs.io/en/latest/tutorials/summer_triangle.html
Instead, I now get the following error:
Traceback (most recent call last):
File "plot_sky.py", line 16, in <module>
plot_sky(vega, subaru, start)
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/astropy/utils/decorators.py", line 842, in plot_sky
func = make_function_with_signature(func, name=name, **wrapped_args)
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/astropy/units/decorators.py", line 222, in wrapper
return_ = wrapped_function(*func_args, **func_kwargs)
File "/local/data/fugussd/rkbarry/.local/lib/python3.7/site-packages/astroplan/plots/sky.py", line 216, in plot_sky
ax.set_thetagrids(range(0, 360, 45), theta_labels, frac=1.2)
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/matplotlib/projections/polar.py", line 1268, in set_thetagrids
t.update(kwargs)
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/matplotlib/text.py", line 187, in update
super().update(kwargs)
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/matplotlib/artist.py", line 916, in update
ret = [_update_property(self, k, v) for k, v in props.items()]
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/matplotlib/artist.py", line 916, in <listcomp>
ret = [_update_property(self, k, v) for k, v in props.items()]
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/matplotlib/artist.py", line 912, in _update_property
raise AttributeError('Unknown property %s' % k)
AttributeError: Unknown property frac

Python Error (ValueError: _getfullpathname: embedded null character)

I don't know How to fix it please help, I have tried everything mentioned in the post Error on import matplotlib.pyplot (on Anaconda3 for Windows 10 Home 64-bit PC) but no luck. I'm a newbie to the python and am self learning specific details would greatly be appreciated.
Console:
Traceback (most recent call last):
from matplotlib import pyplot
File "C:\Users\...\lib\site-packages\matplotlib\pyplot.py", line 29, in <module>
import matplotlib.colorbar
File "C:\Users\...\lib\site-packages\matplotlib\colorbar.py", line 34, in <module>
import matplotlib.collections as collections
File "C:\Users\...\lib\site-packages\matplotlib\collections.py", line 27, in <module>
import matplotlib.backend_bases as backend_bases
File "C:\Users\...\lib\site-packages\matplotlib\backend_bases.py", line 62, in <module>
import matplotlib.textpath as textpath
File "C:\Users\...\lib\site-packages\matplotlib\textpath.py", line 15, in <module>
import matplotlib.font_manager as font_manager
File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 1421, in <module>
_rebuild()
File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 1406, in _rebuild
fontManager = FontManager()
File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 1044, in __init__
self.ttffiles = findSystemFonts(paths) + findSystemFonts()
File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 313, in findSystemFonts
for f in win32InstalledFonts(fontdir):
File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 231, in win32InstalledFonts
direc = os.path.abspath(direc).lower()
File "C:\Users\...\lib\ntpath.py", line 535, in abspath
path = _getfullpathname(path)
ValueError: _getfullpathname: embedded null character
Python:
importing libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#importing dataset
dataset = pd.read_csv('Position_Salaries.csv')
x = dataset.iloc[:,1:2].values
y = dataset.iloc[:,2].values
#Linear Regression
from sklearn.linear_model import LinearRegression
reg_lin = LinearRegression()
reg_lin = reg_lin.fit(x,y)
#ploynomial Linear Regression
from sklearn.preprocessing import PolynomialFeatures
reg_poly = PolynomialFeatures(degree = 3)
x_poly = reg_poly.fit_transform(x)
reg_poly.fit(x_poly,y)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(x_poly,y)
#Visualizing Linear Regression results
plt.scatter(x,y,color = 'red')
plt.plot(x,reg_lin.predict(x), color = 'blue')
plt.title('Truth vs. Bluff (Linear Reg)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()
#Visualizing Polynomial Regression results
plt.scatter(x,y,color = 'red')
plt.plot(x,lin_reg_2.predict(reg_poly.fit_transform(x)), color = 'blue')
plt.title('Truth vs. Bluff (Linear Reg)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()
To find this in font_manager py:
direc = os.path.abspath(direc).lower()
change it into:
direc = direc.split('\0', 1)[0]
and save to apply in your file.
I don't think you applied the patch in Error on import matplotlib.pyplot (on Anaconda3 for Windows 10 Home 64-bit PC) correctly: if you had, there shouldn't be a mention of direc = os.path.abspath(direc).lower() in your error stack, since the patch removed it.
To be clear, here is the entire win32InstalledFonts() method in C:\Anaconda\envs\py35\Lib\site-packages\matplotlib\font_manager.py (or wherever Anaconda is installed) after the patch is applied, with matplotlib 2.0.0:
def win32InstalledFonts(directory=None, fontext='ttf'):
"""
Search for fonts in the specified font directory, or use the
system directories if none given. A list of TrueType font
filenames are returned by default, or AFM fonts if *fontext* ==
'afm'.
"""
from six.moves import winreg
if directory is None:
directory = win32FontDirectory()
fontext = get_fontext_synonyms(fontext)
key, items = None, {}
for fontdir in MSFontDirectories:
try:
local = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, fontdir)
except OSError:
continue
if not local:
return list_fonts(directory, fontext)
try:
for j in range(winreg.QueryInfoKey(local)[1]):
try:
''' Patch fixing [Error on import matplotlib.pyplot (on Anaconda3 for Windows 10 Home 64-bit PC)](https://stackoverflow.com/a/34007642/395857)
key, direc, any = winreg.EnumValue( local, j)
if not is_string_like(direc):
continue
if not os.path.dirname(direc):
direc = os.path.join(directory, direc)
direc = os.path.abspath(direc).lower()
'''
key, direc, any = winreg.EnumValue( local, j)
if not is_string_like(direc):
continue
if not os.path.dirname(direc):
direc = os.path.join(directory, direc)
direc = direc.split('\0', 1)[0]
if os.path.splitext(direc)[1][1:] in fontext:
items[direc] = 1
except EnvironmentError:
continue
except WindowsError:
continue
except MemoryError:
continue
return list(six.iterkeys(items))
finally:
winreg.CloseKey(local)
return None
The actual cause of the issue appears to be in os.path.abspath(). A better solution might be to edit <python dir>\Lib\ntpaths.py as detailed in Error on import matplotlib.pyplot (on Anaconda3 for Windows 10 Home 64-bit PC)
Basically, add a ValueError: exception handler to the Windows version of the abspath() function. This is lower down on the call stack and could save you from encountering this issue in other places.

Python 2.7 Unrecognized Character G in format string during runtime

I have Python 2.7 Win 32 and have installed Matplotlib, Numpy, PyParsing, Dateutil. In IDLE I place in the code:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
import numpy as np
def graphRawFX () :
date=mdates.strpdate2num('%Y%m%d%H%M%S')
bid,ask = np.loadtxt,unpack=True,('GPBUSD1d.txt')
delimiter=',',
converters={0:mdates.strpdate2num('%Y%m%d%H%M%S') }
fig = plt.figure(figsize=(10,7))
ax1 = plt.subplot2grid((40,40), (0,0), rowspan=40, colspan=40)
ax1.plot(date,bid)
ax1.plot(date,ask)
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
plt.grid(True)
plt.show()
I then proceed to enter:
rawGraphFX()
This results into the error below:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
graphRawFX()
File "C:/Users/Emanuel/Desktop/graph", line 16, in graphRawFX
ax1.plot(date,ask)
File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 4137, in plot
for line in self._get_lines(*args, **kwargs):
File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 317, in _grab_next_args
for seg in self._plot_args(remaining, kwargs):
File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 276, in _plot_args
linestyle, marker, color = _process_plot_format(tup[-1])
File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 129, in _process_plot_format
'Unrecognized character %c in format string' % c)
ValueError: Unrecognized character G in format string
>>>
This is probably easy to fix but I need help since I'm getting frustrated over this.
There are at least two issues with these two lines:
date=mdates.strpdate2num('%Y%m%d%H%M%S')
bid,ask = np.loadtxt,unpack=True,('GPBUSD1d.txt')
The first of these lines sets date to a class instance that would convert strings to matplotlib style dates. However, you never supply the dates. You need to come up with date strings from somewhere and apply this function to them.
The second line of these lines makes two assignments. It first assigns np.loadtxt to True and unpack to 'GPBUSD1d.txt'. It consequently assigns bid to True and ask to 'GPBUSD1d.txt'. It is the latter that causes the Unrecognized character error when matplotlib tries to interpret the G in 'GPBUSD1d.txt' as some kind of format instruction. You probably intended something like:
bid, ask = np.loadtxt('GPBUSD1d.txt', unpack=True)
This would call the function np.loadtxt which would load the file GPBUSD1d.txt' and transpose ("unpack") it.

Resources