Python dataframe_image results in SyntaxError: not a PNG file - python

Good day. I used to have a normally working code which exports styled dataframe as a PNG. For some reason now it doesn't work except for certain machines used by my fellow coworkers. I suspect iit is somehow relevant to the latest windows or Chrome updates but I am not sure.
Sample code:
import numpy as np
import pandas as pd
import dataframe_image as dfi
my_array = np.array([[11,22,33],[44,55,66]])
df = pd.DataFrame(my_array, columns = ['Column_A','Column_B','Column_C'])
df=df.style.set_properties(**{'background-color': 'black',
'color': 'white'})
display(df)
dfi.export(df, 'Test.png', table_conversion='chrome')
Received error:
Traceback (most recent call last):
File "C:\Users\Anato\anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3457, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "", line 13, in
dfi.export(df, 'Test.png', table_conversion='chrome')
File "C:\Users\Anato\anaconda3\lib\site-packages\dataframe_image_pandas_accessor.py", line 24, in export
dpi=None
File "C:\Users\Anato\anaconda3\lib\site-packages\dataframe_image_pandas_accessor.py", line 73, in _export
File "C:\Users\Anato\anaconda3\lib\site-packages\dataframe_image_screenshot.py", line 167, in run
max_crop = int(img.shape[1] * 0.15)
File "", line 40, in take_screenshot_override
img = mimage.imread(buffer)
File "C:\Users\Anato\anaconda3\lib\site-packages\matplotlib\image.py", line 1541, in imread
with img_open(fname) as image:
File "C:\Users\Anato\anaconda3\lib\site-packages\PIL\ImageFile.py", line 121, in init
self._open()
File "C:\Users\Anato\anaconda3\lib\site-packages\PIL\PngImagePlugin.py", line 677, in _open
raise SyntaxError("not a PNG file")
File "", line unknown
SyntaxError: not a PNG file
Searched the web and found no answer that could help. Tried udating packages and python itself. I believe it has to do with latest system updates but found no solution for over a week.

In my case the following worked:
Update windows to the latest version
Update conda

Related

Error creating Satellite images from THREDDS server after MetPy 0.12->1.1 upgrade

Upgraded MetPy to 1.1 and my ability to produce satellite images from a THREDDS server is no longer working. I isolated the part that is causing me issues.
Example:
#!/usr/bin/python3
import metpy
from siphon.catalog import TDSCatalog
cat_e = TDSCatalog('https://thredds.ucar.edu/thredds/catalog/satellite/goes/east/products/CloudAndMoistureImagery/FullDisk/Channel09/current/catalog.xml')
nc_e = cat_e.datasets[0].remote_access(use_xarray=True)
data_e = nc_e.metpy.parse_cf('Sectorized_CMI')
yields the following output/error
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/metpy/xarray.py", line 785, in _rebuild_coords
var = var.metpy.convert_coordinate_units(coord_name, 'meters')
File "/usr/local/lib/python3.6/dist-packages/metpy/xarray.py", line 190, in convert_coordinate_units
data=self._data_array[coord].metpy.unit_array.m_as(units)
File "/usr/local/lib/python3.6/dist-packages/pint/quantity.py", line 386, in m_as
return self.to(units).magnitude
File "/usr/local/lib/python3.6/dist-packages/pint/quantity.py", line 591, in to
magnitude = self._convert_magnitude_not_inplace(other, *contexts, **ctx_kwargs)
File "/usr/local/lib/python3.6/dist-packages/pint/quantity.py", line 540, in _convert_magnitude_not_inplace
return self._REGISTRY.convert(self._magnitude, self._units, other)
File "/usr/local/lib/python3.6/dist-packages/pint/registry.py", line 925, in convert
return self._convert(value, src, dst, inplace)
File "/usr/local/lib/python3.6/dist-packages/pint/registry.py", line 1762, in _convert
return super()._convert(value, src, dst, inplace)
File "/usr/local/lib/python3.6/dist-packages/pint/registry.py", line 1376, in _convert
return super()._convert(value, src, dst, inplace)
File "/usr/local/lib/python3.6/dist-packages/pint/registry.py", line 958, in _convert
raise DimensionalityError(src, dst, src_dim, dst_dim)
pint.errors.DimensionalityError: Cannot convert from 'microradian' (dimensionless) to 'meter' ([length])
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/data/home/met_scheduler/scripts/satellite/satellite_metpy11.py", line 8, in <module>
data_e = nc_e.metpy.parse_cf('Sectorized_CMI')
File "/usr/local/lib/python3.6/dist-packages/metpy/xarray.py", line 774, in parse_cf
var = self._rebuild_coords(var, crs)
File "/usr/local/lib/python3.6/dist-packages/metpy/xarray.py", line 797, in _rebuild_coords
var = var.assign_coords(coords={coord_name: new_coord_var})
File "/data/home/met_scheduler/.local/lib/python3.6/site-packages/xarray/core/common.py", line 349, in assign_coords
data.coords.update(results)
File "/data/home/met_scheduler/.local/lib/python3.6/site-packages/xarray/core/coordinates.py", line 90, in update
priority_arg=1, indexes=self.indexes)
File "/data/home/met_scheduler/.local/lib/python3.6/site-packages/xarray/core/merge.py", line 362, in merge_coords
expanded = expand_variable_dicts(aligned)
File "/data/home/met_scheduler/.local/lib/python3.6/site-packages/xarray/core/merge.py", line 222, in expand_variable_dicts
var = as_variable(var, name=name)
File "/data/home/met_scheduler/.local/lib/python3.6/site-packages/xarray/core/variable.py", line 96, in as_variable
"variable %r has invalid type %r" % (name, type(obj)))
TypeError: variable 'coords' has invalid type <class 'dict'>
I appreciate any thoughts on how to get around this.
Can you double check that your Python installation with MetPy is correct? I was able to run your code fine on my local install of MetPy 1.1.0 with Python 3.9. Also, your traceback shows Python 3.6 being used; MetPy 1.1.0 only supports Python >=3.7. You should not have been able to install MetPy 1.1.0 with that version of Python.
You can confirm the version of MetPy being used by adding the following to your script:
print(metpy.__version__)

How to raise index error in Pandas on a Windows machine?

I am using pandas_dedupe library. I get this error when I try to run on a Windows machine, but this same code runs fine on a Mac.
import pandas as pd
import pandas_dedupe as pdd
df=pd.read_csv('sample.csv')
df=pdd.dedupe_dataframe(df,['firstname','lastname','gender','zipcode','address'])
df.to_csv('sample_deduped.csv')
df=df[df['cluster id'].isnull() | ~df[df['cluster id'].notnull()].duplicated(subset='cluster id',keep='first')]
df.to_csv('sample_deuped_removed.csv')
Here are the logs in case you want to have a look:
Traceback (most recent call last):
File "C:/Users/vikas.mittal/Desktop/python projects/untitled2/deduplication.py", line 10, in <module>
df=pdd.dedupe_dataframe(df,['firstname','lastname','gender','zipcode','address'])
File "C:\Users\vikas.mittal\Desktop\python projects\untitled2\venv\lib\site-packages\pandas_dedupe\dedupe_dataframe.py", line 213, in dedupe_dataframe
sample_size)
File "C:\Users\vikas.mittal\Desktop\python projects\untitled2\venv\lib\site-packages\pandas_dedupe\dedupe_dataframe.py", line 72, in _train
dedupe.consoleLabel(deduper)
File "C:\Users\vikas.mittal\Desktop\python projects\untitled2\venv\lib\site-packages\dedupe\convenience.py", line 36, in consoleLabel
uncertain_pairs = deduper.uncertainPairs()
File "C:\Users\vikas.mittal\Desktop\python projects\untitled2\venv\lib\site-packages\dedupe\api.py", line 714, in uncertainPairs
return self.active_learner.pop()
File "C:\Users\vikas.mittal\Desktop\python projects\untitled2\venv\lib\site-packages\dedupe\labeler.py", line 323, in pop
raise IndexError("No more unlabeled examples to label")
IndexError: No more unlabeled examples to label
Process finished with exit code 1

How to use dates in the yahoo_fin Python Package

I recently installed yahoo_fin and I tired the following example:
get_calls('NFLX' ')
It worked. I then tired the following:
get_calls('NFLX', '11/8/2019')
It failed. Here is what I got:
get_calls('NFLX', '11/8/2019')
Traceback (most recent call last):
File "", line 1, in
get_calls('NFLX', '11/8/2019')
File "C:\Users\rsher\Anaconda3\lib\site-packages\yahoo_fin\options.py", line 48, in get_calls
options_chain = get_options_chain(ticker, date)
File "C:\Users\rsher\Anaconda3\lib\site-packages\yahoo_fin\options.py", line 32, in get_options_chain
tables = pd.read_html(site)
File "C:\Users\rsher\Anaconda3\lib\site-packages\pandas\io\html.py", line 906, in read_html
keep_default_na=keep_default_na)
File "C:\Users\rsher\Anaconda3\lib\site-packages\pandas\io\html.py", line 743, in _parse
raise_with_traceback(retained)
File "C:\Users\rsher\Anaconda3\lib\site-packages\pandas\compat__init__.py", line 344, in raise_with_traceback
raise exc.with_traceback(traceback)
ValueError: No tables found
I am using version 3.6.3 of Python and I am also using Spyder.
Am I doing something wrong? Do you think I have found a bug?
I updated my version of yahoo_fin. Not really sure it was out of date. I now get the following error messages when I run the command: get_calls("nflx", "1/31/20")
Traceback (most recent call last):
File "", line 1, in
get_calls("nflx", "1/31/20")
File "C:\Users\rsher\Anaconda3\lib\site-packages\yahoo_fin\options.py", line 48, in get_calls
options_chain = get_options_chain(ticker, date)
File "C:\Users\rsher\Anaconda3\lib\site-packages\yahoo_fin\options.py", line 32, in get_options_chain
tables = pd.read_html(site)
File "C:\Users\rsher\Anaconda3\lib\site-packages\pandas\io\html.py", line 906, in read_html
keep_default_na=keep_default_na)
File "C:\Users\rsher\Anaconda3\lib\site-packages\pandas\io\html.py", line 743, in _parse
raise_with_traceback(retained)
File "C:\Users\rsher\Anaconda3\lib\site-packages\pandas\compat__init__.py", line 344, in raise_with_traceback
raise exc.with_traceback(traceback)
ValueError: No tables found
It should work the way you have it.
from yahoo_fin.options import get_calls
get_calls("nflx", "1/31/20")
Are you using the most recent version of yahoo_fin? It should be (as of this writing) version 0.8.4. Another possible issue is that there could have been a problem with Yahoo Finance's page for that option chain at that particular time.

Pyglet can't load .wav file

Env:
Ubuntu 18.04
Python 3.6.6
pyglet 1.3.2
Issue:
Based on documentation of pyglet I try to run following code:
import pyglet
pyglet.options["audio"] = ("openal", "pulse", "directsound", "silent")
explosion = pyglet.media.load('explosion.wav')
But following exceptions occured:
1) if file was converted by ffmpeg -i input.mp3 output.wav
Traceback (most recent call last):
File "<path_to_dir>/test_sound.py", line 3, in <module>
explosion = pyglet.media.load('zxc.wav', streaming=False)
File "<path_to_env>lib/python3.6/site-packages/pyglet/media/sources/loader.py", line 63, in load
source = get_source_loader().load(filename, file)
File "<path_to_env>lib/python3.6/site-packages/pyglet/media/sources/loader.py", line 84, in load
return WaveSource(filename, file)
File "<path_to_env>lib/python3.6/site-packages/pyglet/media/sources/riff.py", line 197, in __init__
raise WAVEFormatException('Not a WAVE file')
pyglet.media.sources.riff.WAVEFormatException: Not a WAVE file
2) or this for several .wav from internet
Traceback (most recent call last):
File "<path_to_dir>//test_sound.py", line 3, in <module>
explosion = pyglet.media.load('explosion.wav', streaming=False)
File "<path_to_env>lib/python3.6/site-packages/pyglet/media/sources/loader.py", line 63, in load
source = get_source_loader().load(filename, file)
File "<path_to_env>lib/python3.6/site-packages/pyglet/media/sources/loader.py", line 84, in load
return WaveSource(filename, file)
File "<path_to_env>lib/python3.6/site-packages/pyglet/media/sources/riff.py", line 192, in __init__
format = wave_form.get_format_chunk()
File "<path_to_env>lib/python3.6/site-packages/pyglet/media/sources/riff.py", line 172, in get_format_chunk
for chunk in self.get_chunks():
File "<path_to_env>lib/python3.6/site-packages/pyglet/media/sources/riff.py", line 108, in get_chunks
chunk = cls(self.file, name, length, offset)
File "<path_to_env>lib/python3.6/site-packages/pyglet/media/sources/riff.py", line 153, in __init__
raise RIFFFormatException('Size of format chunk is incorrect.')
pyglet.media.sources.riff.RIFFFormatException: Size of format chunk is incorrect.
Question:
How to run .wav files via pyglet correctly?
Like in the example, it is probably either an issue with openal or the wav-files. Are the procedural sounds playing correctly, e.g.:
from pyglet.media.sources.procedural import Sine
sine = Sine(duration=1, frequency=500,
sample_size=16, sample_rate=44100)
pyglet.media.StaticSource(sine).play()
and can you share an offending wav-file? I just ran a test on Linux Mint 19, Python 3.7.1 and pyglet 1.3.2 with https://github.com/pyreiz/pyreiz/blob/master/reiz/media/wav/ding.wav and it runs fine.

Basic ExcelFile read not working

I have just downloaded Python3.5 and have been trying to do a simple task (open an Excel file and remove the first three rows and various columns from the file) for several hours now with no success.
The lastest issue is happening when I try to open the file.
This is the only code:
import pandas as pd
df = pd.ExcelFile("January2016.xlsx")
I get the following error no matter what read option I use with pandas.
Traceback (most recent call last):
File "C:\Python35\lib\site-packages\IPython\core\interactiveshell.py", line 2847, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-25-503f922e97e7>", line 1, in <module>
df = pd.ExcelFile("January2016.xlsx")
File "C:\Python35\lib\site-packages\pandas\io\excel.py", line 257, in __init__
self.book = xlrd.open_workbook(io)
File "C:\Python35\lib\site-packages\xlrd\__init__.py", line 422, in open_workbook
ragged_rows=ragged_rows,
File "C:\Python35\lib\site-packages\xlrd\xlsx.py", line 833, in open_workbook_2007_xml
x12sheet.process_stream(zflo, heading)
File "C:\Python35\lib\site-packages\xlrd\xlsx.py", line 548, in own_process_stream
self_do_row(elem)
File "C:\Python35\lib\site-packages\xlrd\xlsx.py", line 745, in do_row
value = error_code_from_text[tvalue]
KeyError: None
Please help!
You need to either use pd.ExcelFile.parse(...) or pd.read_excel. pd.ExcelFile isn't a method that parses excel files, you need the parse part, too.
I know this thread is 3 years old. Anyway hope this might help someone.
I came across this recently. I think the problem is caused by a image in the file. When I run the code in windows environment it works well. But when I run the code in ubuntu environment it gives a Traceback error.

Categories