I know this might be a very simple problem to solve, but I have been googling all day and cannot make it work. Please be patient with me - I just started working with Python.
I have a very simple code, that I can execute well in Jupyter, but it does not work in PyCharm:
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import pandas as pd
import numpy
y = pd.read_csv('data_all.csv')
df = y.iloc[:, 0:10]
print(df)
g = sns.PairGrid(df, hue='TP_PSP')
g = g.map(plt.scatter)
g = g.map_diag(plt.hist)
g = g.map_offdiag(plt.scatter)
g = g.add_legend()
I receive the following error:
Traceback (most recent call last):
File "C:/Users/lukas/PycharmProjects/untitled/mtth-matplot.py", line 18, in <module>
g = g.map_diag(plt.hist)
File "C:\Users\lukas\PycharmProjects\untitled\venv\lib\site-packages\seaborn\axisgrid.py", line 1399, in map_diag
func(data_k, label=label_k, color=color, **kwargs)
File "C:\Users\lukas\PycharmProjects\untitled\venv\lib\site-packages\matplotlib\pyplot.py", line 3132, in hist
stacked=stacked, normed=normed, data=data, **kwargs)
File "C:\Users\lukas\PycharmProjects\untitled\venv\lib\site-packages\matplotlib\__init__.py", line 1855, in inner
return func(ax, *args, **kwargs)
File "C:\Users\lukas\PycharmProjects\untitled\venv\lib\site-packages\matplotlib\axes\_axes.py", line 6713, in hist
labels = [six.text_type(lab) for lab in label]
TypeError: 'numpy.int64' object is not iterable
I have all packages installed and the interpreter works for "normal" python code. I am sorry posting such a trivial problem, but I cannot find a solution on the web that works for me. I am so grateful every hint to make it work.
Thanks in advance and best regards
LGR
This worked. I was facing a similar problem. Changed the Python Interpreter from 2.7 to 3.8 by clicking in the lower left portion of the Pycharm screen where it shows the interpreter being used. Code worked flawlessly.
Related
from geopy.geocoders import ArcGIS
from arcgis.geocoding import reverse_geocode
arcgis = ArcGIS()
results = reverse_geocode(location={"x": 103.876722, "y": 1.3330736})
print(results)
When I run this script in python, I get the following error.
Traceback (most recent call last):
File "C:\Users\18102\RentScraping\newMarketRequests.py", line 22, in <module>
results = reverse_geocode(location={"x": 103.876722, "y": 1.3330736})
File "C:\Users\18102\AppData\Roaming\Python\Python310\site-packages\arcgis\geocoding\_functions.py", line 1457, in reverse_geocode
geocoder = arcgis.env.active_gis._tools.geocoders[0]
AttributeError: 'NoneType' object has no attribute '_tools'
I pip installed the arcgis library, which I have used before for geocoding on a different project, but the reverse geocoding isn't working. I saw some documentation that had a few variations on how to provide the location parameter. I also tried reverse_geocode([103.876722, 1.3330736]) and got the same result. I think there might be something that got updated and the documentation I'm referencing is out of date. Any advice?
I'm a new learner in data science. I havent find out why I got an attribute error. I used python 3.8.3 in Visual Studio Code. I installed Pandas in terminal (pip install Pandas). I dont know what the problem is. Any help will be appreciated.
import pandas as pd
df=pd.DataFrame()
print(df)
All I did was to create an empty dataframe. And I got that:
Traceback (most recent call last):
File "c:/Users/Fatma Elik/Documents/VS Code/BTK/Pandas_dataframe.py", line 20, in <module>
import pandas as pd
File "C:\Users\Fatma Elik\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\__init__.py", line 180, in <module>
import pandas.testing
File "C:\Users\Fatma Elik\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\testing.py", line 5, in <module>
from pandas._testing import (
File "C:\Users\Fatma Elik\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\_testing.py", line 404, in <module>
RANDS_CHARS = np.array(list(string.ascii_letters + string.digits), dtype=(np.str_, 1))
AttributeError: module 'string' has no attribute 'ascii_letters'
Secondly I tried this instead and I got an attribute error again:
import pandas as pd
s1=pd.Series([3,2,0,1])
s2=pd.Series([0,3,7,2])
data=dict(apples=s1,oranges=s2)
df=pd.DataFrame(data)
print(df)
I did Ctrl+Click on string and I find that I already created a py file before. Because I searched on file search engine Windows 10 before, I couldnt have found it. Another simple mistake again :)
It's a little weird, the "string" module is a part of the standard library. Could you try this code?
from string import ascii_letters
print(ascii_letters)
Check it works or not, if it doesn't work, can you enter into this file:
"C:\Users\Fatma Elik\AppData\Local\Programs\Python\Python38-32\lib\string.py", and can you find:
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_letters = ascii_lowercase + ascii_uppercase
It should be located from line 25 to 27. If you can't find it, you should try to upgrade your python or reinstall it.
import numpy as np
import matplotlib.pyplot as plt
def main():
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
if __name__ == '__main__':
main()
Traceback (most recent call last):
File
"/Users/tim/workspace/Python/MachineLearn/test.py", line 2, in <module>
import matplotlib.pyplot as plt
File "/usr/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 115, in <module>
_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
File "/usr/local/lib/python2.7/site-packages/matplotlib/backends/__init__.py", line 63, in pylab_setup
[backend_name], 0)
File "/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend/backend_interagg.py", line 11, in <module>
from datalore.display import display
File "/Applications/PyCharm.app/Contents/helpers/pycharm_display/datalore/display/__init__.py", line 1, in <module>
from .display_ import *
File "/Applications/PyCharm.app/Contents/helpers/pycharm_display/datalore/display/display_.py", line 5, in <module>
from urllib.parse import urlencode
ImportError: No module named parse
Process finished with exit code 1
=================
Python: 2.7.16
PyCharm Professional: 2019.2
=================
btw, the code run in console mode is work
Simple answer: disable "show plots in scientific window" (Settings -> Tools -> Python Scientific) or downgrade the PyCharm or move your project to python3
Remember to add plt.show() in your code.
A little more complicated. You need to write own importing hooks to find that urllib.parse and urllib.request (next line in display_.py file are requested. More you can read here https://xion.org.pl/2012/05/06/hacking-python-imports/
(i'm not enough familiar with python 2 import system to write it)
For python 2 use
from urlparse import urlparse
If you need to write code which is Python2 and Python3 compatible you can use the following import
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
In your PyCharm project:
press Ctrl+Alt+s to open the settings
on the left column, select Project Interpreter
on the top right there is a list of python binaries found on your system, pick the right one
eventually click the + button to install additional python modules, in your case, it is parse module is missing so install that one
As mentioned by #Grzegorz Bokota, the problem is coming from the "scientific view mode" of PyCharm. This mode allows to visualise graphs and is thus calling matplotlib, and probably an incompatible version of it if you are using Python 2. This bug has been identified here and it seems that we just have to wait for the next release to get it solved.
as I am trying to print financial data:
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
import numpy as np
style.use('ggplot')
start=dt.datetime(2000,1,1)
end=dt.datetime(2016,12,31)
df= web.DataReader('ERIE', 'google', start, end)
print(df.head())
I get the error that df does not exist, or more specifically:
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
print(df.head(5))
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\frame.py", line 582, in __unicode__
width, _ = console.get_console_size()
File "C:\Python34\lib\site-packages\pandas\io\formats\console.py", line 77, in get_console_size
terminal_width, terminal_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 have no clue how to fix this, as this code seems to be working with everyone else who is trying it. I am just a beginner, so any help would be really appreciated.
Thank you!
Greetings, Tristan
It is known bug in shutil library:
https://bugs.python.org/issue24920
https://bugs.python.org/issue24966
It seems, you should change the way you started you code (from GUI or from shell and similar)
This is not a full solution, but at least a workaround.
You can use shutil's get_terminal_size() instead. There's also a backport available for python 2.
I faced the same problem with the code below:
import pandas as pd
dict = {
"country" :["Brazil", "Russia", "India", "China", "South Africa"],
"capital" :["Brasilia", "Moscow", "New Delhi", "Beijing", "Pretoria"],
"area" : [8.516, 17.10, 3.286, 9.597, 1.221],
"population" : [200.4, 143.5, 1252, 1357, 52.98] }
brics = pd.DataFrame(dict)
brics
An easy hack would be to shift your work to the Python shell, instead of IDLE (in my case, working on IDLE was the problem, but this same code ran perfectly on the Python Shell)
In my case, I've used a screen session in the terminal to start up spyder IDE for python. I've accidentally terminated the screen session, but spyder kept working with this error. After I restarted spyder in a new screen session, the error disappeared.
I am trying to run a simple linear regression (using rpy2 from Python) and encountered a strangely worded error when running the script below:
from numpy import array, rec
from numpy.random import normal as nprandom
from rpy2.robjects import numpy2ri, r
foo = array(range(10))
bar = foo + nprandom(0,1,10)
d = rec.fromarrays([foo, bar], names=('foo','bar'))
fit = r.lm('bar ~ foo', data=d)
print fit.rx2('coefficients')
here is the console output:
>>> from numpy import array, rec
>>> from numpy.random import normal as nprandom
>>> from rpy2.robjects import numpy2ri, r
>>>
>>> foo = array(range(10))
>>> bar = foo + nprandom(0,1,10)
>>>
>>> d = rec.fromarrays([foo, bar], names=('foo','bar'))
>>> fit = r.lm('bar ~ foo', data=d)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/rpy2/robjects/functions.py", line 82, in __call__
return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/rpy2/robjects/functions.py", line 33, in __call__
new_kwargs[k] = conversion.py2ri(v)
File "/usr/local/lib/python2.6/dist-packages/rpy2/robjects/__init__.py", line 134, in default_py2ri
raise(ValueError("Nothing can be done for the type %s at the moment." %(type(o))))
ValueError: Nothing can be done for the type <class 'numpy.core.records.recarray'> at the moment.
>>> print fit.rx2('coefficients')
I am running Python 2.6.5 and have numpy version 1.6.1
Does any one know what is causing this error?
You need to add:
rpy2.robjects.activate()
after importing numpy2ri. This SO post references the rpy2 documentation:
That import alone is sufficient to switch an automatic conversion of
numpy objects into rpy2 objects.
Why make this an optional import, while it could have been included in
the function py2ri() (as done in the original patch submitted for that
function) ?
Although both are valid and reasonable options, the design decision
was taken in order to decouple rpy2 from numpy the most, and do not
assume that having numpy installed automatically meant that a
programmer wanted to use it.
Hope this solves your problem.