content
stringlengths 85
101k
| title
stringlengths 0
150
| question
stringlengths 15
48k
| answers
list | answers_scores
list | non_answers
list | non_answers_scores
list | tags
list | name
stringlengths 35
137
|
---|---|---|---|---|---|---|---|---|
Q:
Max string recursion exceeded when using str.format_map()
I am using str.format_map to format some strings but I encounter a problem when this string contains quotes, even escaped. Here is the code:
class __FormatDict(dict):
def __missing__(self, key):
return '{' + key + '}'
def format_dict(node, template_values):
template_values = __FormatDict(template_values)
for key, item in node.items():
if isinstance(item, str):
node[key] = item.format_map(template_values)
For reqular strings (that do not include brackets or quotes) it works, however for strings like "{\"libraries\":[{\"file\": \"bonjour.so\", \"modules\":[{\"name\": \"hello\"}]}]}" it crashes with the message ValueError: Max string recursion exceeded.
Escaping the quotes using json.dumps(item) before formatting it does not solve the issue. What should be done to fix this problem? I am modifying strings I get from JSON files and I would prefer to fix the Python code instead of updating the JSON documents I use.
A:
You can't use your __missing__ trick on JSON data. There are multiple problems. That's because the text within {...} replacement fields are not just treated as strings. Take a look at the syntax grammar:
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name ::= arg_name ("." attribute_name | "[" element_index "]")*
Within a replacement field, !... and :... have meaning too! What goes into those sections has strict limits as well.
The recursion error comes from the multiple nested {...} placeholders inside placeholders inside placeholders; str.format() and str.format_map() can't support a large number of levels of nesting:
>>> '{foo:{baz: {ham}}}'.format_map({'foo': 'bar', 'baz': 's', 'ham': 's'})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Max string recursion exceeded
but there are other problems here:
The : colon denotes a formatting specification, which is then passed to the object (key) from the part before the :. You'd have to give your __missing__ return values a wrapper object with __format__ method if you wanted to recover those.
Field names with . or [...] in them have special meaning too; "bonjour.so" will be parsed as the "bonjour key, with a so attribute. Ditto for [...] in the field name, but for item lookups.
Those last two can be approached by returning a wrapper object with __format__ and __getitem__ and __getattr__ methods, but only in limited cases:
>>> class FormatWrapper:
... def __init__(self, v):
... self.v = v
... def __format__(self, spec):
... return '{{{}{}}}'.format(self.v, (':' + spec) if spec else '')
... def __getitem__(self, key):
... return FormatWrapper('{}[{}]'.format(self.v, key))
... def __getattr__(self, attr):
... return FormatWrapper('{}.{}'.format(self.v, attr))
...
>>> class MissingDict(dict):
... def __missing__(self, key):
... return FormatWrapper(key)
...
>>> '{"foo.com": "bar[baz]", "ham": "eggs"}'.format_map(MissingDict())
'{"foo.com": "bar[baz]", "ham": "eggs"}'
>>> '{"foo .com": "bar [ baz ]", "ham": "eggs"}'.format_map(MissingDict())
'{"foo .com": "bar [ baz ]", "ham": "eggs"}'
This fails for 'empty' attributes:
>>> '{"foo...com": "bar[baz]", "ham": "eggs"}'.format_map(MissingDict())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Empty attribute in format string
In short, the format makes too many assumptions about what is contained inside {...} curly braces, assumptions JSON data easily breaks.
I suggest you look at using the string.Template() class instead, a simpler templating system that can be subclassed; the default is to look for and replace $identifier strings. The Template.safe_substitute() method does exactly what you want; replace known $identifier placeholders, but leave unknown names untouched.
A:
import ast
my_dict = {'outer_key':{"inner1_k1":"iv_some_string_{xyz}"},"inner1_k2":{'inner2_k2':'{abc}'}}
s = str(my_dict)
maps = {'{xyz}':'is_cool','{abc}':123}
for k,v in maps.items():
s = s.replace(f"{k}",str(v))
my_dict = ast.literal_eval(s)
If you are okay with string as value in required dict.
|
Max string recursion exceeded when using str.format_map()
|
I am using str.format_map to format some strings but I encounter a problem when this string contains quotes, even escaped. Here is the code:
class __FormatDict(dict):
def __missing__(self, key):
return '{' + key + '}'
def format_dict(node, template_values):
template_values = __FormatDict(template_values)
for key, item in node.items():
if isinstance(item, str):
node[key] = item.format_map(template_values)
For reqular strings (that do not include brackets or quotes) it works, however for strings like "{\"libraries\":[{\"file\": \"bonjour.so\", \"modules\":[{\"name\": \"hello\"}]}]}" it crashes with the message ValueError: Max string recursion exceeded.
Escaping the quotes using json.dumps(item) before formatting it does not solve the issue. What should be done to fix this problem? I am modifying strings I get from JSON files and I would prefer to fix the Python code instead of updating the JSON documents I use.
|
[
"You can't use your __missing__ trick on JSON data. There are multiple problems. That's because the text within {...} replacement fields are not just treated as strings. Take a look at the syntax grammar:\n\nreplacement_field ::= \"{\" [field_name] [\"!\" conversion] [\":\" format_spec] \"}\"\nfield_name ::= arg_name (\".\" attribute_name | \"[\" element_index \"]\")*\n\n\nWithin a replacement field, !... and :... have meaning too! What goes into those sections has strict limits as well.\nThe recursion error comes from the multiple nested {...} placeholders inside placeholders inside placeholders; str.format() and str.format_map() can't support a large number of levels of nesting:\n>>> '{foo:{baz: {ham}}}'.format_map({'foo': 'bar', 'baz': 's', 'ham': 's'})\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nValueError: Max string recursion exceeded\n\nbut there are other problems here:\n\nThe : colon denotes a formatting specification, which is then passed to the object (key) from the part before the :. You'd have to give your __missing__ return values a wrapper object with __format__ method if you wanted to recover those.\nField names with . or [...] in them have special meaning too; \"bonjour.so\" will be parsed as the \"bonjour key, with a so attribute. Ditto for [...] in the field name, but for item lookups.\n\nThose last two can be approached by returning a wrapper object with __format__ and __getitem__ and __getattr__ methods, but only in limited cases:\n>>> class FormatWrapper:\n... def __init__(self, v):\n... self.v = v\n... def __format__(self, spec):\n... return '{{{}{}}}'.format(self.v, (':' + spec) if spec else '')\n... def __getitem__(self, key):\n... return FormatWrapper('{}[{}]'.format(self.v, key))\n... def __getattr__(self, attr):\n... return FormatWrapper('{}.{}'.format(self.v, attr))\n...\n>>> class MissingDict(dict):\n... def __missing__(self, key):\n... return FormatWrapper(key)\n...\n>>> '{\"foo.com\": \"bar[baz]\", \"ham\": \"eggs\"}'.format_map(MissingDict())\n'{\"foo.com\": \"bar[baz]\", \"ham\": \"eggs\"}'\n>>> '{\"foo .com\": \"bar [ baz ]\", \"ham\": \"eggs\"}'.format_map(MissingDict())\n'{\"foo .com\": \"bar [ baz ]\", \"ham\": \"eggs\"}'\n\nThis fails for 'empty' attributes:\n>>> '{\"foo...com\": \"bar[baz]\", \"ham\": \"eggs\"}'.format_map(MissingDict())\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nValueError: Empty attribute in format string\n\nIn short, the format makes too many assumptions about what is contained inside {...} curly braces, assumptions JSON data easily breaks.\nI suggest you look at using the string.Template() class instead, a simpler templating system that can be subclassed; the default is to look for and replace $identifier strings. The Template.safe_substitute() method does exactly what you want; replace known $identifier placeholders, but leave unknown names untouched.\n",
"import ast\nmy_dict = {'outer_key':{\"inner1_k1\":\"iv_some_string_{xyz}\"},\"inner1_k2\":{'inner2_k2':'{abc}'}}\n \ns = str(my_dict)\nmaps = {'{xyz}':'is_cool','{abc}':123}\nfor k,v in maps.items():\n s = s.replace(f\"{k}\",str(v))\n\nmy_dict = ast.literal_eval(s)\n\n\nIf you are okay with string as value in required dict.\n\n"
] |
[
4,
0
] |
[] |
[] |
[
"json",
"python",
"string"
] |
stackoverflow_0041738604_json_python_string.txt
|
Q:
no such option: --use-feature while installing tensorflow object detection api
I'm trying to install Tensorflow Object Detection API, following the steps at this link, which is the official installation's documentation for Tensorflow 2.
git clone https://github.com/tensorflow/models.git
> everything is ok
cd models/research/
> everything is ok
protoc object_detection/protos/*.proto --python_out=.
> everything is ok
cp object_detection/packages/tf2/setup.py .
> everything is ok
python -m pip install --use-feature=2020-resolver .
> Usage:
> /opt/anaconda3/envs/ml/bin/python -m pip install [options] <requirement specifier> [package-> index-options] ...
> /opt/anaconda3/envs/ml/bin/python -m pip install [options] -r <requirements file> [package-index-options] ...
> /opt/anaconda3/envs/ml/bin/python -m pip install [options] [-e] <vcs project url> ...
> /opt/anaconda3/envs/ml/bin/python -m pip install [options] [-e] <local project path> ...
> /opt/anaconda3/envs/ml/bin/python -m pip install [options] <archive url/path> ...
> no such option: --use-feature
Can someone help me understand why the installation stops as it does? I'm using macOS Mojave, Python 3.6 (on a conda virtual env), and Tensorflow 2.3.0.
A:
I had the same problem, I upgraded pip version from 20.0.2 to 20.2.2, then it worked.
An issue was opened on github on this matter, check here.
Use python -m pip install --upgrade pip to upgrade pip.
A:
just needed to upgrade pip from version 20.0.2 to 20.2.2. An issue on github has also been opened (here)
A:
For the Tensorflow installation, you can simply remove this option and use:
python -m pip install .
Read this:
pip 20.1 included an alpha version of the new resolver (hidden behind an optional --unstable-feature=resolver flag). pip 20.2 removes that flag, and includes a robust beta of the new resolver (hidden behind an optional --use-feature=2020-resolver flag) that we encourage you to test. We will continue to improve the pip dependency resolver in response to testers’ feedback. Please give us feedback through the resolver testing survey. This will help us prepare to release pip 20.3, with the new resolver on by default, in October.
A:
This is what i did and it worked
python -m pip install --user --use-feature=fast-deps .
|
no such option: --use-feature while installing tensorflow object detection api
|
I'm trying to install Tensorflow Object Detection API, following the steps at this link, which is the official installation's documentation for Tensorflow 2.
git clone https://github.com/tensorflow/models.git
> everything is ok
cd models/research/
> everything is ok
protoc object_detection/protos/*.proto --python_out=.
> everything is ok
cp object_detection/packages/tf2/setup.py .
> everything is ok
python -m pip install --use-feature=2020-resolver .
> Usage:
> /opt/anaconda3/envs/ml/bin/python -m pip install [options] <requirement specifier> [package-> index-options] ...
> /opt/anaconda3/envs/ml/bin/python -m pip install [options] -r <requirements file> [package-index-options] ...
> /opt/anaconda3/envs/ml/bin/python -m pip install [options] [-e] <vcs project url> ...
> /opt/anaconda3/envs/ml/bin/python -m pip install [options] [-e] <local project path> ...
> /opt/anaconda3/envs/ml/bin/python -m pip install [options] <archive url/path> ...
> no such option: --use-feature
Can someone help me understand why the installation stops as it does? I'm using macOS Mojave, Python 3.6 (on a conda virtual env), and Tensorflow 2.3.0.
|
[
"I had the same problem, I upgraded pip version from 20.0.2 to 20.2.2, then it worked.\nAn issue was opened on github on this matter, check here.\nUse python -m pip install --upgrade pip to upgrade pip.\n",
"just needed to upgrade pip from version 20.0.2 to 20.2.2. An issue on github has also been opened (here)\n",
"For the Tensorflow installation, you can simply remove this option and use:\npython -m pip install .\n\nRead this:\n\npip 20.1 included an alpha version of the new resolver (hidden behind an optional --unstable-feature=resolver flag). pip 20.2 removes that flag, and includes a robust beta of the new resolver (hidden behind an optional --use-feature=2020-resolver flag) that we encourage you to test. We will continue to improve the pip dependency resolver in response to testers’ feedback. Please give us feedback through the resolver testing survey. This will help us prepare to release pip 20.3, with the new resolver on by default, in October.\n\n",
"This is what i did and it worked\npython -m pip install --user --use-feature=fast-deps .\n"
] |
[
15,
3,
3,
0
] |
[] |
[] |
[
"object_detection",
"python",
"tensorflow",
"tensorflow2.0"
] |
stackoverflow_0063687113_object_detection_python_tensorflow_tensorflow2.0.txt
|
Q:
How to fix: missing 1 required positional argument: 'on_delete'
When I was working on a Django project (blog), I had an error(s) while working on the site. Here are the errors I have appeared:
1: When I entered the python command manage.py makemigrations blog(via the console) in the directory C:\mysite\site\miniproject , then there is this:
Traceback (most recent call last):
File "manage.py", line 23, in <module>
main()
File "manage.py", line 19, in main
execute_from_command_line(sys.argv)
File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 395, in execute
django.setup()
File "C:\Program Files\Python36\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Program Files\Python36\lib\site-packages\django\apps\registry.py", line 114, in populate
app_config.import_models()
File "C:\Program Files\Python36\lib\site-packages\django\apps\config.py", line 301, in import_models
self.models_module = import_module(models_module_name)
File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "C:\mysite\site\miniproject\blog\models.py", line 5, in <module>
class Post(models.Model):
File "C:\mysite\site\miniproject\blog\models.py", line 12, in Post
author = models.ForeignKey(User, related_name='blog_posts')
TypeError: __init__() missing 1 required positional argument: 'on_delete'
Although I did everything according to the instructions on the website https://pocoz .gitbooks.io/django-v-primerah/content/sozdanie-i-primenenie-migracij.html.
I did everything according to plan, I did everything in order and there was such a mistake. And I do not know how to fix it
Updated all the necessary libraries, entered them in manage.ру (which is located in the directory C:\mysite\site\miniproject ) import django, it didn't help
A:
You have declared a ForeignKey somewhere but not provided the on_delete keyword argument.
If you post the BlogPost model, I can give you an exact answer, but you probably want something like:
models.ForeignKey(..., on_delete=models.CASCADE)
To fix the issue add the key word argument to the BlogPost model in blog/models.py
A:
If you debug your error its pretty self-explanatory:
In line 12 File "C:\mysite\site\miniproject\blog\models.py", line 12, in Post
in your Post model you have a field
author = models.ForeignKey(User, related_name='blog_posts')
You need to change that to:
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
|
How to fix: missing 1 required positional argument: 'on_delete'
|
When I was working on a Django project (blog), I had an error(s) while working on the site. Here are the errors I have appeared:
1: When I entered the python command manage.py makemigrations blog(via the console) in the directory C:\mysite\site\miniproject , then there is this:
Traceback (most recent call last):
File "manage.py", line 23, in <module>
main()
File "manage.py", line 19, in main
execute_from_command_line(sys.argv)
File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 395, in execute
django.setup()
File "C:\Program Files\Python36\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Program Files\Python36\lib\site-packages\django\apps\registry.py", line 114, in populate
app_config.import_models()
File "C:\Program Files\Python36\lib\site-packages\django\apps\config.py", line 301, in import_models
self.models_module = import_module(models_module_name)
File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "C:\mysite\site\miniproject\blog\models.py", line 5, in <module>
class Post(models.Model):
File "C:\mysite\site\miniproject\blog\models.py", line 12, in Post
author = models.ForeignKey(User, related_name='blog_posts')
TypeError: __init__() missing 1 required positional argument: 'on_delete'
Although I did everything according to the instructions on the website https://pocoz .gitbooks.io/django-v-primerah/content/sozdanie-i-primenenie-migracij.html.
I did everything according to plan, I did everything in order and there was such a mistake. And I do not know how to fix it
Updated all the necessary libraries, entered them in manage.ру (which is located in the directory C:\mysite\site\miniproject ) import django, it didn't help
|
[
"You have declared a ForeignKey somewhere but not provided the on_delete keyword argument.\nIf you post the BlogPost model, I can give you an exact answer, but you probably want something like:\nmodels.ForeignKey(..., on_delete=models.CASCADE)\n\nTo fix the issue add the key word argument to the BlogPost model in blog/models.py\n",
"If you debug your error its pretty self-explanatory:\nIn line 12 File \"C:\\mysite\\site\\miniproject\\blog\\models.py\", line 12, in Post\nin your Post model you have a field\nauthor = models.ForeignKey(User, related_name='blog_posts')\n\nYou need to change that to:\nauthor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0074565437_django_python.txt
|
Q:
Plot a function with telegram bot (python, matplotlib)
I faced with the problem during telegram bot writing. I would be very happy if somebody help me with this.
My code
import telebot
import matplotlib.pyplot as plt
import numpy as np
...
def plot_func(message):
x = np.linspace(-5,5,100)
y = message.text # <-- here is something wrong I supppose
plt.plot(x, y, 'r')
plt.savefig('plot_name.png', dpi = 300)
bot.send_photo(message.chat.id, photo=open('plot_name.png', 'rb'))
#plt.show()
Main idea
User send function, bot plot it and send image back:
ERROR
/home/anmnv/Desktop/news_scrapper_bot/bot.py:148: UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail.
plt.plot(x, y, 'r')
Traceback (most recent call last):
File "/home/anmnv/Desktop/news_scrapper_bot/bot.py", line 424, in <module>
bot.polling(none_stop=True)
File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1047, in polling
self.__threaded_polling(non_stop=non_stop, interval=interval, timeout=timeout, long_polling_timeout=long_polling_timeout,
File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1122, in __threaded_polling
raise e
File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1078, in __threaded_polling
self.worker_pool.raise_exceptions()
File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/util.py", line 154, in raise_exceptions
raise self.exception_info
File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/util.py", line 98, in run
task(*args, **kwargs)
File "/home/anmnv/Desktop/news_scrapper_bot/bot.py", line 148, in plot_func
plt.plot(x, y, 'r')
File "/home/anmnv/.local/lib/python3.10/site-packages/matplotlib/pyplot.py", line 2730, in plot
return gca().plot(
File "/home/anmnv/.local/lib/python3.10/site-packages/matplotlib/axes/_axes.py", line 1662, in plot
lines = [*self._get_lines(*args, data=data, **kwargs)]
File "/home/anmnv/.local/lib/python3.10/site-packages/matplotlib/axes/_base.py", line 311, in __call__
yield from self._plot_args(
File "/home/anmnv/.local/lib/python3.10/site-packages/matplotlib/axes/_base.py", line 504, in _plot_args
raise ValueError(f"x and y must have same first dimension, but "
ValueError: x and y must have same first dimension, but have shapes (100,) and (1,)
Thank you in advance
A:
Assuming message.text contains the string 'x**2', you can use numexpr.evaluate to convert to numpy array:
import numexpr
import matplotlib.pyplot as plt
x = np.linspace(-5, 5, 100)
y = numexpr.evaluate(message.text) # message.text = 'x**2'
plt.plot(x, y, 'r')
Output:
|
Plot a function with telegram bot (python, matplotlib)
|
I faced with the problem during telegram bot writing. I would be very happy if somebody help me with this.
My code
import telebot
import matplotlib.pyplot as plt
import numpy as np
...
def plot_func(message):
x = np.linspace(-5,5,100)
y = message.text # <-- here is something wrong I supppose
plt.plot(x, y, 'r')
plt.savefig('plot_name.png', dpi = 300)
bot.send_photo(message.chat.id, photo=open('plot_name.png', 'rb'))
#plt.show()
Main idea
User send function, bot plot it and send image back:
ERROR
/home/anmnv/Desktop/news_scrapper_bot/bot.py:148: UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail.
plt.plot(x, y, 'r')
Traceback (most recent call last):
File "/home/anmnv/Desktop/news_scrapper_bot/bot.py", line 424, in <module>
bot.polling(none_stop=True)
File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1047, in polling
self.__threaded_polling(non_stop=non_stop, interval=interval, timeout=timeout, long_polling_timeout=long_polling_timeout,
File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1122, in __threaded_polling
raise e
File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1078, in __threaded_polling
self.worker_pool.raise_exceptions()
File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/util.py", line 154, in raise_exceptions
raise self.exception_info
File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/util.py", line 98, in run
task(*args, **kwargs)
File "/home/anmnv/Desktop/news_scrapper_bot/bot.py", line 148, in plot_func
plt.plot(x, y, 'r')
File "/home/anmnv/.local/lib/python3.10/site-packages/matplotlib/pyplot.py", line 2730, in plot
return gca().plot(
File "/home/anmnv/.local/lib/python3.10/site-packages/matplotlib/axes/_axes.py", line 1662, in plot
lines = [*self._get_lines(*args, data=data, **kwargs)]
File "/home/anmnv/.local/lib/python3.10/site-packages/matplotlib/axes/_base.py", line 311, in __call__
yield from self._plot_args(
File "/home/anmnv/.local/lib/python3.10/site-packages/matplotlib/axes/_base.py", line 504, in _plot_args
raise ValueError(f"x and y must have same first dimension, but "
ValueError: x and y must have same first dimension, but have shapes (100,) and (1,)
Thank you in advance
|
[
"Assuming message.text contains the string 'x**2', you can use numexpr.evaluate to convert to numpy array:\nimport numexpr\nimport matplotlib.pyplot as plt\n\nx = np.linspace(-5, 5, 100)\ny = numexpr.evaluate(message.text) # message.text = 'x**2'\n\nplt.plot(x, y, 'r')\n\nOutput:\n\n"
] |
[
1
] |
[] |
[] |
[
"matplotlib",
"plot",
"python",
"telegram",
"telegram_bot"
] |
stackoverflow_0074570550_matplotlib_plot_python_telegram_telegram_bot.txt
|
Q:
How to add a new JSON data at the end of the existing data in python
I am trying to populate a JSON file from the user input. The users.json file is initially empty, and I was able to register the first user ("Doe_Joh"). The problem was when I ran the program and registered for the second use. The data inside got replaced by the data. What I expected was to have the data saved incrementally. How can I achieve this?
Here is my code.
import json
class User:
def register():
first = input("Name: ")
last = input("Last: ")
username = input("Username: ")
email = input("Email: ")
user_data = { username: [ {
"fname": first,
"lname": last,
"username": username,
"email": email
}
]
}
with open("users.json", "w") as outfile:
json.dump(user_data, outfile, indent=4)
user1 = User
user1.register()
A:
You can do it in 2 ways:
Load the whole user.json, add a new user to the end of the file,
and save everything.
import json
from dataclasses import dataclass
@dataclass
class User:
f_name: str
l_name: str
username: str
email: str
def save_user(user: User) -> None:
with open("users.json", "r") as file:
try:
file_data = json.load(file)
except JSONDecodeError:
file_data = {}
file_data[user.username] = [{
"fname": user.f_name,
"lname": user.l_name,
"username": user.username,
"email": user.email
}]
with open("users.json", "w") as outfile:
json.dump(file_data, outfile, indent=4)
def register():
first = input("Name: ")
last = input("Last: ")
username = input("Username: ")
email = input("Email: ")
user_data = User(
f_name=first,
l_name=last,
username=username,
email=email
)
save_user(user=user_data)
register()
Without dataclasses (as per OP's requirement):
import json
def save_user(user) -> None:
with open("users.json", "r") as file:
try:
file_data = json.load(file)
except JSONDecodeError:
file_data = {}
file_data[user['username']] = [{
"fname": user['f_name'],
"lname": user['l_name'],
"username": user['username'],
"email": user['email']
}]
with open("users.json", "w") as outfile:
json.dump(file_data, outfile, indent=4)
def register():
first = input("Name: ")
last = input("Last: ")
username = input("Username: ")
email = input("Email: ")
user_data = {
"f_name": first,
"l_name": last,
"username": username,
"email": email
}
save_user(user=user_data)
register()
Or try to open your user.json in append mode:
with open("users.json", "a") as outfile:
json.dump(user_data, outfile, indent=4)
Note the "a" in the open() function.
Note: This will break your formatting in the file
A:
You can make load() function that loads previously saved data.
import json
import os
data = {}
class User():
def register(self):
first = input("Name: ")
last = input("Last: ")
username = input("Username: ")
email = input("Email: ")
data[username] = [{
"fname": first,
"lname": last,
"username": username,
"email": email
}
]
with open("users.json", "w") as outfile:
json.dump(data, outfile, indent=4)
def load(self):
global data
with open("users.json", "r") as outfile:
data = json.loads(outfile.read())
print(data, type(data))
return data
user1 = User()
if os.path.isfile("users.json"):
user1.load()
user1.register()
|
How to add a new JSON data at the end of the existing data in python
|
I am trying to populate a JSON file from the user input. The users.json file is initially empty, and I was able to register the first user ("Doe_Joh"). The problem was when I ran the program and registered for the second use. The data inside got replaced by the data. What I expected was to have the data saved incrementally. How can I achieve this?
Here is my code.
import json
class User:
def register():
first = input("Name: ")
last = input("Last: ")
username = input("Username: ")
email = input("Email: ")
user_data = { username: [ {
"fname": first,
"lname": last,
"username": username,
"email": email
}
]
}
with open("users.json", "w") as outfile:
json.dump(user_data, outfile, indent=4)
user1 = User
user1.register()
|
[
"You can do it in 2 ways:\nLoad the whole user.json, add a new user to the end of the file,\nand save everything.\nimport json\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass User:\n f_name: str\n l_name: str\n username: str\n email: str\n\n\ndef save_user(user: User) -> None:\n with open(\"users.json\", \"r\") as file:\n try:\n file_data = json.load(file)\n except JSONDecodeError:\n file_data = {}\n file_data[user.username] = [{\n \"fname\": user.f_name,\n \"lname\": user.l_name,\n \"username\": user.username,\n \"email\": user.email\n }]\n with open(\"users.json\", \"w\") as outfile:\n json.dump(file_data, outfile, indent=4)\n\n\ndef register():\n first = input(\"Name: \")\n last = input(\"Last: \")\n username = input(\"Username: \")\n email = input(\"Email: \")\n user_data = User(\n f_name=first,\n l_name=last,\n username=username,\n email=email\n )\n save_user(user=user_data)\n\n\nregister()\n\nWithout dataclasses (as per OP's requirement):\nimport json\n\n\ndef save_user(user) -> None:\n with open(\"users.json\", \"r\") as file:\n try:\n file_data = json.load(file)\n except JSONDecodeError:\n file_data = {}\n file_data[user['username']] = [{\n \"fname\": user['f_name'],\n \"lname\": user['l_name'],\n \"username\": user['username'],\n \"email\": user['email']\n }]\n with open(\"users.json\", \"w\") as outfile:\n json.dump(file_data, outfile, indent=4)\n\n\ndef register():\n first = input(\"Name: \")\n last = input(\"Last: \")\n username = input(\"Username: \")\n email = input(\"Email: \")\n user_data = {\n \"f_name\": first,\n \"l_name\": last,\n \"username\": username,\n \"email\": email\n }\n save_user(user=user_data)\n\n\nregister()\n\nOr try to open your user.json in append mode:\n with open(\"users.json\", \"a\") as outfile:\n json.dump(user_data, outfile, indent=4)\n\nNote the \"a\" in the open() function.\nNote: This will break your formatting in the file\n",
"You can make load() function that loads previously saved data.\nimport json\nimport os\n\ndata = {}\n\n\nclass User():\n\n def register(self):\n first = input(\"Name: \")\n last = input(\"Last: \")\n username = input(\"Username: \")\n email = input(\"Email: \")\n data[username] = [{\n \"fname\": first,\n \"lname\": last,\n \"username\": username,\n \"email\": email\n }\n ]\n with open(\"users.json\", \"w\") as outfile:\n json.dump(data, outfile, indent=4)\n\n def load(self):\n global data\n with open(\"users.json\", \"r\") as outfile:\n data = json.loads(outfile.read())\n print(data, type(data))\n return data\n\n\nuser1 = User()\n\nif os.path.isfile(\"users.json\"):\n user1.load()\nuser1.register()\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"json",
"python"
] |
stackoverflow_0074570372_json_python.txt
|
Q:
CombineFn for Python dict in Apache Beam pipeline
I've been experimenting with the Apache Beam SDK in Python to write data processing pipelines.
My data mocks IoT sensor data from a Google PubSub topic that streams JSON data like this:
{"id": 1, "temperature": 12.34}
{"id": 2, "temperature": 76.54}
There are IDs ranging from 0 to 99. Reading the JSON into a Python dict is no problem.
I created a custom CombineFn to process by CombinePerKey. I hoped that the output of my accumulator would be the calculations, grouped by the respective id fields from the dictionaries in the PCollection.
However, when the add_input method is called, it only receives the string temperature instead of the whole dictionary. I also did not find any reference to tell CombinePerKey which key (id field in my case) I want it to group data.
Maybe I also misunderstood the concept of CombinePerKey and CombineFn. I'd appreciate any help or hint on this. Maybe someone has an example for processing JSON batches with ID based grouping? Do I have to convert the dictionary into something else?
A:
You need to either adjust your CombineFn or (what I would recommend) keep the CombineFn as generic as possible and map the input of the CombinePerKey accordingly. I have made a short examples of both cases below using this official beam example.
Specific CombineFn:
import apache_beam as beam
class SpecificAverageFn(beam.CombineFn):
def create_accumulator(self):
sum = 0.0
count = 0
accumulator = sum, count
return accumulator
def add_input(self, accumulator, input):
sum, count = accumulator
extracted_input = input['temperature'] # <- this is a dict, you need to create custom code here
return sum + extracted_input, count + 1
def merge_accumulators(self, accumulators):
# accumulators = [(sum1, count1), (sum2, count2), (sum3, count3), ...]
sums, counts = zip(*accumulators)
# sums = [sum1, sum2, sum3, ...]
# counts = [count1, count2, count3, ...]
return sum(sums), sum(counts)
def extract_output(self, accumulator):
sum, count = accumulator
if count == 0:
return float('NaN')
return sum / count
with beam.Pipeline() as pipeline:
(
pipeline
| "mock input" >> beam.Create([
{'id': 1, 'temperature': 2},
{'id': 2, 'temperature': 3},
{'id': 2, 'temperature': 2}
])
| "add key" >> beam.Map(lambda x: (x['id'], x))
| beam.CombinePerKey(SpecificAverageFn())
| beam.Map(print)
)
Generic Combinefn:
import apache_beam as beam
class GenericAverageFn(beam.CombineFn):
# everything as SpecificAverageFn, except add_input:
def add_input(self, accumulator, input):
sum, count = accumulator
return sum + input, count + 1
with beam.Pipeline() as pipeline:
iot_data = (
pipeline
| "mock input" >> beam.Create([
{'id': 1, 'temperature': 2},
{'id': 2, 'temperature': 3},
{'id': 2, 'temperature': 2}
])
| "add key" >> beam.Map(lambda x: (x['id'], x))
)
# repeat below for other values
(
iot_data
| "extract temp" >> beam.Map(lambda x: (x[0], x[1]['temperature'])
| beam.CombinePerKey(AverageFn())
| beam.Map(print)
)
Both approaches return
(1, 2.0)
(2, 2.5)
|
CombineFn for Python dict in Apache Beam pipeline
|
I've been experimenting with the Apache Beam SDK in Python to write data processing pipelines.
My data mocks IoT sensor data from a Google PubSub topic that streams JSON data like this:
{"id": 1, "temperature": 12.34}
{"id": 2, "temperature": 76.54}
There are IDs ranging from 0 to 99. Reading the JSON into a Python dict is no problem.
I created a custom CombineFn to process by CombinePerKey. I hoped that the output of my accumulator would be the calculations, grouped by the respective id fields from the dictionaries in the PCollection.
However, when the add_input method is called, it only receives the string temperature instead of the whole dictionary. I also did not find any reference to tell CombinePerKey which key (id field in my case) I want it to group data.
Maybe I also misunderstood the concept of CombinePerKey and CombineFn. I'd appreciate any help or hint on this. Maybe someone has an example for processing JSON batches with ID based grouping? Do I have to convert the dictionary into something else?
|
[
"You need to either adjust your CombineFn or (what I would recommend) keep the CombineFn as generic as possible and map the input of the CombinePerKey accordingly. I have made a short examples of both cases below using this official beam example.\nSpecific CombineFn:\nimport apache_beam as beam\n\nclass SpecificAverageFn(beam.CombineFn):\n def create_accumulator(self):\n sum = 0.0\n count = 0\n accumulator = sum, count\n return accumulator\n\n def add_input(self, accumulator, input):\n sum, count = accumulator\n extracted_input = input['temperature'] # <- this is a dict, you need to create custom code here\n return sum + extracted_input, count + 1\n\n def merge_accumulators(self, accumulators):\n # accumulators = [(sum1, count1), (sum2, count2), (sum3, count3), ...]\n sums, counts = zip(*accumulators)\n # sums = [sum1, sum2, sum3, ...]\n # counts = [count1, count2, count3, ...]\n return sum(sums), sum(counts)\n\n def extract_output(self, accumulator):\n sum, count = accumulator\n if count == 0:\n return float('NaN')\n return sum / count\n\nwith beam.Pipeline() as pipeline:\n (\n pipeline\n | \"mock input\" >> beam.Create([\n {'id': 1, 'temperature': 2},\n {'id': 2, 'temperature': 3},\n {'id': 2, 'temperature': 2}\n ])\n | \"add key\" >> beam.Map(lambda x: (x['id'], x))\n | beam.CombinePerKey(SpecificAverageFn())\n | beam.Map(print)\n )\n\nGeneric Combinefn:\nimport apache_beam as beam\n\nclass GenericAverageFn(beam.CombineFn):\n # everything as SpecificAverageFn, except add_input:\n def add_input(self, accumulator, input):\n sum, count = accumulator\n return sum + input, count + 1\n\n\nwith beam.Pipeline() as pipeline:\n iot_data = (\n pipeline\n | \"mock input\" >> beam.Create([\n {'id': 1, 'temperature': 2},\n {'id': 2, 'temperature': 3},\n {'id': 2, 'temperature': 2}\n ])\n | \"add key\" >> beam.Map(lambda x: (x['id'], x))\n )\n\n # repeat below for other values\n (\n iot_data\n | \"extract temp\" >> beam.Map(lambda x: (x[0], x[1]['temperature']) \n | beam.CombinePerKey(AverageFn())\n | beam.Map(print)\n )\n\nBoth approaches return\n(1, 2.0)\n(2, 2.5)\n\n"
] |
[
1
] |
[] |
[] |
[
"apache_beam",
"google_cloud_dataflow",
"python"
] |
stackoverflow_0074521933_apache_beam_google_cloud_dataflow_python.txt
|
Q:
Testing logging output with pytest
I am trying to write a test, using pytest, that would check that a specific function is writing out a warning to the log when needed. For example:
In module.py:
import logging
LOGGER = logging.getLogger(__name__)
def run_function():
if something_bad_happens:
LOGGER.warning('Something bad happened!')
In test_module.py:
import logging
from module import run_function
LOGGER = logging.getLogger(__name__)
def test_func():
LOGGER.info('Testing now.')
run_function()
~ somehow get the stdout/log of run_function() ~
assert 'Something bad happened!' in output
I have seen that you can supposedly get the log or the stdout/stderr with pytest by passing capsys or caplog as an argument to the test, and then using either capsus.readouterr() or caplog.records to access the output.
However, when I try those methods, I only see "Testing now.", and not "Something bad happened!". It seems like the logging output that is happening within the call to run_function() is not accessible from test_func()?
The same thing happens if I try a more direct method, such as sys.stdout.getvalue(). Which is confusing, because run_function() is writing to the terminal, so I would think that would be accessible from stdout...?
Basically, does anyone know how I can access that 'Something bad happened!' from within test_func()?
A:
I don't know why this didn't work when I tried it before, but this solution works for me now:
In test_module.py:
import logging
from module import run_function
LOGGER = logging.getLogger(__name__)
def test_func(caplog):
LOGGER.info('Testing now.')
run_function()
assert 'Something bad happened!' in caplog.text
A:
test_module.py should look like this:
import logging
from module import run_function
LOGGER = logging.getLogger(__name__)
def test_func(caplog):
with caplog.at_level(logging.WARNING):
run_function()
assert 'Something bad happened!' in caplog.text
or, alternatively:
import logging
from module import run_function
LOGGER = logging.getLogger(__name__)
def test_func(caplog):
caplog.set_level(logging.WARNING)
run_function()
assert 'Something bad happened!' in caplog.text
Documentation for pytest capture logging is here
A:
In your logging set up, check propagate is set to True, otherwise caplog handler is not able to see the logging message.
A:
I also want to add to this thread for anybody in the future coming across this. You may need to use
@pytest.fixture(autouse=True)
as a decorator on your test so the test has access to the caplog fixture.
A:
I had the same issue. I just explicitly mentioned the name of the module instead of name inside the test function And set the propagate attribute to True.
Note: module should be the directory in which you have scripts to be test.
def test_func():
LOGGER = logging.getLogger("module")
LOGGER.propagate = True
run_function()
~ somehow get the stdout/log of run_function() ~
assert 'Something bad happened!' in output
|
Testing logging output with pytest
|
I am trying to write a test, using pytest, that would check that a specific function is writing out a warning to the log when needed. For example:
In module.py:
import logging
LOGGER = logging.getLogger(__name__)
def run_function():
if something_bad_happens:
LOGGER.warning('Something bad happened!')
In test_module.py:
import logging
from module import run_function
LOGGER = logging.getLogger(__name__)
def test_func():
LOGGER.info('Testing now.')
run_function()
~ somehow get the stdout/log of run_function() ~
assert 'Something bad happened!' in output
I have seen that you can supposedly get the log or the stdout/stderr with pytest by passing capsys or caplog as an argument to the test, and then using either capsus.readouterr() or caplog.records to access the output.
However, when I try those methods, I only see "Testing now.", and not "Something bad happened!". It seems like the logging output that is happening within the call to run_function() is not accessible from test_func()?
The same thing happens if I try a more direct method, such as sys.stdout.getvalue(). Which is confusing, because run_function() is writing to the terminal, so I would think that would be accessible from stdout...?
Basically, does anyone know how I can access that 'Something bad happened!' from within test_func()?
|
[
"I don't know why this didn't work when I tried it before, but this solution works for me now:\nIn test_module.py:\nimport logging\nfrom module import run_function\n\nLOGGER = logging.getLogger(__name__)\n\ndef test_func(caplog):\n LOGGER.info('Testing now.')\n run_function()\n assert 'Something bad happened!' in caplog.text\n\n",
"test_module.py should look like this:\nimport logging\nfrom module import run_function\n\nLOGGER = logging.getLogger(__name__)\n\ndef test_func(caplog):\n with caplog.at_level(logging.WARNING):\n run_function()\n assert 'Something bad happened!' in caplog.text\n\nor, alternatively:\nimport logging\nfrom module import run_function\n\nLOGGER = logging.getLogger(__name__)\n\ndef test_func(caplog):\n caplog.set_level(logging.WARNING)\n run_function()\n assert 'Something bad happened!' in caplog.text\n\nDocumentation for pytest capture logging is here\n",
"In your logging set up, check propagate is set to True, otherwise caplog handler is not able to see the logging message.\n",
"I also want to add to this thread for anybody in the future coming across this. You may need to use\n@pytest.fixture(autouse=True)\n\nas a decorator on your test so the test has access to the caplog fixture.\n",
"I had the same issue. I just explicitly mentioned the name of the module instead of name inside the test function And set the propagate attribute to True.\nNote: module should be the directory in which you have scripts to be test.\ndef test_func():\nLOGGER = logging.getLogger(\"module\")\nLOGGER.propagate = True\nrun_function()\n~ somehow get the stdout/log of run_function() ~\nassert 'Something bad happened!' in output\n\n"
] |
[
54,
47,
8,
1,
0
] |
[] |
[] |
[
"logging",
"pytest",
"python",
"testing",
"unit_testing"
] |
stackoverflow_0053125305_logging_pytest_python_testing_unit_testing.txt
|
Q:
How to fix beautiful soup list index out of range
I want to get specific information from the website. It is okey to run first four url, but when we run the fifth one, we get 'IndexError: list index out of range' at 'company = soup.select('.companyName')[0].get_text().strip()'.
we have url like
https://www.indeed.com/jobs?q=data analyst&l=remote
## Number of postings to scrape
postings = 100
jn=0
for i in range(0, postings, 10):
driver.get(url + "&start=" + str(i))
driver.implicitly_wait(3)
jobs = driver.find_elements(By.CLASS_NAME, 'job_seen_beacon')
for job in jobs:
result_html = job.get_attribute('innerHTML')
soup = BeautifulSoup(result_html, 'html.parser')
jn += 1
liens = job.find_elements(By.TAG_NAME, "a")
links = liens[0].get_attribute("href")
title = soup.select('.jobTitle')[0].get_text().strip()
company = soup.select('.companyName')[0].get_text().strip()
location = soup.select('.companyLocation')[0].get_text().strip()
try:
salary = soup.select('.salary-snippet-container')[0].get_text().strip()
except:
salary = 'NaN'
try:
rating = soup.select('.ratingNumber')[0].get_text().strip()
except:
rating = 'NaN'
try:
date = soup.select('.date')[0].get_text().strip()
except:
date = 'NaN'
try:
description = soup.select('.job-snippet')[0].get_text().strip()
except:
description = ''
dataframe = pd.concat([dataframe, pd.DataFrame([{'Title': title,
"Company": company,
'Location': location,
'Rating': rating,
'Date': date,
"Salary": salary,
"Description": description,
"Links": links}])], ignore_index=True)
print("Job number {0:4d} added - {1:s}".format(jn,title))
A:
Generally, it's safer to check that select/find returns something before applying .get.... When you have to select-and-get from multiple elements, it's more convenient to use a function on loop.
[This is a simplified version of another function I often use when scraping; if interested, see an example with the full version.]
def extractAttr(tag, sel, attr='', defVal=None):
s = tag.select_one(sel)
if s is None: return defVal
if attr == '':
stxt = s.get_text(' ').strip()
return stxt if stxt else defVal
return s.get(attr, defVal)
then you just need to create a reference list with selectors for all the information you need:
selRef = [ # key, selector, attribute, default
('Title', '.jobTitle', '', '?'),
('Company', '.companyName', '', '?'),
('Location', '.companyLocation', '', '?'),
('Rating', '.ratingNumber', '', 'NaN'),
('Date', '.date', '', 'NaN'),
('Salary', '.salary-snippet-container', '', 'NaN'),
('Description', '.job-snippet', '', ''),
('Links', 'a[href]', 'href', None)
] # be careful to have exactly 4 items in each tuple
and you can just simplify your loop to
for job in jobs:
result_html = job.get_attribute('innerHTML')
soup = BeautifulSoup(result_html, 'html.parser')
jn += 1
jDict = {k: extractAttr(soup, s, a, d) for k, s, a, d in selRef}
dataframe = pd.concat([dataframe, pd.DataFrame([jDict])])
print("Job number {0:4d} added - {1:s}".format(jn, jDict['Title']))
|
How to fix beautiful soup list index out of range
|
I want to get specific information from the website. It is okey to run first four url, but when we run the fifth one, we get 'IndexError: list index out of range' at 'company = soup.select('.companyName')[0].get_text().strip()'.
we have url like
https://www.indeed.com/jobs?q=data analyst&l=remote
## Number of postings to scrape
postings = 100
jn=0
for i in range(0, postings, 10):
driver.get(url + "&start=" + str(i))
driver.implicitly_wait(3)
jobs = driver.find_elements(By.CLASS_NAME, 'job_seen_beacon')
for job in jobs:
result_html = job.get_attribute('innerHTML')
soup = BeautifulSoup(result_html, 'html.parser')
jn += 1
liens = job.find_elements(By.TAG_NAME, "a")
links = liens[0].get_attribute("href")
title = soup.select('.jobTitle')[0].get_text().strip()
company = soup.select('.companyName')[0].get_text().strip()
location = soup.select('.companyLocation')[0].get_text().strip()
try:
salary = soup.select('.salary-snippet-container')[0].get_text().strip()
except:
salary = 'NaN'
try:
rating = soup.select('.ratingNumber')[0].get_text().strip()
except:
rating = 'NaN'
try:
date = soup.select('.date')[0].get_text().strip()
except:
date = 'NaN'
try:
description = soup.select('.job-snippet')[0].get_text().strip()
except:
description = ''
dataframe = pd.concat([dataframe, pd.DataFrame([{'Title': title,
"Company": company,
'Location': location,
'Rating': rating,
'Date': date,
"Salary": salary,
"Description": description,
"Links": links}])], ignore_index=True)
print("Job number {0:4d} added - {1:s}".format(jn,title))
|
[
"Generally, it's safer to check that select/find returns something before applying .get.... When you have to select-and-get from multiple elements, it's more convenient to use a function on loop.\n[This is a simplified version of another function I often use when scraping; if interested, see an example with the full version.]\ndef extractAttr(tag, sel, attr='', defVal=None):\n s = tag.select_one(sel)\n if s is None: return defVal\n if attr == '': \n stxt = s.get_text(' ').strip()\n return stxt if stxt else defVal\n return s.get(attr, defVal)\n\nthen you just need to create a reference list with selectors for all the information you need:\nselRef = [ # key, selector, attribute, default\n ('Title', '.jobTitle', '', '?'),\n ('Company', '.companyName', '', '?'),\n ('Location', '.companyLocation', '', '?'),\n ('Rating', '.ratingNumber', '', 'NaN'),\n ('Date', '.date', '', 'NaN'),\n ('Salary', '.salary-snippet-container', '', 'NaN'),\n ('Description', '.job-snippet', '', ''),\n ('Links', 'a[href]', 'href', None)\n] # be careful to have exactly 4 items in each tuple\n\nand you can just simplify your loop to\n for job in jobs:\n result_html = job.get_attribute('innerHTML')\n soup = BeautifulSoup(result_html, 'html.parser') \n jn += 1\n\n jDict = {k: extractAttr(soup, s, a, d) for k, s, a, d in selRef}\n dataframe = pd.concat([dataframe, pd.DataFrame([jDict])])\n print(\"Job number {0:4d} added - {1:s}\".format(jn, jDict['Title']))\n\n"
] |
[
0
] |
[] |
[] |
[
"beautifulsoup",
"python",
"web_scraping"
] |
stackoverflow_0074525562_beautifulsoup_python_web_scraping.txt
|
Q:
To to remove html tag to get text
I have text like this:
text =
<option value="tfa_4472" id="tfa_4472" class="">helo 1</option>
<option value="tfa_4473" id="tfa_4473" class="">helo 2</option>
<option value="tfa_4474" id="tfa_4474" class="">helo 3</option>
<option value="tfa_4475" id="tfa_4475" class="">helo 4</option>
<option value="tfa_4476" id="tfa_4476" class="">helo 5</option>
i want get result like this:
my_list = get_text(text)
helo 1
helo 2
helo 3
helo 4
helo 5
Thank you
To to remove html tag to get text
A:
Python:
from bs4 import BeautifulSoup
myhtml = """<option value="tfa_4472" id="tfa_4472" class="">helo 1</option>
<option value="tfa_4473" id="tfa_4473" class="">helo 2</option>
<option value="tfa_4474" id="tfa_4474" class="">helo 3</option>
<option value="tfa_4475" id="tfa_4475" class="">helo 4</option>
<option value="tfa_4476" id="tfa_4476" class="">helo 5</option>"""
soup = BeautifulSoup(myhtml, 'html.parser')
my_text = []
for text_tag in soup.find_all("option", {'class': ''}):
my_text.append(text_tag.getText())
my_text
['helo 1', 'helo 2', 'helo 3', 'helo 4', 'helo 5']
A:
In javascript you can try to select the option tags with queryselectorall and get the text with innerText by looping over the nodes and appending to myList.
$mylist = []
$nodes = document.querySelectorAll('option')
$nodes.forEach($node => {
$mylist += $node.innerText
});
console.log($mylist)
|
To to remove html tag to get text
|
I have text like this:
text =
<option value="tfa_4472" id="tfa_4472" class="">helo 1</option>
<option value="tfa_4473" id="tfa_4473" class="">helo 2</option>
<option value="tfa_4474" id="tfa_4474" class="">helo 3</option>
<option value="tfa_4475" id="tfa_4475" class="">helo 4</option>
<option value="tfa_4476" id="tfa_4476" class="">helo 5</option>
i want get result like this:
my_list = get_text(text)
helo 1
helo 2
helo 3
helo 4
helo 5
Thank you
To to remove html tag to get text
|
[
"Python:\nfrom bs4 import BeautifulSoup\n\n\nmyhtml = \"\"\"<option value=\"tfa_4472\" id=\"tfa_4472\" class=\"\">helo 1</option>\n<option value=\"tfa_4473\" id=\"tfa_4473\" class=\"\">helo 2</option>\n<option value=\"tfa_4474\" id=\"tfa_4474\" class=\"\">helo 3</option>\n<option value=\"tfa_4475\" id=\"tfa_4475\" class=\"\">helo 4</option>\n<option value=\"tfa_4476\" id=\"tfa_4476\" class=\"\">helo 5</option>\"\"\"\n\n\nsoup = BeautifulSoup(myhtml, 'html.parser')\n\nmy_text = []\nfor text_tag in soup.find_all(\"option\", {'class': ''}):\n my_text.append(text_tag.getText()) \n\nmy_text\n['helo 1', 'helo 2', 'helo 3', 'helo 4', 'helo 5']\n",
"In javascript you can try to select the option tags with queryselectorall and get the text with innerText by looping over the nodes and appending to myList.\n$mylist = []\n$nodes = document.querySelectorAll('option')\n\n$nodes.forEach($node => {\n $mylist += $node.innerText\n});\n\nconsole.log($mylist)\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"javascript",
"python"
] |
stackoverflow_0074570186_javascript_python.txt
|
Q:
How to annotate my subclass to avoid mypy error: Class cannot sublass "Foo" (has type "Any")
I have a common library, lib_common that defines a basic pydantic BaseModel that I use in all other packages:
├── lib_common
├── __init__.py
├── models.py
where models.py contains:
from pydantic import BaseModel, Extra
class StrictBaseModel(BaseModel):
class Config:
extra = Extra.forbid
Whenever I try to import this into other packages and inherit from StrictBaseModel to define a pydantic model, I get the
error: Class cannot subclass "StrictBaseModel" (has type "Any")
from pydantic import Field
from lib_common.models import StrictBaseModel
class Foo(StrictBaseModel):
bar: str = Field(...)
I haven't found a good answer to what that actually means. What hints to I need to add to not get this warning? I don't want to just mute it with a # type: ignore or change my mypy settings.
It's really weird to me that this error only occurs since lib_common is a separate python package that my other packages depend on.
I've seen multiple posts on this, with good answers like here: mypy calls error: Class cannot subclass 'ObjectType' (has type 'Any') on graphene that says to build a stub-file for the package you are importing. But these are all exclusively using external libraries. However, I have the option to just type-hint my imported/inherited class correctly.
How do I solve this? Thanks
A:
If lib_common is a separate package, then there is nothing weird here.
PEP561 explains it quite well: if your package contains inline annotations (e.g. you consider it typed and do not ship separate stub files), then it needs a py.typed marker in root.
There is an example of such package in mypy documentation. Quote:
If you would like to publish a library package to a package repository yourself (e.g. on PyPI) for either internal or external use in type checking, packages that supply type information via type comments or annotations in the code should put a py.typed file in their package directory. For example, here is a typical directory structure:
setup.py
package_a/
__init__.py
lib.py
py.typed
py.typed marker is just an empty file named py.typed and located in appropriate place.
|
How to annotate my subclass to avoid mypy error: Class cannot sublass "Foo" (has type "Any")
|
I have a common library, lib_common that defines a basic pydantic BaseModel that I use in all other packages:
├── lib_common
├── __init__.py
├── models.py
where models.py contains:
from pydantic import BaseModel, Extra
class StrictBaseModel(BaseModel):
class Config:
extra = Extra.forbid
Whenever I try to import this into other packages and inherit from StrictBaseModel to define a pydantic model, I get the
error: Class cannot subclass "StrictBaseModel" (has type "Any")
from pydantic import Field
from lib_common.models import StrictBaseModel
class Foo(StrictBaseModel):
bar: str = Field(...)
I haven't found a good answer to what that actually means. What hints to I need to add to not get this warning? I don't want to just mute it with a # type: ignore or change my mypy settings.
It's really weird to me that this error only occurs since lib_common is a separate python package that my other packages depend on.
I've seen multiple posts on this, with good answers like here: mypy calls error: Class cannot subclass 'ObjectType' (has type 'Any') on graphene that says to build a stub-file for the package you are importing. But these are all exclusively using external libraries. However, I have the option to just type-hint my imported/inherited class correctly.
How do I solve this? Thanks
|
[
"If lib_common is a separate package, then there is nothing weird here.\nPEP561 explains it quite well: if your package contains inline annotations (e.g. you consider it typed and do not ship separate stub files), then it needs a py.typed marker in root.\nThere is an example of such package in mypy documentation. Quote:\n\nIf you would like to publish a library package to a package repository yourself (e.g. on PyPI) for either internal or external use in type checking, packages that supply type information via type comments or annotations in the code should put a py.typed file in their package directory. For example, here is a typical directory structure:\n\nsetup.py\npackage_a/\n __init__.py\n lib.py\n py.typed\n\npy.typed marker is just an empty file named py.typed and located in appropriate place.\n"
] |
[
1
] |
[] |
[] |
[
"mypy",
"python",
"python_typing"
] |
stackoverflow_0070290482_mypy_python_python_typing.txt
|
Q:
How do I write JSON data to a file?
How do I write JSON data stored in the dictionary data to a file?
f = open('data.json', 'wb')
f.write(data)
This gives the error:
TypeError: must be string or buffer, not dict
A:
data is a Python dictionary. It needs to be encoded as JSON before writing.
Use this for maximum compatibility (Python 2 and 3):
import json
with open('data.json', 'w') as f:
json.dump(data, f)
On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using:
import json
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
See json documentation.
A:
To get utf8-encoded file as opposed to ascii-encoded in the accepted answer for Python 2 use:
import io, json
with io.open('data.txt', 'w', encoding='utf-8') as f:
f.write(json.dumps(data, ensure_ascii=False))
The code is simpler in Python 3:
import json
with open('data.txt', 'w') as f:
json.dump(data, f, ensure_ascii=False)
On Windows, the encoding='utf-8' argument to open is still necessary.
To avoid storing an encoded copy of the data in memory (result of dumps) and to output utf8-encoded bytestrings in both Python 2 and 3, use:
import json, codecs
with open('data.txt', 'wb') as f:
json.dump(data, codecs.getwriter('utf-8')(f), ensure_ascii=False)
The codecs.getwriter call is redundant in Python 3 but required for Python 2
Readability and size:
The use of ensure_ascii=False gives better readability and smaller size:
>>> json.dumps({'price': '€10'})
'{"price": "\\u20ac10"}'
>>> json.dumps({'price': '€10'}, ensure_ascii=False)
'{"price": "€10"}'
>>> len(json.dumps({'абвгд': 1}))
37
>>> len(json.dumps({'абвгд': 1}, ensure_ascii=False).encode('utf8'))
17
Further improve readability by adding flags indent=4, sort_keys=True (as suggested by dinos66) to arguments of dump or dumps. This way you'll get a nicely indented sorted structure in the json file at the cost of a slightly larger file size.
A:
I would answer with slight modification with aforementioned answers and that is to write a prettified JSON file which human eyes can read better. For this, pass sort_keys as True and indent with 4 space characters and you are good to go. Also take care of ensuring that the ascii codes will not be written in your JSON file:
with open('data.txt', 'w') as out_file:
json.dump(json_data, out_file, sort_keys = True, indent = 4,
ensure_ascii = False)
A:
Read and write JSON files with Python 2+3; works with unicode
# -*- coding: utf-8 -*-
import json
# Make it work for Python 2+3 and with Unicode
import io
try:
to_unicode = unicode
except NameError:
to_unicode = str
# Define data
data = {'a list': [1, 42, 3.141, 1337, 'help', u'€'],
'a string': 'bla',
'another dict': {'foo': 'bar',
'key': 'value',
'the answer': 42}}
# Write JSON file
with io.open('data.json', 'w', encoding='utf8') as outfile:
str_ = json.dumps(data,
indent=4, sort_keys=True,
separators=(',', ': '), ensure_ascii=False)
outfile.write(to_unicode(str_))
# Read JSON file
with open('data.json') as data_file:
data_loaded = json.load(data_file)
print(data == data_loaded)
Explanation of the parameters of json.dump:
indent: Use 4 spaces to indent each entry, e.g. when a new dict is started (otherwise all will be in one line),
sort_keys: sort the keys of dictionaries. This is useful if you want to compare json files with a diff tool / put them under version control.
separators: To prevent Python from adding trailing whitespaces
With a package
Have a look at my utility package mpu for a super simple and easy to remember one:
import mpu.io
data = mpu.io.read('example.json')
mpu.io.write('example.json', data)
Created JSON file
{
"a list":[
1,
42,
3.141,
1337,
"help",
"€"
],
"a string":"bla",
"another dict":{
"foo":"bar",
"key":"value",
"the answer":42
}
}
Common file endings
.json
Alternatives
CSV: Super simple format (read & write)
JSON: Nice for writing human-readable data; VERY commonly used (read & write)
YAML: YAML is a superset of JSON, but easier to read (read & write, comparison of JSON and YAML)
pickle: A Python serialization format (read & write)
MessagePack (Python package): More compact representation (read & write)
HDF5 (Python package): Nice for matrices (read & write)
XML: exists too *sigh* (read & write)
For your application, the following might be important:
Support by other programming languages
Reading / writing performance
Compactness (file size)
See also: Comparison of data serialization formats
In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python
A:
For those of you who are trying to dump greek or other "exotic" languages such as me but are also having problems (unicode errors) with weird characters such as the peace symbol (\u262E) or others which are often contained in json formated data such as Twitter's, the solution could be as follows (sort_keys is obviously optional):
import codecs, json
with codecs.open('data.json', 'w', 'utf8') as f:
f.write(json.dumps(data, sort_keys = True, ensure_ascii=False))
A:
I don't have enough reputation to add in comments, so I just write some of my findings of this annoying TypeError here:
Basically, I think it's a bug in the json.dump() function in Python 2 only - It can't dump a Python (dictionary / list) data containing non-ASCII characters, even you open the file with the encoding = 'utf-8' parameter. (i.e. No matter what you do). But, json.dumps() works on both Python 2 and 3.
To illustrate this, following up phihag's answer: the code in his answer breaks in Python 2 with exception TypeError: must be unicode, not str, if data contains non-ASCII characters. (Python 2.7.6, Debian):
import json
data = {u'\u0430\u0431\u0432\u0433\u0434': 1} #{u'абвгд': 1}
with open('data.txt', 'w') as outfile:
json.dump(data, outfile)
It however works fine in Python 3.
A:
Write a data in file using JSON use json.dump() or json.dumps() used.
write like this to store data in file.
import json
data = [1,2,3,4,5]
with open('no.txt', 'w') as txtfile:
json.dump(data, txtfile)
this example in list is store to a file.
A:
json.dump(data, open('data.txt', 'wb'))
A:
To write the JSON with indentation, "pretty print":
import json
outfile = open('data.json')
json.dump(data, outfile, indent=4)
Also, if you need to debug improperly formatted JSON, and want a helpful error message, use import simplejson library, instead of import json (functions should be the same)
A:
All previous answers are correct here is a very simple example:
#! /usr/bin/env python
import json
def write_json():
# create a dictionary
student_data = {"students":[]}
#create a list
data_holder = student_data["students"]
# just a counter
counter = 0
#loop through if you have multiple items..
while counter < 3:
data_holder.append({'id':counter})
data_holder.append({'room':counter})
counter += 1
#write the file
file_path='/tmp/student_data.json'
with open(file_path, 'w') as outfile:
print("writing file to: ",file_path)
# HERE IS WHERE THE MAGIC HAPPENS
json.dump(student_data, outfile)
outfile.close()
print("done")
write_json()
A:
if you are trying to write a pandas dataframe into a file using a json format i'd recommend this
destination='filepath'
saveFile = open(destination, 'w')
saveFile.write(df.to_json())
saveFile.close()
A:
The accepted answer is fine. However, I ran into "is not json serializable" error using that.
Here's how I fixed it
with open("file-name.json", 'w') as output:
output.write(str(response))
Although it is not a good fix as the json file it creates will not have double quotes, however it is great if you are looking for quick and dirty.
A:
The JSON data can be written to a file as follows
hist1 = [{'val_loss': [0.5139984398465246],
'val_acc': [0.8002029867684085],
'loss': [0.593220705309384],
'acc': [0.7687131817929321]},
{'val_loss': [0.46456472964199463],
'val_acc': [0.8173602046780344],
'loss': [0.4932038113037539],
'acc': [0.8063946213802453]}]
Write to a file:
with open('text1.json', 'w') as f:
json.dump(hist1, f)
A:
Before write a dictionary into a file as a json, you have to turn that dict onto json string using json library.
import json
data = {
"field1":{
"a": 10,
"b": 20,
},
"field2":{
"c": 30,
"d": 40,
},
}
json_data = json.dumps(json_data)
And also you can add indent to json data to look prettier.
json_data = json.dumps(json_data, indent=4)
If you want to sort keys before turning into json,
json_data = json.dumps(json_data, sort_keys=True)
You can use the combination of these two also.
Refer the json documentation here for much more features
Finally you can write into a json file
f = open('data.json', 'wb')
f.write(json_data)
A:
For people liking oneliners (hence with statement is not an option), a cleaner method than leaving a dangling opened file descriptor behind can be to use write_text from pathlib and do something like below:
pathlib.Path("data.txt").write_text(json.dumps(data))
This can be handy in some cases in contexts where statements are not allowed like:
[pathlib.Path(f"data_{x}.json").write_text(json.dumps(x)) for x in [1, 2, 3]]
I'm not claiming it should be preferred to with (and it's likely slower), just another option.
|
How do I write JSON data to a file?
|
How do I write JSON data stored in the dictionary data to a file?
f = open('data.json', 'wb')
f.write(data)
This gives the error:
TypeError: must be string or buffer, not dict
|
[
"data is a Python dictionary. It needs to be encoded as JSON before writing.\nUse this for maximum compatibility (Python 2 and 3):\nimport json\nwith open('data.json', 'w') as f:\n json.dump(data, f)\n\nOn a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using:\nimport json\nwith open('data.json', 'w', encoding='utf-8') as f:\n json.dump(data, f, ensure_ascii=False, indent=4)\n\nSee json documentation.\n",
"To get utf8-encoded file as opposed to ascii-encoded in the accepted answer for Python 2 use:\nimport io, json\nwith io.open('data.txt', 'w', encoding='utf-8') as f:\n f.write(json.dumps(data, ensure_ascii=False))\n\nThe code is simpler in Python 3:\nimport json\nwith open('data.txt', 'w') as f:\n json.dump(data, f, ensure_ascii=False)\n\nOn Windows, the encoding='utf-8' argument to open is still necessary.\nTo avoid storing an encoded copy of the data in memory (result of dumps) and to output utf8-encoded bytestrings in both Python 2 and 3, use:\nimport json, codecs\nwith open('data.txt', 'wb') as f:\n json.dump(data, codecs.getwriter('utf-8')(f), ensure_ascii=False)\n\nThe codecs.getwriter call is redundant in Python 3 but required for Python 2\n\nReadability and size:\nThe use of ensure_ascii=False gives better readability and smaller size:\n>>> json.dumps({'price': '€10'})\n'{\"price\": \"\\\\u20ac10\"}'\n>>> json.dumps({'price': '€10'}, ensure_ascii=False)\n'{\"price\": \"€10\"}'\n\n>>> len(json.dumps({'абвгд': 1}))\n37\n>>> len(json.dumps({'абвгд': 1}, ensure_ascii=False).encode('utf8'))\n17\n\nFurther improve readability by adding flags indent=4, sort_keys=True (as suggested by dinos66) to arguments of dump or dumps. This way you'll get a nicely indented sorted structure in the json file at the cost of a slightly larger file size.\n",
"I would answer with slight modification with aforementioned answers and that is to write a prettified JSON file which human eyes can read better. For this, pass sort_keys as True and indent with 4 space characters and you are good to go. Also take care of ensuring that the ascii codes will not be written in your JSON file:\nwith open('data.txt', 'w') as out_file:\n json.dump(json_data, out_file, sort_keys = True, indent = 4,\n ensure_ascii = False)\n\n",
"Read and write JSON files with Python 2+3; works with unicode\n# -*- coding: utf-8 -*-\nimport json\n\n# Make it work for Python 2+3 and with Unicode\nimport io\ntry:\n to_unicode = unicode\nexcept NameError:\n to_unicode = str\n\n# Define data\ndata = {'a list': [1, 42, 3.141, 1337, 'help', u'€'],\n 'a string': 'bla',\n 'another dict': {'foo': 'bar',\n 'key': 'value',\n 'the answer': 42}}\n\n# Write JSON file\nwith io.open('data.json', 'w', encoding='utf8') as outfile:\n str_ = json.dumps(data,\n indent=4, sort_keys=True,\n separators=(',', ': '), ensure_ascii=False)\n outfile.write(to_unicode(str_))\n\n# Read JSON file\nwith open('data.json') as data_file:\n data_loaded = json.load(data_file)\n\nprint(data == data_loaded)\n\nExplanation of the parameters of json.dump:\n\nindent: Use 4 spaces to indent each entry, e.g. when a new dict is started (otherwise all will be in one line),\nsort_keys: sort the keys of dictionaries. This is useful if you want to compare json files with a diff tool / put them under version control.\nseparators: To prevent Python from adding trailing whitespaces\n\nWith a package\nHave a look at my utility package mpu for a super simple and easy to remember one:\nimport mpu.io\ndata = mpu.io.read('example.json')\nmpu.io.write('example.json', data)\n\nCreated JSON file\n{\n \"a list\":[\n 1,\n 42,\n 3.141,\n 1337,\n \"help\",\n \"€\"\n ],\n \"a string\":\"bla\",\n \"another dict\":{\n \"foo\":\"bar\",\n \"key\":\"value\",\n \"the answer\":42\n }\n}\n\nCommon file endings\n.json\nAlternatives\n\nCSV: Super simple format (read & write)\nJSON: Nice for writing human-readable data; VERY commonly used (read & write)\nYAML: YAML is a superset of JSON, but easier to read (read & write, comparison of JSON and YAML)\npickle: A Python serialization format (read & write)\nMessagePack (Python package): More compact representation (read & write)\nHDF5 (Python package): Nice for matrices (read & write)\nXML: exists too *sigh* (read & write)\n\nFor your application, the following might be important:\n\nSupport by other programming languages\nReading / writing performance\nCompactness (file size)\n\nSee also: Comparison of data serialization formats\nIn case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python\n",
"For those of you who are trying to dump greek or other \"exotic\" languages such as me but are also having problems (unicode errors) with weird characters such as the peace symbol (\\u262E) or others which are often contained in json formated data such as Twitter's, the solution could be as follows (sort_keys is obviously optional):\nimport codecs, json\nwith codecs.open('data.json', 'w', 'utf8') as f:\n f.write(json.dumps(data, sort_keys = True, ensure_ascii=False))\n\n",
"I don't have enough reputation to add in comments, so I just write some of my findings of this annoying TypeError here:\nBasically, I think it's a bug in the json.dump() function in Python 2 only - It can't dump a Python (dictionary / list) data containing non-ASCII characters, even you open the file with the encoding = 'utf-8' parameter. (i.e. No matter what you do). But, json.dumps() works on both Python 2 and 3.\nTo illustrate this, following up phihag's answer: the code in his answer breaks in Python 2 with exception TypeError: must be unicode, not str, if data contains non-ASCII characters. (Python 2.7.6, Debian):\nimport json\ndata = {u'\\u0430\\u0431\\u0432\\u0433\\u0434': 1} #{u'абвгд': 1}\nwith open('data.txt', 'w') as outfile:\n json.dump(data, outfile)\n\nIt however works fine in Python 3.\n",
"Write a data in file using JSON use json.dump() or json.dumps() used.\nwrite like this to store data in file.\nimport json\ndata = [1,2,3,4,5]\nwith open('no.txt', 'w') as txtfile:\n json.dump(data, txtfile)\n\nthis example in list is store to a file.\n",
"json.dump(data, open('data.txt', 'wb'))\n\n",
"To write the JSON with indentation, \"pretty print\":\nimport json\n\noutfile = open('data.json')\njson.dump(data, outfile, indent=4)\n\nAlso, if you need to debug improperly formatted JSON, and want a helpful error message, use import simplejson library, instead of import json (functions should be the same)\n",
"All previous answers are correct here is a very simple example:\n#! /usr/bin/env python\nimport json\n\ndef write_json():\n # create a dictionary \n student_data = {\"students\":[]}\n #create a list\n data_holder = student_data[\"students\"]\n # just a counter\n counter = 0\n #loop through if you have multiple items.. \n while counter < 3:\n data_holder.append({'id':counter})\n data_holder.append({'room':counter})\n counter += 1 \n #write the file \n file_path='/tmp/student_data.json'\n with open(file_path, 'w') as outfile:\n print(\"writing file to: \",file_path)\n # HERE IS WHERE THE MAGIC HAPPENS \n json.dump(student_data, outfile)\n outfile.close() \n print(\"done\")\n\nwrite_json()\n\n\n",
"if you are trying to write a pandas dataframe into a file using a json format i'd recommend this\ndestination='filepath'\nsaveFile = open(destination, 'w')\nsaveFile.write(df.to_json())\nsaveFile.close()\n\n",
"The accepted answer is fine. However, I ran into \"is not json serializable\" error using that.\nHere's how I fixed it\nwith open(\"file-name.json\", 'w') as output:\noutput.write(str(response))\nAlthough it is not a good fix as the json file it creates will not have double quotes, however it is great if you are looking for quick and dirty.\n",
"The JSON data can be written to a file as follows \nhist1 = [{'val_loss': [0.5139984398465246],\n'val_acc': [0.8002029867684085],\n'loss': [0.593220705309384],\n'acc': [0.7687131817929321]},\n{'val_loss': [0.46456472964199463],\n'val_acc': [0.8173602046780344],\n'loss': [0.4932038113037539],\n'acc': [0.8063946213802453]}]\n\nWrite to a file:\nwith open('text1.json', 'w') as f:\n json.dump(hist1, f)\n\n",
"Before write a dictionary into a file as a json, you have to turn that dict onto json string using json library.\nimport json\n\ndata = {\n \"field1\":{\n \"a\": 10,\n \"b\": 20,\n },\n \"field2\":{\n \"c\": 30,\n \"d\": 40,\n },\n}\n\njson_data = json.dumps(json_data)\n\nAnd also you can add indent to json data to look prettier.\njson_data = json.dumps(json_data, indent=4)\n\nIf you want to sort keys before turning into json,\njson_data = json.dumps(json_data, sort_keys=True)\n\nYou can use the combination of these two also.\nRefer the json documentation here for much more features\nFinally you can write into a json file\nf = open('data.json', 'wb')\nf.write(json_data)\n\n",
"For people liking oneliners (hence with statement is not an option), a cleaner method than leaving a dangling opened file descriptor behind can be to use write_text from pathlib and do something like below:\npathlib.Path(\"data.txt\").write_text(json.dumps(data))\n\nThis can be handy in some cases in contexts where statements are not allowed like:\n[pathlib.Path(f\"data_{x}.json\").write_text(json.dumps(x)) for x in [1, 2, 3]]\n\nI'm not claiming it should be preferred to with (and it's likely slower), just another option.\n"
] |
[
2846,
305,
186,
129,
26,
13,
11,
8,
6,
5,
3,
3,
3,
2,
0
] |
[
"This is just an extra hint at the usage of json.dumps (this is not an answer to the problem of the question, but a trick for those who have to dump numpy data types):\nIf there are NumPy data types in the dictionary, json.dumps() needs an additional parameter, credits go to TypeError: Object of type 'ndarray' is not JSON serializable, and it will also fix errors like TypeError: Object of type int64 is not JSON serializable and so on:\nclass NumpyEncoder(json.JSONEncoder):\n \"\"\" Special json encoder for np types \"\"\"\n def default(self, obj):\n if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,\n np.int16, np.int32, np.int64, np.uint8,\n np.uint16, np.uint32, np.uint64)):\n return int(obj)\n elif isinstance(obj, (np.float_, np.float16, np.float32,\n np.float64)):\n return float(obj)\n elif isinstance(obj, (np.ndarray,)):\n return obj.tolist()\n return json.JSONEncoder.default(self, obj)\n\nAnd then run:\nimport json\n\n#print(json.dumps(my_data[:2], indent=4, cls=NumpyEncoder)))\nwith open(my_dir+'/my_filename.json', 'w') as f:\n json.dumps(my_data, indent=4, cls=NumpyEncoder)))\n\nYou may also want to return a string instead of a list in case of a np.array() since arrays are printed as lists that are spread over rows which will blow up the output if you have large or many arrays. The caveat: it is more difficult to access the items from the dumped dictionary later to get them back as the original array. Yet, if you do not mind having just a string of an array, this makes the dictionary more readable. Then exchange:\n elif isinstance(obj, (np.ndarray,)):\n return obj.tolist()\n\nwith:\n elif isinstance(obj, (np.ndarray,)):\n return str(obj)\n\nor just:\n else:\n return str(obj)\n\n"
] |
[
-1
] |
[
"json",
"python"
] |
stackoverflow_0012309269_json_python.txt
|
Q:
Can Tkinter ask for input from a different page?
I am trying to create a gui with tkinter where I am being redirected to different pages and I want those different pages to ask for different inputs and do different functions. As of now I still can't fix it I am just using this tkinter as of today so I am new.
what I envision is:
Page 1: ask student section
Page 2: ask for something else
Page 3: ask for something else again
although it seems to display it for all the pages.
I tried changing the values of the win in the tk.label to the page value to maybe display it on the page itself although it will result in a blank so I reverted it.
This is the output if I go to other pages.
page 1
page 2
for page 3 it is the same as the first two.
This is the code that I have used.
import tkinter as tk
from tkinter import *
from tkinter import font
import os
import cv2
win = tk.Tk()
style1 = font.Font(size=25)
page1 = Frame(win)
page2 = Frame(win)
page3 = Frame(win)
page1.grid(row = 0, column = 0, sticky="nsew")
page2.grid(row = 0, column = 0, sticky="nsew")
page3.grid(row = 0, column = 0, sticky="nsew")
lbl1 =Label(page1, text = " This is Page 1", font=style1)
lbl1.pack(pady=20)
lbl2 =Label(page2, text = "This is Page 2", font=style1)
lbl2.pack(pady=30)
lbl3 =Label(page3, text = " This is Page 3", font=style1)
lbl3.pack(pady=50)
lbl1p2 = tk.Label(win, text="Enter Section", width=20 , height=2 , fg="black" , bg="white", font=('times', 15, ' bold ') )
lbl1p2.place(x=300, y=200)
txt1 = tk.Entry(win, width=20, bg="white", fg="black", font=('times', 15, ' bold '))
txt1.place(x=550, y=215)
btn1 = Button(page1, text = "Show page 2", command = lambda: page2.tkraise(), font = style1)
btn1.pack()
btn1p2 = Button(page1, text = "Show page 3", command = lambda: page3.tkraise(), font = style1)
btn1p2.pack()
message1 = tk.Label(win, text="", bg="white", fg="black", width=30, height=2, font=('times', 15, ' bold '))
message1.place(x=550, y=400)
btn2 = Button(page2, text = "Show page 1", command = lambda: page1.tkraise(), font = style1)
btn3 = Button(page2, text = "Show page 3", command = lambda: page3.tkraise(), font = style1)
btn2.pack()
btn3.pack()
btn4 = Button(page3, text="Show page 1", command= lambda: page1.tkraise(),font=style1)
btn5 = Button(page3, text="Show page 2", command= lambda: page2.tkraise(),font=style1)
btn4.pack()
btn5.pack()
def getfolder():
while True:
dataset_folder = input("Please input the section of the students: ")
if not os.path.exists(dataset_folder):
print("Datasets folder does not exist")
else:
print("Folder found...")
break
page1.tkraise()
win.geometry("1200x600")
win.title("Main menu")
win.resizable(False, False)
win.mainloop()
A:
First of all you should seperate your pages. Like these situations, using OOP would be life saver. Creating instance or class per page will solve problems.
first of all lets create a base page class that will have everything we need.
class Page:
def __init__(self,frame,pageName):
self.pageName = pageName
self.frame = frame
def _LoadPage(self):
#clear inside frame
for child in self.frame.winfo_children():
child.destroy()
This way, we will get container frame and we will empty it before fill everytime new page opened.
this is an example student page class
class StudentPage(Page):
def __init__(self,frame,pageName,studentName):
super().__init__(frame,pageName)
self.__studentValues = {"Student Name":studentName}
def loadPage(self):
#do studentPage placement.
self._LoadPage()
row = 0
for i,j in self.__studentValues.items():
tk.Label(self.frame,text=f"{i}: {j}").grid(row=row,column=0)
row += 1
as you can see here you can have information of student in a dictionary like studentvalues.
class OtherPage(Page):
def __init__(self,frame,pageName):
Page.__init__(self,frame,pageName)
self.pressTimes = 1
def loadPage(self):
#do other Page things.
super()._LoadPage()
self.label = tk.Button(self.frame,text=f"Button pressed {self.pressTimes} times")
self.label.grid(row=0,column=0)
self.__button = tk.Button(self.frame,command=self.doButtonThings,text="Press button to increase")
self.__button.grid(row=1,column=0)
def doButtonThings(self):
self.pressTimes += 1
self.label["text"] = f"Button pressed {self.pressTimes} times"
This is an example for other pages. It keeps how many times you have pressed buttons. Even though you have changed pages it keeps in its memory.
finally create mainwindow, instances etc.
win = tk.Tk()
style1 = font.Font(size=25)
#left part would be like a menu
buttonsFrame = tk.Frame(win)
buttonsFrame.place(relx=0,rely=0,relheight=1,relwidth=0.3)
#right side will be a place where content will be shown
layoutFrame = tk.Frame(win)
layoutFrame.place(relx=0.3,rely=0,relheight=1,relwidth=0.7)
#create pages
sp = StudentPage(layoutFrame,"Student Page","Nasur")
op = OtherPage(layoutFrame, "a page")
studentButton = tk.Button(buttonsFrame,text="Load student Page",command=sp.loadPage)
studentButton.grid(row=0,column=0)
otherButton = tk.Button(buttonsFrame,text="Load other Page",command=op.loadPage)
otherButton.grid(row=1,column=0)
win.geometry("1200x600")
win.title("Main menu")
win.resizable(False, False)
win.mainloop()
Everytime you change a page, base class load page method called and frame cleared.
Your load page method will fill the page as you desired. Also as it's a class pages can their own methods and variables, arrays, dictionaries.
|
Can Tkinter ask for input from a different page?
|
I am trying to create a gui with tkinter where I am being redirected to different pages and I want those different pages to ask for different inputs and do different functions. As of now I still can't fix it I am just using this tkinter as of today so I am new.
what I envision is:
Page 1: ask student section
Page 2: ask for something else
Page 3: ask for something else again
although it seems to display it for all the pages.
I tried changing the values of the win in the tk.label to the page value to maybe display it on the page itself although it will result in a blank so I reverted it.
This is the output if I go to other pages.
page 1
page 2
for page 3 it is the same as the first two.
This is the code that I have used.
import tkinter as tk
from tkinter import *
from tkinter import font
import os
import cv2
win = tk.Tk()
style1 = font.Font(size=25)
page1 = Frame(win)
page2 = Frame(win)
page3 = Frame(win)
page1.grid(row = 0, column = 0, sticky="nsew")
page2.grid(row = 0, column = 0, sticky="nsew")
page3.grid(row = 0, column = 0, sticky="nsew")
lbl1 =Label(page1, text = " This is Page 1", font=style1)
lbl1.pack(pady=20)
lbl2 =Label(page2, text = "This is Page 2", font=style1)
lbl2.pack(pady=30)
lbl3 =Label(page3, text = " This is Page 3", font=style1)
lbl3.pack(pady=50)
lbl1p2 = tk.Label(win, text="Enter Section", width=20 , height=2 , fg="black" , bg="white", font=('times', 15, ' bold ') )
lbl1p2.place(x=300, y=200)
txt1 = tk.Entry(win, width=20, bg="white", fg="black", font=('times', 15, ' bold '))
txt1.place(x=550, y=215)
btn1 = Button(page1, text = "Show page 2", command = lambda: page2.tkraise(), font = style1)
btn1.pack()
btn1p2 = Button(page1, text = "Show page 3", command = lambda: page3.tkraise(), font = style1)
btn1p2.pack()
message1 = tk.Label(win, text="", bg="white", fg="black", width=30, height=2, font=('times', 15, ' bold '))
message1.place(x=550, y=400)
btn2 = Button(page2, text = "Show page 1", command = lambda: page1.tkraise(), font = style1)
btn3 = Button(page2, text = "Show page 3", command = lambda: page3.tkraise(), font = style1)
btn2.pack()
btn3.pack()
btn4 = Button(page3, text="Show page 1", command= lambda: page1.tkraise(),font=style1)
btn5 = Button(page3, text="Show page 2", command= lambda: page2.tkraise(),font=style1)
btn4.pack()
btn5.pack()
def getfolder():
while True:
dataset_folder = input("Please input the section of the students: ")
if not os.path.exists(dataset_folder):
print("Datasets folder does not exist")
else:
print("Folder found...")
break
page1.tkraise()
win.geometry("1200x600")
win.title("Main menu")
win.resizable(False, False)
win.mainloop()
|
[
"First of all you should seperate your pages. Like these situations, using OOP would be life saver. Creating instance or class per page will solve problems.\nfirst of all lets create a base page class that will have everything we need.\nclass Page:\n def __init__(self,frame,pageName):\n self.pageName = pageName\n self.frame = frame\n\n def _LoadPage(self):\n #clear inside frame\n for child in self.frame.winfo_children():\n child.destroy()\n\nThis way, we will get container frame and we will empty it before fill everytime new page opened.\nthis is an example student page class\nclass StudentPage(Page):\n def __init__(self,frame,pageName,studentName):\n super().__init__(frame,pageName)\n self.__studentValues = {\"Student Name\":studentName}\n def loadPage(self):\n #do studentPage placement.\n self._LoadPage()\n row = 0\n for i,j in self.__studentValues.items():\n tk.Label(self.frame,text=f\"{i}: {j}\").grid(row=row,column=0)\n row += 1\n\nas you can see here you can have information of student in a dictionary like studentvalues.\nclass OtherPage(Page):\n def __init__(self,frame,pageName):\n Page.__init__(self,frame,pageName)\n self.pressTimes = 1\n\n def loadPage(self):\n #do other Page things.\n super()._LoadPage()\n self.label = tk.Button(self.frame,text=f\"Button pressed {self.pressTimes} times\")\n self.label.grid(row=0,column=0)\n\n self.__button = tk.Button(self.frame,command=self.doButtonThings,text=\"Press button to increase\")\n self.__button.grid(row=1,column=0)\n\n\n def doButtonThings(self):\n self.pressTimes += 1\n self.label[\"text\"] = f\"Button pressed {self.pressTimes} times\"\n\nThis is an example for other pages. It keeps how many times you have pressed buttons. Even though you have changed pages it keeps in its memory.\nfinally create mainwindow, instances etc.\nwin = tk.Tk()\nstyle1 = font.Font(size=25)\n\n#left part would be like a menu\nbuttonsFrame = tk.Frame(win)\nbuttonsFrame.place(relx=0,rely=0,relheight=1,relwidth=0.3)\n\n#right side will be a place where content will be shown\nlayoutFrame = tk.Frame(win)\nlayoutFrame.place(relx=0.3,rely=0,relheight=1,relwidth=0.7)\n\n#create pages\nsp = StudentPage(layoutFrame,\"Student Page\",\"Nasur\")\nop = OtherPage(layoutFrame, \"a page\")\n\nstudentButton = tk.Button(buttonsFrame,text=\"Load student Page\",command=sp.loadPage)\nstudentButton.grid(row=0,column=0)\n\notherButton = tk.Button(buttonsFrame,text=\"Load other Page\",command=op.loadPage)\notherButton.grid(row=1,column=0)\n\nwin.geometry(\"1200x600\")\nwin.title(\"Main menu\")\nwin.resizable(False, False)\nwin.mainloop()\n\nEverytime you change a page, base class load page method called and frame cleared.\nYour load page method will fill the page as you desired. Also as it's a class pages can their own methods and variables, arrays, dictionaries.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"python_3.x",
"tkinter"
] |
stackoverflow_0074565423_python_python_3.x_tkinter.txt
|
Q:
PostgresSQL connection refused on docker container in same server
I have postgresSQL database running docker on server when i spin up another container for django app and trying to connect postgress getting connection error. any idea?
django.db.utils.OperationalError: connection to server at "localhost" (127.0.0.1), port 6545 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (::1), port 6545 failed: Cannot assign requested address
Is the server running on that host and accepting TCP/IP connections?
DB docker file
container_name: pg-docker
ports:
- "6545:5432"
volumes:
- ./data:/var/lib/postgresql/data
networks:
- default
Django docker file
version: "3.9"
services:
django_api:
build:
context: ./app
dockerfile: Dockerfile
container_name: api-dev
command: python manage.py runserver 0.0.0.0:8000
ports:
- 8000:8000
networks:
- default
A:
As @JustLudo said in the Comments, you have to address postgres with the container name "pg-docker". Localhost would be your django container.
In general, if you use multiple docker containers you should not use localhost. Instead treat every container as a standalone server and address via DNS / container_name.
|
PostgresSQL connection refused on docker container in same server
|
I have postgresSQL database running docker on server when i spin up another container for django app and trying to connect postgress getting connection error. any idea?
django.db.utils.OperationalError: connection to server at "localhost" (127.0.0.1), port 6545 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (::1), port 6545 failed: Cannot assign requested address
Is the server running on that host and accepting TCP/IP connections?
DB docker file
container_name: pg-docker
ports:
- "6545:5432"
volumes:
- ./data:/var/lib/postgresql/data
networks:
- default
Django docker file
version: "3.9"
services:
django_api:
build:
context: ./app
dockerfile: Dockerfile
container_name: api-dev
command: python manage.py runserver 0.0.0.0:8000
ports:
- 8000:8000
networks:
- default
|
[
"As @JustLudo said in the Comments, you have to address postgres with the container name \"pg-docker\". Localhost would be your django container.\nIn general, if you use multiple docker containers you should not use localhost. Instead treat every container as a standalone server and address via DNS / container_name.\n"
] |
[
0
] |
[] |
[] |
[
"django",
"docker",
"docker_compose",
"postgresql",
"python"
] |
stackoverflow_0074570161_django_docker_docker_compose_postgresql_python.txt
|
Q:
Get the inverse of a dataframe column in terms of rows with NaN values
I have an original dataframe df0 with a number of values, based on this dataframe I have a second dateframe where some the original values are NaN, df1.
import pandas as pd
df0 = pd.DataFrame({'col1': [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]})
df1 = pd.DataFrame({'col1': [1,2,None,4,5,6,None,8,None,10,11,None,13,None,None]})
I need a df2 to be the inverse of df1 in terms of rows with NaN. Every row which is NaN in df1 should get its original value back from df0 and rows which are not NaN must become NaN such that I get the following dataframe:
df2 = pd.DataFrame({'col1': [None,None,3,None,None,None,7,None,9,None,None,12,None,14,15]})
What is the best way to go about this if it were a larger dataset?
A:
masking all columns
If you need to mask all columns, use mask + notna OR where + isna:
df2 = df0.mask(df1['col1'].notna())
# or
df2 = df0.where(df1['col1'].isna())
output:
col1
0 NaN
1 NaN
2 3.0
3 NaN
4 NaN
5 NaN
6 7.0
7 NaN
8 9.0
9 NaN
10 NaN
11 12.0
12 NaN
13 14.0
14 15.0
masking only "col1"
If you just need to replace col1 and leave potential other columns intact rather use assign and Series.mask:
df2 = df0.assign(col1=df0['col1'].mask(df1['col1'].notna()))
A:
Use Series.where with Series.isna for replace one column by another DataFrame, only necessary same index in both:
df0['col1'] = df0['col1'].where(df1['col1'].isna())
print (df0)
col1
0 NaN
1 NaN
2 3.0
3 NaN
4 NaN
5 NaN
6 7.0
7 NaN
8 9.0
9 NaN
10 NaN
11 12.0
12 NaN
13 14.0
14 15.0
Alternative with DataFrame.loc and Series.notna:
df0.loc[df1['col1'].notna(), 'col1'] = np.nan
|
Get the inverse of a dataframe column in terms of rows with NaN values
|
I have an original dataframe df0 with a number of values, based on this dataframe I have a second dateframe where some the original values are NaN, df1.
import pandas as pd
df0 = pd.DataFrame({'col1': [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]})
df1 = pd.DataFrame({'col1': [1,2,None,4,5,6,None,8,None,10,11,None,13,None,None]})
I need a df2 to be the inverse of df1 in terms of rows with NaN. Every row which is NaN in df1 should get its original value back from df0 and rows which are not NaN must become NaN such that I get the following dataframe:
df2 = pd.DataFrame({'col1': [None,None,3,None,None,None,7,None,9,None,None,12,None,14,15]})
What is the best way to go about this if it were a larger dataset?
|
[
"masking all columns\nIf you need to mask all columns, use mask + notna OR where + isna:\ndf2 = df0.mask(df1['col1'].notna())\n# or\ndf2 = df0.where(df1['col1'].isna())\n\noutput:\n col1\n0 NaN\n1 NaN\n2 3.0\n3 NaN\n4 NaN\n5 NaN\n6 7.0\n7 NaN\n8 9.0\n9 NaN\n10 NaN\n11 12.0\n12 NaN\n13 14.0\n14 15.0\n\nmasking only \"col1\"\nIf you just need to replace col1 and leave potential other columns intact rather use assign and Series.mask:\ndf2 = df0.assign(col1=df0['col1'].mask(df1['col1'].notna()))\n\n",
"Use Series.where with Series.isna for replace one column by another DataFrame, only necessary same index in both:\ndf0['col1'] = df0['col1'].where(df1['col1'].isna())\nprint (df0)\n col1\n0 NaN\n1 NaN\n2 3.0\n3 NaN\n4 NaN\n5 NaN\n6 7.0\n7 NaN\n8 9.0\n9 NaN\n10 NaN\n11 12.0\n12 NaN\n13 14.0\n14 15.0\n\nAlternative with DataFrame.loc and Series.notna:\ndf0.loc[df1['col1'].notna(), 'col1'] = np.nan\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074570974_dataframe_pandas_python.txt
|
Q:
How to extract information from atom feed based on condition?
I have output of API request in given below.
From each atom:entry I need to extract
<c:series href="http://company.com/series/product/123"/>
<c:series-order>2020-09-17T00:00:00Z</c:series-order>
<f:assessment-low precision="0">980</f:assessment-low>
I tried to extract them to different list with BeautifulSoup, but that wasn't successful because in some entries there are dates but there isn't price (I've shown example below). How could I conditionally extract it? at least put N/A for entries where price is ommited.
soup = BeautifulSoup(request.text, "html.parser")
date = soup.find_all('c:series-order')
value = soup.find_all('f:assessment-low')
quot=soup.find_all('c:series')
p_day = []
p_val = []
q_val=[]
for i in date:
p_day.append(i.text)
for j in value:
p_val.append(j.text)
for j in quot:
q_val.append(j.get('href'))
d2={'date': p_day,
'price': p_val,
'quote': q_val
}
and
<atom:feed xmlns:atom="http://www.w3.org/2005/Atom" xmlns:a="http://company.com/ns/assets" xmlns:c="http://company.com/ns/core" xmlns:f="http://company.com/ns/fields" xmlns:s="http://company.com/ns/search">
<atom:id>http://company.com/search</atom:id>
<atom:title> COMPANYSearch Results</atom:title>
<atom:updated>2022-11-24T19:36:19.104414Z</atom:updated>
<atom:author>COMPANY atom:author>
<atom:generator> COMPANY/search Endpoint</atom:generator>
<atom:link href="/search" rel="self" type="application/atom"/>
<s:first-result>1</s:first-result>
<s:max-results>15500</s:max-results>
<s:selected-count>212</s:selected-count>
<s:returned-count>212</s:returned-count>
<s:query-time>PT0.036179S</s:query-time>
<s:request version="1.0">
<s:scope>
<s:series>http://company.com/series/product/123</s:series>
</s:scope>
<s:constraints>
<s:compare field="c:series-order" op="ge" value="2018-10-01"/>
<s:compare field="c:series-order" op="le" value="2022-11-18"/>
</s:constraints>
<s:options>
<s:first-result>1</s:first-result>
<s:max-results>15500</s:max-results>
<s:order-by key="commodity-name" direction="ascending" xml:lang="en"/>
<s:no-currency-rate-scheme>no-element</s:no-currency-rate-scheme>
<s:precision>embed</s:precision>
<s:include-last-commit-time>false</s:include-last-commit-time>
<s:include-result-types>live</s:include-result-types>
<s:relevance-score algorithm="score-logtfidf"/>
<s:lang-data-missing-scheme>show-available-language-content</s:lang-data-missing-scheme>
</s:options>
</s:request>
<s:facets/>
<atom:entry>
<atom:title>http://company.com/series-item/product/123-pricehistory-20200917000000</atom:title>
<atom:id>http://company.com/series-item/product/123-pricehistory-20200917000000</atom:id>
<atom:updated>2020-09-17T17:09:43.55243Z</atom:updated>
<atom:relevance-score>60800</atom:relevance-score>
<atom:content type="application/vnd.icis.iddn.entity+xml"><a:price-range>
<c:id>http://company.com/series-item/product/123-pricehistory-20200917000000</c:id>
<c:version>1</c:version>
<c:type>series-item</c:type>
<c:created-on>2020-09-17T17:09:43.55243Z</c:created-on>
<c:descriptor href="http://company.com/descriptor/price-range"/>
<c:domain href="http://company.com/domain/product"/>
<c:released-on>2020-09-17T21:30:00Z</c:released-on>
<c:series href="http://company.com/series/product/123"/>
<c:series-order>2020-09-17T00:00:00Z</c:series-order>
<f:assessment-low precision="0">980</f:assessment-low>
<f:assessment-high precision="0">1020</f:assessment-high>
<f:mid precision="1">1000</f:mid>
<f:assessment-low-delta>0</f:assessment-low-delta>
<f:assessment-high-delta>+20</f:assessment-high-delta>
<f:delta-type href="http://company.com/ref-data/delta-type/regular"/>
</a:price-range></atom:content>
</atom:entry>
<atom:entry>
<atom:title>http://company.com/series-item/product/123-pricehistory-20200910000000</atom:title>
<atom:id>http://company.com/series-item/product/123-pricehistory-20200910000000</atom:id>
<atom:updated>2020-09-10T18:57:55.128308Z</atom:updated>
<atom:relevance-score>60800</atom:relevance-score>
<atom:content type="application/vnd.icis.iddn.entity+xml"><a:price-range>
<c:id>http://company.com/series-item/product/123-pricehistory-20200910000000</c:id>
<c:version>1</c:version>
<c:type>series-item</c:type>
<c:created-on>2020-09-10T18:57:55.128308Z</c:created-on>
<c:descriptor href="http://company.com/descriptor/price-range"/>
<c:domain href="http://company.com/domain/product"/>
<c:released-on>2020-09-10T21:30:00Z</c:released-on>
<c:series href="http://company.com/series/product/123"/>
<c:series-order>2020-09-10T00:00:00Z</c:series-order>
for example here is no price
<f:delta-type href="http://company.com/ref-data/delta-type/regular"/>
</a:price-range></atom:content>
</atom:entry>
A:
May try to iterate per entry, use xml parser to get a propper result and check if element exists:
soup = BeautifulSoup(request.text,'xml')
data = []
for i in soup.select('entry'):
data.append({
'date':i.find('series-order').text,
'value': i.find('assessment-low').text if i.find('assessment-low') else None,
'quot': i.find('series').get('href')
})
data
or with html.parser:
soup = BeautifulSoup(xml,'html.parser')
data = []
for i in soup.find_all('atom:entry'):
data.append({
'date':i.find('c:series-order').text,
'value': i.find('f:assessment-low').text if i.find('assessment-low') else None,
'quot': i.find('c:series').get('href')
})
data
Output:
[{'date': '2020-09-17T00:00:00Z',
'value': '980',
'quot': 'http://company.com/series/product/123'},
{'date': '2020-09-10T00:00:00Z',
'value': None,
'quot': 'http://company.com/series/product/123'}]
A:
You can try this:
split your request.text by <atom:entry>
deal with each section seperately.
Use enumerate to identify the section that it came from
entries = request.text.split("<atom:entry>")
p_day = []
p_val = []
q_val=[]
for i, entry in enumerate(entries):
soup = BeautifulSoup(entry, "html.parser")
date = soup.find_all('c:series-order')
value = soup.find_all('f:assessment-low')
quot=soup.find_all('c:series')
for d in date:
p_day.append([i, d.text])
for v in value:
p_val.append([i, v.text])
for q in quot:
q_val.append([i, q.get('href')])
d2={'date': p_day,
'price': p_val,
'quote': q_val
}
print(d2)
OUTPUT:
{'date': [[1, '2020-09-17T00:00:00Z'], [2, '2020-09-10T00:00:00Z']],
'price': [[1, '980']],
'quote': [[1, 'http://company.com/series/product/123'],
[2, 'http://company.com/series/product/123']]}
|
How to extract information from atom feed based on condition?
|
I have output of API request in given below.
From each atom:entry I need to extract
<c:series href="http://company.com/series/product/123"/>
<c:series-order>2020-09-17T00:00:00Z</c:series-order>
<f:assessment-low precision="0">980</f:assessment-low>
I tried to extract them to different list with BeautifulSoup, but that wasn't successful because in some entries there are dates but there isn't price (I've shown example below). How could I conditionally extract it? at least put N/A for entries where price is ommited.
soup = BeautifulSoup(request.text, "html.parser")
date = soup.find_all('c:series-order')
value = soup.find_all('f:assessment-low')
quot=soup.find_all('c:series')
p_day = []
p_val = []
q_val=[]
for i in date:
p_day.append(i.text)
for j in value:
p_val.append(j.text)
for j in quot:
q_val.append(j.get('href'))
d2={'date': p_day,
'price': p_val,
'quote': q_val
}
and
<atom:feed xmlns:atom="http://www.w3.org/2005/Atom" xmlns:a="http://company.com/ns/assets" xmlns:c="http://company.com/ns/core" xmlns:f="http://company.com/ns/fields" xmlns:s="http://company.com/ns/search">
<atom:id>http://company.com/search</atom:id>
<atom:title> COMPANYSearch Results</atom:title>
<atom:updated>2022-11-24T19:36:19.104414Z</atom:updated>
<atom:author>COMPANY atom:author>
<atom:generator> COMPANY/search Endpoint</atom:generator>
<atom:link href="/search" rel="self" type="application/atom"/>
<s:first-result>1</s:first-result>
<s:max-results>15500</s:max-results>
<s:selected-count>212</s:selected-count>
<s:returned-count>212</s:returned-count>
<s:query-time>PT0.036179S</s:query-time>
<s:request version="1.0">
<s:scope>
<s:series>http://company.com/series/product/123</s:series>
</s:scope>
<s:constraints>
<s:compare field="c:series-order" op="ge" value="2018-10-01"/>
<s:compare field="c:series-order" op="le" value="2022-11-18"/>
</s:constraints>
<s:options>
<s:first-result>1</s:first-result>
<s:max-results>15500</s:max-results>
<s:order-by key="commodity-name" direction="ascending" xml:lang="en"/>
<s:no-currency-rate-scheme>no-element</s:no-currency-rate-scheme>
<s:precision>embed</s:precision>
<s:include-last-commit-time>false</s:include-last-commit-time>
<s:include-result-types>live</s:include-result-types>
<s:relevance-score algorithm="score-logtfidf"/>
<s:lang-data-missing-scheme>show-available-language-content</s:lang-data-missing-scheme>
</s:options>
</s:request>
<s:facets/>
<atom:entry>
<atom:title>http://company.com/series-item/product/123-pricehistory-20200917000000</atom:title>
<atom:id>http://company.com/series-item/product/123-pricehistory-20200917000000</atom:id>
<atom:updated>2020-09-17T17:09:43.55243Z</atom:updated>
<atom:relevance-score>60800</atom:relevance-score>
<atom:content type="application/vnd.icis.iddn.entity+xml"><a:price-range>
<c:id>http://company.com/series-item/product/123-pricehistory-20200917000000</c:id>
<c:version>1</c:version>
<c:type>series-item</c:type>
<c:created-on>2020-09-17T17:09:43.55243Z</c:created-on>
<c:descriptor href="http://company.com/descriptor/price-range"/>
<c:domain href="http://company.com/domain/product"/>
<c:released-on>2020-09-17T21:30:00Z</c:released-on>
<c:series href="http://company.com/series/product/123"/>
<c:series-order>2020-09-17T00:00:00Z</c:series-order>
<f:assessment-low precision="0">980</f:assessment-low>
<f:assessment-high precision="0">1020</f:assessment-high>
<f:mid precision="1">1000</f:mid>
<f:assessment-low-delta>0</f:assessment-low-delta>
<f:assessment-high-delta>+20</f:assessment-high-delta>
<f:delta-type href="http://company.com/ref-data/delta-type/regular"/>
</a:price-range></atom:content>
</atom:entry>
<atom:entry>
<atom:title>http://company.com/series-item/product/123-pricehistory-20200910000000</atom:title>
<atom:id>http://company.com/series-item/product/123-pricehistory-20200910000000</atom:id>
<atom:updated>2020-09-10T18:57:55.128308Z</atom:updated>
<atom:relevance-score>60800</atom:relevance-score>
<atom:content type="application/vnd.icis.iddn.entity+xml"><a:price-range>
<c:id>http://company.com/series-item/product/123-pricehistory-20200910000000</c:id>
<c:version>1</c:version>
<c:type>series-item</c:type>
<c:created-on>2020-09-10T18:57:55.128308Z</c:created-on>
<c:descriptor href="http://company.com/descriptor/price-range"/>
<c:domain href="http://company.com/domain/product"/>
<c:released-on>2020-09-10T21:30:00Z</c:released-on>
<c:series href="http://company.com/series/product/123"/>
<c:series-order>2020-09-10T00:00:00Z</c:series-order>
for example here is no price
<f:delta-type href="http://company.com/ref-data/delta-type/regular"/>
</a:price-range></atom:content>
</atom:entry>
|
[
"May try to iterate per entry, use xml parser to get a propper result and check if element exists:\nsoup = BeautifulSoup(request.text,'xml')\ndata = []\nfor i in soup.select('entry'):\n data.append({\n 'date':i.find('series-order').text,\n 'value': i.find('assessment-low').text if i.find('assessment-low') else None,\n 'quot': i.find('series').get('href')\n })\ndata\n\nor with html.parser:\nsoup = BeautifulSoup(xml,'html.parser')\ndata = []\nfor i in soup.find_all('atom:entry'):\n data.append({\n 'date':i.find('c:series-order').text,\n 'value': i.find('f:assessment-low').text if i.find('assessment-low') else None,\n 'quot': i.find('c:series').get('href')\n })\ndata\n\nOutput:\n[{'date': '2020-09-17T00:00:00Z',\n 'value': '980',\n 'quot': 'http://company.com/series/product/123'},\n {'date': '2020-09-10T00:00:00Z',\n 'value': None,\n 'quot': 'http://company.com/series/product/123'}]\n\n",
"You can try this:\n\nsplit your request.text by <atom:entry>\ndeal with each section seperately.\nUse enumerate to identify the section that it came from\n\nentries = request.text.split(\"<atom:entry>\")\n\np_day = []\np_val = []\nq_val=[]\n\nfor i, entry in enumerate(entries):\n soup = BeautifulSoup(entry, \"html.parser\")\n date = soup.find_all('c:series-order')\n value = soup.find_all('f:assessment-low')\n quot=soup.find_all('c:series')\n\n\n for d in date:\n p_day.append([i, d.text])\n for v in value:\n p_val.append([i, v.text])\n for q in quot:\n q_val.append([i, q.get('href')])\n\nd2={'date': p_day,\n 'price': p_val,\n 'quote': q_val\n }\n\nprint(d2)\n\nOUTPUT:\n{'date': [[1, '2020-09-17T00:00:00Z'], [2, '2020-09-10T00:00:00Z']],\n 'price': [[1, '980']],\n 'quote': [[1, 'http://company.com/series/product/123'],\n [2, 'http://company.com/series/product/123']]}\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"atom_feed",
"beautifulsoup",
"python"
] |
stackoverflow_0074570699_atom_feed_beautifulsoup_python.txt
|
Q:
Returning values from a function :(
Please can someone explain what's going wrong here?
Unfortunately, I have been tasked to complete this using a function; otherwise, I would've used a built-in function like count()
Thanks!
scores = [3,7,6,9,4,3,5,2,6,8]
y = int(input("What score are you searching for in the scores array? "))
a = len(scores)
z = False
def count1(c,b):
for d in range(0,c):
if scores[d] == y:
print("yes")
b = True
return(b)
else:
print("no")
count1(a,z)
if z == True:
print(y, "occurs in the array")
else:
print(y, "does not occur in the array")
my code^
Python 3.7.5 (tags/v3.7.5:5c02a39a0b, Oct 15 2019, 00:11:34) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
= RESTART: C:\Users\18skeffingtonc\
What score are you searching for in the scores array? 3
yes
3 does not occur in the array
the output, after entering what should be a valid input^
A:
The basic fix to your immediate problem is to modify the line count1(a, z) to read z = count1(a, z).
That way, you give z to your count1, allow count1 to modify z, and then overwrite the old value of z with the new value generated by your count1.
That said, you have a lot going on in your code that you don't really need. One concise way to do what you're attempting would be:
scores = [3,7,6,9,4,3,5,2,6,8]
def count1(scores):
y = int(input("What score are you searching for in the scores array? "))
print (f'{y} is {"" if y in scores else "not "}in the array.')
count1(scores)
Trying this out:
What score are you searching for in the scores array? 3
3 is in the array.
What score are you searching for in the scores array? 12
12 is not in the array.
|
Returning values from a function :(
|
Please can someone explain what's going wrong here?
Unfortunately, I have been tasked to complete this using a function; otherwise, I would've used a built-in function like count()
Thanks!
scores = [3,7,6,9,4,3,5,2,6,8]
y = int(input("What score are you searching for in the scores array? "))
a = len(scores)
z = False
def count1(c,b):
for d in range(0,c):
if scores[d] == y:
print("yes")
b = True
return(b)
else:
print("no")
count1(a,z)
if z == True:
print(y, "occurs in the array")
else:
print(y, "does not occur in the array")
my code^
Python 3.7.5 (tags/v3.7.5:5c02a39a0b, Oct 15 2019, 00:11:34) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
= RESTART: C:\Users\18skeffingtonc\
What score are you searching for in the scores array? 3
yes
3 does not occur in the array
the output, after entering what should be a valid input^
|
[
"The basic fix to your immediate problem is to modify the line count1(a, z) to read z = count1(a, z).\nThat way, you give z to your count1, allow count1 to modify z, and then overwrite the old value of z with the new value generated by your count1.\nThat said, you have a lot going on in your code that you don't really need. One concise way to do what you're attempting would be:\nscores = [3,7,6,9,4,3,5,2,6,8]\n\ndef count1(scores):\n y = int(input(\"What score are you searching for in the scores array? \"))\n print (f'{y} is {\"\" if y in scores else \"not \"}in the array.')\n \ncount1(scores)\n\nTrying this out:\nWhat score are you searching for in the scores array? 3\n3 is in the array.\n\nWhat score are you searching for in the scores array? 12\n12 is not in the array.\n\n"
] |
[
0
] |
[] |
[] |
[
"boolean",
"boolean_logic",
"function",
"parameters",
"python"
] |
stackoverflow_0074570782_boolean_boolean_logic_function_parameters_python.txt
|
Q:
Remove ")" from cells in list if ")" exists
Could you please tell me how can I remove ")" from strings in a list without converting the list to a string? Example:
Input:
list =[
'ABDDDDC 1,000 IWJBCKNBCDVV',
'BDISJBJ 2,000 DBFIAJDBDIAJ',
'JDBISJB 5,000 AHSBIEFEWEFJ)', # there is a parenthesis at the end
'CONDDDD 7,000 4DJVBDISJEVV)'] # there is a parenthesis at the end
Expected output:
list =[
'ABDDDDC 1,000 IWJBCKNBCDVV',
'BDISJBJ 2,000 DBFIAJDBDIAJ',
'JDBISJB 5,000 AHSBIEFEWEFJ', # parenthesis is removed
'CONDDDD 7,000 4DJVBDISJEVV'] # parenthesis is removed
I know how to do it by converting list to str like following:
a = str(list)
a = a.replace(")","")
print(a)
However, since I need convert it to a dataframe later... I want to keep it as list.
Please let me know if you need any clarificaiton for my question. This is my first time to post a question.
A:
You may use a list comprehension here:
inp = ['ABDDDDC 1,000 IWJBCKNBCDVV', 'BDISJBJ 2,000 DBFIAJDBDIAJ', 'JDBISJB 5,000 AHSBIEFEWEFJ)', 'CONDDDD 7,000 4DJVBDISJEVV)']
output = [re.sub(r'\)$', '', x) for x in inp]
print(output)
This prints:
['ABDDDDC 1,000 IWJBCKNBCDVV',
'BDISJBJ 2,000 DBFIAJDBDIAJ',
'JDBISJB 5,000 AHSBIEFEWEFJ',
'CONDDDD 7,000 4DJVBDISJEVV']
A:
This is the solution for that.
list =[
'ABDDDDC 1,000 IWJBCKNBCDVV',
'BDISJBJ 2,000 DBFIAJDBDIAJ',
'JDBISJB 5,000 AHSBIEFEWEFJ)',
'CONDDDD 7,000 4DJVBDISJEVV)']
list = [i.replace(')','') if ')' in i else i for i in list]
[print(x) for x in list]
|
Remove ")" from cells in list if ")" exists
|
Could you please tell me how can I remove ")" from strings in a list without converting the list to a string? Example:
Input:
list =[
'ABDDDDC 1,000 IWJBCKNBCDVV',
'BDISJBJ 2,000 DBFIAJDBDIAJ',
'JDBISJB 5,000 AHSBIEFEWEFJ)', # there is a parenthesis at the end
'CONDDDD 7,000 4DJVBDISJEVV)'] # there is a parenthesis at the end
Expected output:
list =[
'ABDDDDC 1,000 IWJBCKNBCDVV',
'BDISJBJ 2,000 DBFIAJDBDIAJ',
'JDBISJB 5,000 AHSBIEFEWEFJ', # parenthesis is removed
'CONDDDD 7,000 4DJVBDISJEVV'] # parenthesis is removed
I know how to do it by converting list to str like following:
a = str(list)
a = a.replace(")","")
print(a)
However, since I need convert it to a dataframe later... I want to keep it as list.
Please let me know if you need any clarificaiton for my question. This is my first time to post a question.
|
[
"You may use a list comprehension here:\ninp = ['ABDDDDC 1,000 IWJBCKNBCDVV', 'BDISJBJ 2,000 DBFIAJDBDIAJ', 'JDBISJB 5,000 AHSBIEFEWEFJ)', 'CONDDDD 7,000 4DJVBDISJEVV)']\noutput = [re.sub(r'\\)$', '', x) for x in inp]\nprint(output)\n\nThis prints:\n['ABDDDDC 1,000 IWJBCKNBCDVV',\n 'BDISJBJ 2,000 DBFIAJDBDIAJ',\n 'JDBISJB 5,000 AHSBIEFEWEFJ',\n 'CONDDDD 7,000 4DJVBDISJEVV']\n\n",
"This is the solution for that.\nlist =[\n 'ABDDDDC 1,000 IWJBCKNBCDVV',\n 'BDISJBJ 2,000 DBFIAJDBDIAJ',\n 'JDBISJB 5,000 AHSBIEFEWEFJ)',\n 'CONDDDD 7,000 4DJVBDISJEVV)']\n\nlist = [i.replace(')','') if ')' in i else i for i in list]\n[print(x) for x in list]\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"code_cleanup",
"data_cleaning",
"list",
"parentheses",
"python"
] |
stackoverflow_0074568085_code_cleanup_data_cleaning_list_parentheses_python.txt
|
Q:
I need to solve an equation numerically, but fsolve gives me a seemingly incorrect answer
I need to solve a single variable in an equation numerically. I tried using fsolve on two different functions that are, according to my understanding, equivalent. Call these functions func1 and func2. If I specify the variable I am solving for, both functions return the same value (the residual of the equation). However when I don't specify the variable and use fsolve to find it, I get different answers depending on whether I use func1 or func2. What am I doing wrong?
data for my question
dHi=array([-125790,49080,4.2]) # [n butane : 1,3 butadiene : H2]
dGi=array([-16570,124520,17.6])
V=array([-1,1,2])
No=array([1,0,0])
dH=sum(V*dHi)
dG=sum(V*dGi)
now function 1
def func1(e):
R=8.314
T1=298
T2=925
Nt=1+2*e
Ni=array([1-e,e,2*e])
lnk1=(-dG/(R*T1))
lnk2=-(dH/R)*(1/T2 - 1/T1)+lnk1
k2=exp(lnk2)
A1=prod((Ni/Nt)**V)-k2
return A1
for function 2 I wrote a separate function that does not require me to specify Ni, but calculates it as a function of e.
def N(e):
return No+e*V
def func2(e):
R=8.314
T1=298
T2=925
Nt=1+2*e
lnk1=(-dG/(R*T1))
lnk2=-(dH/R)*(1/T2 - 1/T1)+lnk1
k2=exp(lnk2)
A1=prod(((N(e))/Nt)**V)-k2
return A1
to prove N(e) and Ni is equivalent
e=0.1
Ni=array([1-e,e,2*e])
print(Ni,N(e))
I get
[0.9 0.1 0.2] [0.9 0.1 0.2]
Now to compare func1 and func2
print(fsolve(func1,0.03), fsolve(func2,0.03))
[0.10045184] [0.03108138]
If I check the second answer with both functions..
print(func1(0.03108138),func2(0.03108138))
1.2794325793047054e-11 1.2794325793047054e-11
So e = 0.03108138, and both functions can confirm this, but why does fsolve give the wrong answer for func1 ?
A:
The function you pass to scipy.optimize.fsolve is supposed to accept a 1-dimensional array, and return a 1-dimensional array of the same length. (This doesn't mean it should broadcast - the function is supposed to represent a system of N nonlinear equations in N variables for some N, so the input represents N input variables and the output represents the N output values.)
Whenever scipy.optimize.fsolve calls your function, it will pass the function an array. Even if you give an initial estimated root as a scalar, scipy.optimize.fsolve will pass your function 1-element arrays.
Neither of your functions are designed to handle array input. By sheer luck, your func2 happens to do the right thing when passed a single-element array, but func1 builds a Ni array of the wrong shape, then broadcasts the (Ni/Nt)**V computation in a way you don't want, and ends up computing the wrong value.
Write your functions to take and return 1-dimensional 1-element arrays instead of scalars, and you will get the right output.
|
I need to solve an equation numerically, but fsolve gives me a seemingly incorrect answer
|
I need to solve a single variable in an equation numerically. I tried using fsolve on two different functions that are, according to my understanding, equivalent. Call these functions func1 and func2. If I specify the variable I am solving for, both functions return the same value (the residual of the equation). However when I don't specify the variable and use fsolve to find it, I get different answers depending on whether I use func1 or func2. What am I doing wrong?
data for my question
dHi=array([-125790,49080,4.2]) # [n butane : 1,3 butadiene : H2]
dGi=array([-16570,124520,17.6])
V=array([-1,1,2])
No=array([1,0,0])
dH=sum(V*dHi)
dG=sum(V*dGi)
now function 1
def func1(e):
R=8.314
T1=298
T2=925
Nt=1+2*e
Ni=array([1-e,e,2*e])
lnk1=(-dG/(R*T1))
lnk2=-(dH/R)*(1/T2 - 1/T1)+lnk1
k2=exp(lnk2)
A1=prod((Ni/Nt)**V)-k2
return A1
for function 2 I wrote a separate function that does not require me to specify Ni, but calculates it as a function of e.
def N(e):
return No+e*V
def func2(e):
R=8.314
T1=298
T2=925
Nt=1+2*e
lnk1=(-dG/(R*T1))
lnk2=-(dH/R)*(1/T2 - 1/T1)+lnk1
k2=exp(lnk2)
A1=prod(((N(e))/Nt)**V)-k2
return A1
to prove N(e) and Ni is equivalent
e=0.1
Ni=array([1-e,e,2*e])
print(Ni,N(e))
I get
[0.9 0.1 0.2] [0.9 0.1 0.2]
Now to compare func1 and func2
print(fsolve(func1,0.03), fsolve(func2,0.03))
[0.10045184] [0.03108138]
If I check the second answer with both functions..
print(func1(0.03108138),func2(0.03108138))
1.2794325793047054e-11 1.2794325793047054e-11
So e = 0.03108138, and both functions can confirm this, but why does fsolve give the wrong answer for func1 ?
|
[
"The function you pass to scipy.optimize.fsolve is supposed to accept a 1-dimensional array, and return a 1-dimensional array of the same length. (This doesn't mean it should broadcast - the function is supposed to represent a system of N nonlinear equations in N variables for some N, so the input represents N input variables and the output represents the N output values.)\nWhenever scipy.optimize.fsolve calls your function, it will pass the function an array. Even if you give an initial estimated root as a scalar, scipy.optimize.fsolve will pass your function 1-element arrays.\nNeither of your functions are designed to handle array input. By sheer luck, your func2 happens to do the right thing when passed a single-element array, but func1 builds a Ni array of the wrong shape, then broadcasts the (Ni/Nt)**V computation in a way you don't want, and ends up computing the wrong value.\nWrite your functions to take and return 1-dimensional 1-element arrays instead of scalars, and you will get the right output.\n"
] |
[
1
] |
[] |
[] |
[
"fsolve",
"python"
] |
stackoverflow_0074570657_fsolve_python.txt
|
Q:
"RuntimeError: self must be a matrix"
RBM
we add methods to convert the visible input to the hidden representation and the hidden representation back to reconstructed visible input. Both methods return the activation probabilities, while the sample_h method also returns the observed hidden state as well
<pre><code>
class RBM():
def __init__(self, visible_dim, hidden_dim, gaussian_hidden_distribution=False):
self.visible_dim = visible_dim
self.hidden_dim = hidden_dim
self.gaussian_hidden_distribution = gaussian_hidden_distribution
# intialize parameters
self.W = torch.randn(visible_dim, hidden_dim) * 0.1
self.h_bias = torch.zeros(hidden_dim) # visible --> hidden
self.v_bias = torch.zeros(visible_dim) # hidden --> visible
# parameters for learning with momentum
self.W_momentum = torch.zeros(visible_dim, hidden_dim)
self.h_bias_momentum = torch.zeros(hidden_dim)
self.v_bias_momentum = torch.zeros(visible_dim)
def sample_h(self, v):
activation = torch.mm(v, self.W) + self.h_bias
if self.gaussian_hidden_distribution:
return activation, torch.normal(activation, torch.tensor([1]))
else:
p = torch.sigmoid(activation)
return p, torch.bernoulli(p)
def sample_v(self, h):
"""Get visible activation probabilities"""
activation = torch.mm(h, self.W.t()) + self.v_bias
p = torch.sigmoid(activation)
return p
def update_weights(self, v0, vk, ph0, phk, lr,
momentum_coef, weight_decay, batch_size):
self.W_momentum *= momentum_coef
self.W_momentum += torch.mm(v0.t(), ph0) - torch.mm(vk.t(), phk)
self.h_bias_momentum *= momentum_coef
self.h_bias_momentum += torch.sum((ph0 - phk), 0)
self.v_bias_momentum *= momentum_coef
self.v_bias_momentum += torch.sum((v0 - vk), 0)
self.W += lr*self.W_momentum/batch_size
self.h_bias += lr*self.h_bias_momentum/batch_size
self.v_bias += lr*self.v_bias_momentum/batch_size
self.W -= self.W * weight_decay # L2 weight decay
</code></pre>
Training RBM
While training the model i am getting " RuntimeError: self must be a matrix", can someone help me out and tell me what changes should I make in code.
<pre><code>
models = [] # store trained RBM models
visible_dim = 784
rbm_train_dl = train_dl_flat
for hidden_dim in [1000, 500, 250, 2]:
# configs - we have a different configuration for the last layer
num_epochs = 30 if hidden_dim == 2 else 10
lr = 1e-3 if hidden_dim == 2 else 0.1
use_gaussian = hidden_dim == 2
# train RBM
rbm = RBM(visible_dim=visible_dim, hidden_dim=hidden_dim,
gaussian_hidden_distribution=use_gaussian)
for epoch in range(num_epochs):
for i, data_list in enumerate(train_dl):
v0 = data_list[0]
# get reconstructed input via Gibbs sampling with k=1
_, hk = rbm.sample_h(v0)
pvk = rbm.sample_v(hk)
# update weights
rbm.update_weights(v0, pvk, rbm.sample_h(v0)[0], rbm.sample_h(pvk)[0], lr,
momentum_coef=0.5 if epoch < 5 else 0.9,
weight_decay=2e-4,
batch_size=sample_data.shape[0])
models.append(rbm)
# rederive new data loader based on hidden activations of trained model
new_data = [model.sample_h(data_list[0])[0].detach().numpy() for data_list in rbm_train_dl]
rbm_train_dl = DataLoader(
TensorDataset(torch.Tensor(np.concatenate(new_data))),
batch_size=64, shuffle=False
)
visible_dim = hidden_dim
</code></pre>
ERROR
<pre><code>
RuntimeError Traceback (most recent call last)
<ipython-input-3-53fe4223334d> in <module>()
16
17 # get reconstructed input via Gibbs sampling with k=1
---> 18 _, hk = rbm.sample_h(v0)
19 pvk = rbm.sample_v(hk)
20 # update weights
<ipython-input-1-49d2abc1da92> in sample_h(self, v)
15 def sample_h(self, v):
16 """Get sample hidden values and activation probabilities"""
---> 17 activation = torch.mm(v, self.W) + self.h_bias
18 if self.gaussian_hidden_distribution:
19 return activation, torch.normal(activation, torch.tensor([1]))
RuntimeError: self must be a matrix
</code></pre>
A:
Seems you need broadcasting (because you're multiplying 1d vector on 2D matrix).
Try using torch.matmul instead.
This link for understanding the difference between mm and matmul:
What's the difference between torch.mm, torch.matmul and torch.mul?
|
"RuntimeError: self must be a matrix"
|
RBM
we add methods to convert the visible input to the hidden representation and the hidden representation back to reconstructed visible input. Both methods return the activation probabilities, while the sample_h method also returns the observed hidden state as well
<pre><code>
class RBM():
def __init__(self, visible_dim, hidden_dim, gaussian_hidden_distribution=False):
self.visible_dim = visible_dim
self.hidden_dim = hidden_dim
self.gaussian_hidden_distribution = gaussian_hidden_distribution
# intialize parameters
self.W = torch.randn(visible_dim, hidden_dim) * 0.1
self.h_bias = torch.zeros(hidden_dim) # visible --> hidden
self.v_bias = torch.zeros(visible_dim) # hidden --> visible
# parameters for learning with momentum
self.W_momentum = torch.zeros(visible_dim, hidden_dim)
self.h_bias_momentum = torch.zeros(hidden_dim)
self.v_bias_momentum = torch.zeros(visible_dim)
def sample_h(self, v):
activation = torch.mm(v, self.W) + self.h_bias
if self.gaussian_hidden_distribution:
return activation, torch.normal(activation, torch.tensor([1]))
else:
p = torch.sigmoid(activation)
return p, torch.bernoulli(p)
def sample_v(self, h):
"""Get visible activation probabilities"""
activation = torch.mm(h, self.W.t()) + self.v_bias
p = torch.sigmoid(activation)
return p
def update_weights(self, v0, vk, ph0, phk, lr,
momentum_coef, weight_decay, batch_size):
self.W_momentum *= momentum_coef
self.W_momentum += torch.mm(v0.t(), ph0) - torch.mm(vk.t(), phk)
self.h_bias_momentum *= momentum_coef
self.h_bias_momentum += torch.sum((ph0 - phk), 0)
self.v_bias_momentum *= momentum_coef
self.v_bias_momentum += torch.sum((v0 - vk), 0)
self.W += lr*self.W_momentum/batch_size
self.h_bias += lr*self.h_bias_momentum/batch_size
self.v_bias += lr*self.v_bias_momentum/batch_size
self.W -= self.W * weight_decay # L2 weight decay
</code></pre>
Training RBM
While training the model i am getting " RuntimeError: self must be a matrix", can someone help me out and tell me what changes should I make in code.
<pre><code>
models = [] # store trained RBM models
visible_dim = 784
rbm_train_dl = train_dl_flat
for hidden_dim in [1000, 500, 250, 2]:
# configs - we have a different configuration for the last layer
num_epochs = 30 if hidden_dim == 2 else 10
lr = 1e-3 if hidden_dim == 2 else 0.1
use_gaussian = hidden_dim == 2
# train RBM
rbm = RBM(visible_dim=visible_dim, hidden_dim=hidden_dim,
gaussian_hidden_distribution=use_gaussian)
for epoch in range(num_epochs):
for i, data_list in enumerate(train_dl):
v0 = data_list[0]
# get reconstructed input via Gibbs sampling with k=1
_, hk = rbm.sample_h(v0)
pvk = rbm.sample_v(hk)
# update weights
rbm.update_weights(v0, pvk, rbm.sample_h(v0)[0], rbm.sample_h(pvk)[0], lr,
momentum_coef=0.5 if epoch < 5 else 0.9,
weight_decay=2e-4,
batch_size=sample_data.shape[0])
models.append(rbm)
# rederive new data loader based on hidden activations of trained model
new_data = [model.sample_h(data_list[0])[0].detach().numpy() for data_list in rbm_train_dl]
rbm_train_dl = DataLoader(
TensorDataset(torch.Tensor(np.concatenate(new_data))),
batch_size=64, shuffle=False
)
visible_dim = hidden_dim
</code></pre>
ERROR
<pre><code>
RuntimeError Traceback (most recent call last)
<ipython-input-3-53fe4223334d> in <module>()
16
17 # get reconstructed input via Gibbs sampling with k=1
---> 18 _, hk = rbm.sample_h(v0)
19 pvk = rbm.sample_v(hk)
20 # update weights
<ipython-input-1-49d2abc1da92> in sample_h(self, v)
15 def sample_h(self, v):
16 """Get sample hidden values and activation probabilities"""
---> 17 activation = torch.mm(v, self.W) + self.h_bias
18 if self.gaussian_hidden_distribution:
19 return activation, torch.normal(activation, torch.tensor([1]))
RuntimeError: self must be a matrix
</code></pre>
|
[
"Seems you need broadcasting (because you're multiplying 1d vector on 2D matrix). \nTry using torch.matmul instead.\nThis link for understanding the difference between mm and matmul:\nWhat's the difference between torch.mm, torch.matmul and torch.mul?\n"
] |
[
0
] |
[] |
[] |
[
"python",
"pytorch",
"rbm"
] |
stackoverflow_0067957655_python_pytorch_rbm.txt
|
Q:
Merge two dataframes on nearest value while duplicating rows
I have two dataframes,
DF1 = NUM1 Car COLOR
100 Honda blue
100 Honda yellow
200 Volvo red
DF2 = NUM2 Car STATE
110 Honda good
110 Honda bad
230 Volvo not bad
230 Volvo excellent
I want to merge them on nearest value in columns NUM1 & NUM2 in order to get this desired dataframe:
DF3 = NUM CAR COLOR STATE
100 HONDA blue good
100 HONDA blue bad
100 HONDA yellow good
100 HONDA yellow bad
200 VOLVO red not bad
200 VOLVO red excellent
I've tried this:
df3 = pd.merge_asof(df1, df2, left_on="NUM1", right_on="NUM2")
But this is the result I get:
DF3 = NUM CAR COLOR STATE
100 HONDA blue good
100 HONDA yellow good
200 VOLVO red not bad
A:
IIUC, you might need to combine merge_asof and merge:
key = pd.merge_asof(DF1.reset_index().sort_values(by='NUM1'),
DF2['NUM2'],
left_on='NUM1', right_on='NUM2',
direction='nearest')['NUM2']
DF1.merge(DF2.drop(columns=DF1.columns.intersection(DF2.columns)),
left_on=key, right_on='NUM2')
|
Merge two dataframes on nearest value while duplicating rows
|
I have two dataframes,
DF1 = NUM1 Car COLOR
100 Honda blue
100 Honda yellow
200 Volvo red
DF2 = NUM2 Car STATE
110 Honda good
110 Honda bad
230 Volvo not bad
230 Volvo excellent
I want to merge them on nearest value in columns NUM1 & NUM2 in order to get this desired dataframe:
DF3 = NUM CAR COLOR STATE
100 HONDA blue good
100 HONDA blue bad
100 HONDA yellow good
100 HONDA yellow bad
200 VOLVO red not bad
200 VOLVO red excellent
I've tried this:
df3 = pd.merge_asof(df1, df2, left_on="NUM1", right_on="NUM2")
But this is the result I get:
DF3 = NUM CAR COLOR STATE
100 HONDA blue good
100 HONDA yellow good
200 VOLVO red not bad
|
[
"IIUC, you might need to combine merge_asof and merge:\nkey = pd.merge_asof(DF1.reset_index().sort_values(by='NUM1'),\n DF2['NUM2'],\n left_on='NUM1', right_on='NUM2',\n direction='nearest')['NUM2']\n\nDF1.merge(DF2.drop(columns=DF1.columns.intersection(DF2.columns)),\n left_on=key, right_on='NUM2')\n\n"
] |
[
1
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074570934_dataframe_pandas_python.txt
|
Q:
How to assert data in a JSON array with Python
I am trying to automate some API endpoints, but the JSON response is an array of data. How can I assert a specific user with all his data inside that JSON array?
I am trying with:
assert {
"user": "test1",
"userName": "John Berner",
"userid": "1"
} in response.json()
The JSON response is:
{
"data": [
{
"user": "test1",
"userName": "John Berner",
"userid": "1"
},
{
"user": "test2",
"userName": "Nick Morris",
"userid": "2"
}
],
"metadata": {
"current_page": 1,
"pages": 1,
"per_page": 100,
"total": 2
}
}
A:
Please try like this:
You can use loop over the data within any to perform this check.
contents = json.loads(apiresponse_data)
assert any(i['user'] == 'test1' for i in contents['data'])
A:
If all the fields are in the response are part of your user_info you can do what you are thinking of doing -
# response = json.loads(api_response_data)
response = {
"data": [
{
"user": "test1",
"userName": "John Berner",
"userid": "1"
},
{
"user": "test2",
"userName": "Nick Morris",
"userid": "2"
}
],
"metadata": {
"current_page": 1,
"pages": 1,
"per_page": 100,
"total": 2
}
}
user_info = {
"user": "test1",
"userName": "John Berner",
"userid": "1"
}
assert user_info in response['data']
Above doesn't raise AssertionError because the user_info is there in the response['data']
You can also use following if you have decoded the json response already -
assert {
"user": "test1",
"userName": "John Berner",
"userid": "1"
} in response['data']
|
How to assert data in a JSON array with Python
|
I am trying to automate some API endpoints, but the JSON response is an array of data. How can I assert a specific user with all his data inside that JSON array?
I am trying with:
assert {
"user": "test1",
"userName": "John Berner",
"userid": "1"
} in response.json()
The JSON response is:
{
"data": [
{
"user": "test1",
"userName": "John Berner",
"userid": "1"
},
{
"user": "test2",
"userName": "Nick Morris",
"userid": "2"
}
],
"metadata": {
"current_page": 1,
"pages": 1,
"per_page": 100,
"total": 2
}
}
|
[
"Please try like this:\nYou can use loop over the data within any to perform this check.\ncontents = json.loads(apiresponse_data)\nassert any(i['user'] == 'test1' for i in contents['data'])\n\n",
"If all the fields are in the response are part of your user_info you can do what you are thinking of doing -\n# response = json.loads(api_response_data)\nresponse = {\n \"data\": [\n {\n \"user\": \"test1\",\n \"userName\": \"John Berner\",\n \"userid\": \"1\"\n },\n {\n \"user\": \"test2\",\n \"userName\": \"Nick Morris\",\n \"userid\": \"2\"\n }\n ],\n \"metadata\": {\n \"current_page\": 1,\n \"pages\": 1,\n \"per_page\": 100,\n \"total\": 2\n }\n}\n\nuser_info = {\n \"user\": \"test1\",\n \"userName\": \"John Berner\",\n \"userid\": \"1\"\n}\n\nassert user_info in response['data']\n\nAbove doesn't raise AssertionError because the user_info is there in the response['data']\nYou can also use following if you have decoded the json response already -\nassert {\n \"user\": \"test1\",\n \"userName\": \"John Berner\",\n \"userid\": \"1\"\n} in response['data']\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"api",
"automation",
"json",
"python"
] |
stackoverflow_0074570926_api_automation_json_python.txt
|
Q:
Runtime Error: mat1 and mat2 shapes cannot be multiplied (16x756900 and 3048516x30)
How can I solve this problem?
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3,8,11, padding=0) # in_channel, out_channel, kernel size
self.pool = nn.MaxPool2d(2,2) # kernel_size, stride
self.conv2 = nn.Conv2d(8, 36, 5, padding=0)
self.fc1 = nn.Linear(36*291*291, 30) # in_features, out_features
self.fc2 = nn.Linear(30, 20)
self.fc3 = nn.Linear(20, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = torch.flatten(x, 1) # flatten all dimensions except batch
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
I wrote my code like this, but I got "Runtime Error: mat1 and mat2 shapes cannot be multiplied".
The input shape is:'torch.Size([3,600,600])' ,with 3 channels.
Please help me!
A:
756900
Just change the model definition, the output shape of your last convolution layer does not have the shape 36x291x291. Just change the model definition to:
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3,8,11, padding=0) # in_channel, out_channel, kernel size
self.pool = nn.MaxPool2d(2,2) # kernel_size, stride
self.conv2 = nn.Conv2d(8, 36, 5, padding=0)
self.fc1 = nn.Linear(756900, 30) # in_features, out_features
self.fc2 = nn.Linear(30, 20)
self.fc3 = nn.Linear(20, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = torch.flatten(x, 1) # flatten all dimensions except batch
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
Tried the same with your input size, and it works.
|
Runtime Error: mat1 and mat2 shapes cannot be multiplied (16x756900 and 3048516x30)
|
How can I solve this problem?
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3,8,11, padding=0) # in_channel, out_channel, kernel size
self.pool = nn.MaxPool2d(2,2) # kernel_size, stride
self.conv2 = nn.Conv2d(8, 36, 5, padding=0)
self.fc1 = nn.Linear(36*291*291, 30) # in_features, out_features
self.fc2 = nn.Linear(30, 20)
self.fc3 = nn.Linear(20, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = torch.flatten(x, 1) # flatten all dimensions except batch
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
I wrote my code like this, but I got "Runtime Error: mat1 and mat2 shapes cannot be multiplied".
The input shape is:'torch.Size([3,600,600])' ,with 3 channels.
Please help me!
|
[
"756900\nJust change the model definition, the output shape of your last convolution layer does not have the shape 36x291x291. Just change the model definition to:\nclass Net(nn.Module):\n def __init__(self):\n super().__init__()\n \n self.conv1 = nn.Conv2d(3,8,11, padding=0) # in_channel, out_channel, kernel size\n self.pool = nn.MaxPool2d(2,2) # kernel_size, stride\n self.conv2 = nn.Conv2d(8, 36, 5, padding=0)\n self.fc1 = nn.Linear(756900, 30) # in_features, out_features\n self.fc2 = nn.Linear(30, 20)\n self.fc3 = nn.Linear(20, 10)\n\n\n def forward(self, x):\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = torch.flatten(x, 1) # flatten all dimensions except batch\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\nTried the same with your input size, and it works.\n"
] |
[
0
] |
[] |
[] |
[
"artificial_intelligence",
"conv_neural_network",
"python",
"torch"
] |
stackoverflow_0074550050_artificial_intelligence_conv_neural_network_python_torch.txt
|
Q:
Convert dataframe into JSON file
Dataframe:
Name Location code ID Dept Details Fbk
Kirsh HD12 76 Admin "Age:25; Location : ""SF""; From: ""London""; Marital stays: ""Single"";" Good
John HD12 87 Support "Age:35; Location : ""SF""; From: ""Chicago""; Marital stays: ""Single"";" Good
Desired output:
{
“Kirsh”: {
“Location code”:”HD12”,
“ID”: “76”,
“Dept”: “IT”,
“Details”: {
“Age”:”25”;,
“Location”:”SF”;,
“From”: "London";,
“Marital stays”: "Single";,
}
“Fbk”: “good”
},
“John”: {
“Location code”:”HD12”,
“ID”: “87”,
“Dept”: “Support”,
“Details”: {
“Age”:”35”;,
“Location”:”SF”;,
“From”: "chicago";,
“Marital stays”: "Single";,
}
“Fbk”: “good”
}
}
A:
import pandas as pd
import json
df = pd.DataFrame({'name':['a','b','c','d'],'age':[10,20,30,40],'address':['e','f','g','h']})
df_without_name = data1.loc[:, df.columns!='name']
dict_wihtout_name = df_without_name.to_dict(orient='records')
dict_index_by_name = dict(zip(df['name'], df_without_name))
print(json.dumps(dict_index_by_name, indent=2))
Output:
{
"a": {
"age": 10,
"address": "e"
},
"b": {
"age": 20,
"address": "f"
},
"c": {
"age": 30,
"address": "g"
},
"d": {
"age": 40,
"address": "h"
}
}
Answering the comment posted by @Eswar:
If a field has multiple values then you can store it as a tuple in the dataframe. Check this answer - https://stackoverflow.com/a/74584666/1788146 on how to store tuple values in pandas dataframe.
|
Convert dataframe into JSON file
|
Dataframe:
Name Location code ID Dept Details Fbk
Kirsh HD12 76 Admin "Age:25; Location : ""SF""; From: ""London""; Marital stays: ""Single"";" Good
John HD12 87 Support "Age:35; Location : ""SF""; From: ""Chicago""; Marital stays: ""Single"";" Good
Desired output:
{
“Kirsh”: {
“Location code”:”HD12”,
“ID”: “76”,
“Dept”: “IT”,
“Details”: {
“Age”:”25”;,
“Location”:”SF”;,
“From”: "London";,
“Marital stays”: "Single";,
}
“Fbk”: “good”
},
“John”: {
“Location code”:”HD12”,
“ID”: “87”,
“Dept”: “Support”,
“Details”: {
“Age”:”35”;,
“Location”:”SF”;,
“From”: "chicago";,
“Marital stays”: "Single";,
}
“Fbk”: “good”
}
}
|
[
"import pandas as pd\nimport json\n\ndf = pd.DataFrame({'name':['a','b','c','d'],'age':[10,20,30,40],'address':['e','f','g','h']})\n\ndf_without_name = data1.loc[:, df.columns!='name']\n\ndict_wihtout_name = df_without_name.to_dict(orient='records')\n\ndict_index_by_name = dict(zip(df['name'], df_without_name))\n\nprint(json.dumps(dict_index_by_name, indent=2))\n\nOutput:\n{\n \"a\": {\n \"age\": 10,\n \"address\": \"e\"\n },\n \"b\": {\n \"age\": 20,\n \"address\": \"f\"\n },\n \"c\": {\n \"age\": 30,\n \"address\": \"g\"\n },\n \"d\": {\n \"age\": 40,\n \"address\": \"h\"\n }\n}\n\nAnswering the comment posted by @Eswar:\nIf a field has multiple values then you can store it as a tuple in the dataframe. Check this answer - https://stackoverflow.com/a/74584666/1788146 on how to store tuple values in pandas dataframe.\n"
] |
[
1
] |
[] |
[] |
[
"dataframe",
"json",
"pandas",
"python"
] |
stackoverflow_0074568501_dataframe_json_pandas_python.txt
|
Q:
How to zip two columns into a key value pair dictionary in pandas
I have a dataframe with two related columns that needs to be merged into a single dictionary column.
Sample Data:
skuId coreAttributes.price coreAttributes.amount
0 100 price 8.84
1 102 price 12.99
2 103 price 9.99
Expected output:
skuId coreAttributes
100 {'price': 8.84}
102 {'price': 12.99}
103 {'price': 9.99}
What I've tried:
planProducts_T = planProducts.filter(regex = 'coreAttributes').T
planProducts_T.columns = planProducts_T.iloc[0]
planProducts_T.iloc[1:].to_dict(orient = 'records')
I get UserWarning: DataFrame columns are not unique, some columns will be omitted. and this output:
[{'price': 9.99}]
Could you someone please help me on this.
A:
You can use a list comprehension with python's zip:
df['coreAttributes'] = [{k: v} for k,v in
zip(df['coreAttributes.price'],
df['coreAttributes.amount'])]
Output:
skuId coreAttributes.price coreAttributes.amount coreAttributes
0 100 price 8.84 {'price': 8.84}
1 102 price 12.99 {'price': 12.99}
2 103 price 9.99 {'price': 9.99}
If you need to remove the initial columns, use pop.
df['coreAttributes'] = [{k: v} for k,v in
zip(df.pop('coreAttributes.price'),
df.pop('coreAttributes.amount'))]
Output:
skuId coreAttributes
0 100 {'price': 8.84}
1 102 {'price': 12.99}
2 103 {'price': 9.99}
A:
you can use apply and drop for an optimize computation
df["coreAttributes"] = df.apply(lambda row: {row["coreAttributes.price"]: row["coreAttributes.amount"]}, axis=1)
df.drop(["coreAttributes.price","coreAttributes.amount"], axis=1)
output
skuId coreAttributes
0 100 {'price': 8.84}
1 102 {'price': 12.99}
2 103 {'price': 9.99}
|
How to zip two columns into a key value pair dictionary in pandas
|
I have a dataframe with two related columns that needs to be merged into a single dictionary column.
Sample Data:
skuId coreAttributes.price coreAttributes.amount
0 100 price 8.84
1 102 price 12.99
2 103 price 9.99
Expected output:
skuId coreAttributes
100 {'price': 8.84}
102 {'price': 12.99}
103 {'price': 9.99}
What I've tried:
planProducts_T = planProducts.filter(regex = 'coreAttributes').T
planProducts_T.columns = planProducts_T.iloc[0]
planProducts_T.iloc[1:].to_dict(orient = 'records')
I get UserWarning: DataFrame columns are not unique, some columns will be omitted. and this output:
[{'price': 9.99}]
Could you someone please help me on this.
|
[
"You can use a list comprehension with python's zip:\ndf['coreAttributes'] = [{k: v} for k,v in\n zip(df['coreAttributes.price'],\n df['coreAttributes.amount'])]\n\nOutput:\n skuId coreAttributes.price coreAttributes.amount coreAttributes\n0 100 price 8.84 {'price': 8.84}\n1 102 price 12.99 {'price': 12.99}\n2 103 price 9.99 {'price': 9.99}\n\nIf you need to remove the initial columns, use pop.\ndf['coreAttributes'] = [{k: v} for k,v in\n zip(df.pop('coreAttributes.price'),\n df.pop('coreAttributes.amount'))]\n\nOutput:\n skuId coreAttributes\n0 100 {'price': 8.84}\n1 102 {'price': 12.99}\n2 103 {'price': 9.99}\n\n",
"you can use apply and drop for an optimize computation\ndf[\"coreAttributes\"] = df.apply(lambda row: {row[\"coreAttributes.price\"]: row[\"coreAttributes.amount\"]}, axis=1)\ndf.drop([\"coreAttributes.price\",\"coreAttributes.amount\"], axis=1)\n\noutput\n skuId coreAttributes\n0 100 {'price': 8.84}\n1 102 {'price': 12.99}\n2 103 {'price': 9.99}\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074571107_pandas_python.txt
|
Q:
Prophet: disable or hide verbose logger output
Using ~~facebook~~ meta prophet's cross-validation function, I get lots of this:
WARNING:prophet.models:Optimization terminated abnormally. Falling back to Newton.
I can disable the stan output using this, but I can't seem to get rid of these pesky logs. I might find them useful if I was running this interactively, but I'm not.
I'm already doing this near the top of my script:
import logging
logging.getLogger('fbprophet').setLevel(logging.ERROR)
It doesn't help.
A:
You should ensure the qualifier is already set by te library, importing it.
import fbprophet
after that, you can get the logger and disable it.
logging.getLogger('fbprophet').disabled = True
I don't know if prophet use propagation to sub-qualifier, if so you can disable it by (use this technique carefully, disabling propagation can cause unwanted blinding situations):
logger.propagate = False
|
Prophet: disable or hide verbose logger output
|
Using ~~facebook~~ meta prophet's cross-validation function, I get lots of this:
WARNING:prophet.models:Optimization terminated abnormally. Falling back to Newton.
I can disable the stan output using this, but I can't seem to get rid of these pesky logs. I might find them useful if I was running this interactively, but I'm not.
I'm already doing this near the top of my script:
import logging
logging.getLogger('fbprophet').setLevel(logging.ERROR)
It doesn't help.
|
[
"You should ensure the qualifier is already set by te library, importing it.\n\nimport fbprophet\n\nafter that, you can get the logger and disable it.\n\nlogging.getLogger('fbprophet').disabled = True\n\nI don't know if prophet use propagation to sub-qualifier, if so you can disable it by (use this technique carefully, disabling propagation can cause unwanted blinding situations):\n\nlogger.propagate = False\n\n"
] |
[
0
] |
[] |
[] |
[
"facebook_prophet",
"logging",
"python"
] |
stackoverflow_0070608968_facebook_prophet_logging_python.txt
|
Q:
Effecient conversion of multilevel nested dictionary to df
I looked at several questions but did not find an answer to convert a nested dictionary with this irregular structure:
a = {'Cat0': {'brand1': {'b': 0.78, 'c': 1}, 'brand2': {'k': 1, 'c': 1}}, 'Cat1': {'brand4': {'b': 10, 's': 0.0}}, 'Cat2': {'brand1': {'j': 1, 'c': 0.0}}}
to the following pandas dataframe:
Category Brand Peer Value
0 Cat0 brand1 b 0.78
1 Cat0 brand1 c 1
2 Cat0 brand2 k 1
3 Cat0 brand2 c 1
4 Cat1 brand4 b 10
5 Cat1 brand4 s 0.0
6 Cat2 brand1 j 1
7 Cat2 brand1 c 0.0
The dictionary is going to be huge, so I am lookingfor the most efficient solution. Can you help me?
A:
It's quite straightforward with a comprehension to flatten the dictionary:
df = pd.DataFrame([[k, k1, k2, v]
for k, d in a.items()
for k1, d1 in d.items()
for k2, v in d1.items()],
columns=['Category', 'Brand', 'Peer', 'Value'])
You might get a slightly better efficiency using a generator instead of the comprehension (to be tested on the real data):
df = pd.DataFrame(([k, k1, k2, v]
for k, d in a.items()
for k1, d1 in d.items()
for k2, v in d1.items()),
columns=['Category', 'Brand', 'Peer', 'Value'])
Output:
Category Brand Peer Value
0 Cat0 brand1 b 0.78
1 Cat0 brand1 c 1.00
2 Cat0 brand2 k 1.00
3 Cat0 brand2 c 1.00
4 Cat1 brand4 b 10.00
5 Cat1 brand4 s 0.00
6 Cat2 brand1 j 1.00
7 Cat2 brand1 c 0.00
|
Effecient conversion of multilevel nested dictionary to df
|
I looked at several questions but did not find an answer to convert a nested dictionary with this irregular structure:
a = {'Cat0': {'brand1': {'b': 0.78, 'c': 1}, 'brand2': {'k': 1, 'c': 1}}, 'Cat1': {'brand4': {'b': 10, 's': 0.0}}, 'Cat2': {'brand1': {'j': 1, 'c': 0.0}}}
to the following pandas dataframe:
Category Brand Peer Value
0 Cat0 brand1 b 0.78
1 Cat0 brand1 c 1
2 Cat0 brand2 k 1
3 Cat0 brand2 c 1
4 Cat1 brand4 b 10
5 Cat1 brand4 s 0.0
6 Cat2 brand1 j 1
7 Cat2 brand1 c 0.0
The dictionary is going to be huge, so I am lookingfor the most efficient solution. Can you help me?
|
[
"It's quite straightforward with a comprehension to flatten the dictionary:\ndf = pd.DataFrame([[k, k1, k2, v]\n for k, d in a.items()\n for k1, d1 in d.items()\n for k2, v in d1.items()],\n columns=['Category', 'Brand', 'Peer', 'Value'])\n\nYou might get a slightly better efficiency using a generator instead of the comprehension (to be tested on the real data):\ndf = pd.DataFrame(([k, k1, k2, v]\n for k, d in a.items()\n for k1, d1 in d.items()\n for k2, v in d1.items()),\n columns=['Category', 'Brand', 'Peer', 'Value'])\n\nOutput:\n Category Brand Peer Value\n0 Cat0 brand1 b 0.78\n1 Cat0 brand1 c 1.00\n2 Cat0 brand2 k 1.00\n3 Cat0 brand2 c 1.00\n4 Cat1 brand4 b 10.00\n5 Cat1 brand4 s 0.00\n6 Cat2 brand1 j 1.00\n7 Cat2 brand1 c 0.00\n\n"
] |
[
3
] |
[] |
[] |
[
"dictionary",
"pandas",
"python"
] |
stackoverflow_0074571157_dictionary_pandas_python.txt
|
Q:
What is the best way to compare two dataframes with multiple entries for a key?
I have two dataframes. They can have multiple values for the same product id. What would be the best way to compare their values?
I have tried comparing them with compare, from csv_diff library, but it is based on a unique key. However, my dataframes don't have a unique key, having multiple entries for the same product_name.
diff = compare(
load_csv(open("df1.csv"), key="product_name"),
load_csv(open("df2.csv"), key="product_name")
)
The dataframes look like below:
df1:
product name value value2 value3 value4 value5 value6 value7 ...
0 1234PROD 1 2 3 4 5 6 7 ...
1 1234PROD 7 4 4 7 8 7 8 ...
2 1234PROD 8 7 4 7 8 7 8 ...
df2:
product name value value2 value3 value4 value5 value6 value7 ...
0 4567PROD 1 2 3 4 5 6 9 ...
1 8767PROD 7 4 4 7 8 7 8 ...
2 1234PROD 5 7 4 7 8 7 8 ...
3 1234PROD 8 7 4 7 8 7 8 ...
I would like to obtain the summary of their changes, something similar to:
changes:
[{'key': '1234PROD',
'changes': {'value': [1, 5],
'value1': [2,7],
'value2': [3,4]
}]
A:
I'm not sure what your expected output should be, but you could try the following:
df1.apply(lambda row: row == df2[df2.product_name == row.product_name], axis=1)
The result is an object where each row has all rows that corresponds with the product name. You can search that result per row:
result[2]:
index product_name value value2 value3 value4 value5 value6 value7
2 True False True True True True True True
3 True True True True True True True True
|
What is the best way to compare two dataframes with multiple entries for a key?
|
I have two dataframes. They can have multiple values for the same product id. What would be the best way to compare their values?
I have tried comparing them with compare, from csv_diff library, but it is based on a unique key. However, my dataframes don't have a unique key, having multiple entries for the same product_name.
diff = compare(
load_csv(open("df1.csv"), key="product_name"),
load_csv(open("df2.csv"), key="product_name")
)
The dataframes look like below:
df1:
product name value value2 value3 value4 value5 value6 value7 ...
0 1234PROD 1 2 3 4 5 6 7 ...
1 1234PROD 7 4 4 7 8 7 8 ...
2 1234PROD 8 7 4 7 8 7 8 ...
df2:
product name value value2 value3 value4 value5 value6 value7 ...
0 4567PROD 1 2 3 4 5 6 9 ...
1 8767PROD 7 4 4 7 8 7 8 ...
2 1234PROD 5 7 4 7 8 7 8 ...
3 1234PROD 8 7 4 7 8 7 8 ...
I would like to obtain the summary of their changes, something similar to:
changes:
[{'key': '1234PROD',
'changes': {'value': [1, 5],
'value1': [2,7],
'value2': [3,4]
}]
|
[
"I'm not sure what your expected output should be, but you could try the following:\ndf1.apply(lambda row: row == df2[df2.product_name == row.product_name], axis=1)\n\nThe result is an object where each row has all rows that corresponds with the product name. You can search that result per row:\nresult[2]:\nindex product_name value value2 value3 value4 value5 value6 value7\n2 True False True True True True True True\n3 True True True True True True True True\n\n"
] |
[
0
] |
[] |
[] |
[
"compare",
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074571090_compare_dataframe_pandas_python.txt
|
Q:
Not getting the hue ...of various 'Region'
plt.figure(figsize=(20,10))
plt.title('Regionwise Killed')
plt.xlabel('Year',fontsize=15)
plt.ylabel('Killed',fontsize=15)
sns.lineplot(x=df['Year'].index,y=df['Year'].value_counts(),hue=df['Region'])
plt.show()
getting output
only getting 3 hue regions in lineplot
I want a lineplot like this
|
Not getting the hue ...of various 'Region'
|
plt.figure(figsize=(20,10))
plt.title('Regionwise Killed')
plt.xlabel('Year',fontsize=15)
plt.ylabel('Killed',fontsize=15)
sns.lineplot(x=df['Year'].index,y=df['Year'].value_counts(),hue=df['Region'])
plt.show()
getting output
only getting 3 hue regions in lineplot
I want a lineplot like this
|
[] |
[] |
[
"Here this will help\ndf[\"counts\"] = 1\n\nnewDf = pd.DataFrame(df[[ \"Region\",\"Year\",\"counts\"]].groupby([ \"Region\",\"Year\" ]).sum([\"counts\"])).reset_index()\n\n\nand then after that on the new data set you can build those required graphs\nplt.figure(figsize=(20,10))\nplt.title('Regionwise Killed')\nplt.xlabel('Year',fontsize=15)\nplt.ylabel('Killed',fontsize=15)\nsns.lineplot(x=newDf ['Year'].index,y=newDf ['counts'],hue=newDf['Region'])\nplt.show()\n\n\n\n"
] |
[
-1
] |
[
"pandas",
"python",
"seaborn"
] |
stackoverflow_0074569573_pandas_python_seaborn.txt
|
Q:
How can I know the queues created in celery with -Q argument?
I want to load a different configuration for Celery workers depending on which queueu I'm initializing. Specially, I want to change its concurrency.
I have seen that concurrency can be changed if I load it in the config. For example, if I do:
celery_app = current_celery_app
# myconfig is a py file with all configuration, including concurrency
celery_app.config_from_object(myconfig, namespace='CELERY')
Then I saw that I can ask for signals, like:
@celeryd_init.connect
def configure_workers(sender=None, **kwargs):
if 'celery' in celery_app.amqp.queues.keys():
celery_app.config_from_object(config, namespace='CELERY')
celery_app.conf.update(worker_concurrency=4)
elif 'queue2' in celery_app.amqp.queues.keys():
celery_app.config_from_object(config, namespace='queue2')
celery_app.conf.update(worker_concurrency=2)
Here I saw that excluding the worker_concurrency from config and changing it with celery_app.conf.update(worker_concurrency=4) also works. However, this solution could fulfill my necessity if I could read the queues I'm starting.
To init the celery app I do:
celery -A run_api.celery worker -Q queue2
But if I print the queues in my first or second code example I'm always getting only one queue when executing celery_app.amqp.queues.keys(): celery (which is the default one). If I try any other signal, such as celeryd_after_setup, worker_ready, worker_start I see the queue queue2 if I execute celery_app.amqp.queues.keys(). However, if I try to do
celery_app.conf.update(worker_concurrency=2)
there's no change in concurrency. I'm out of ideas. How can I read celery queues passed in -Q argument in celeryd_init signal? or how can I change the concurrency after the worker is created?
This project is for FastAPI interconnection. I'm not using Django.
A:
I found a workaround. It's not what I would like to, but I think it's more general than initializing celery with --concurrency, which was my last option in case I couldn't find a better one. My workaround:
I found that you can start celery with -n option. This changes the name of the celery:
celery -A run_api.celery worker -Q queue2 -n queue2_name
Then in the signal:
@celeryd_init.connect
def configure_workers(sender=None, **kwargs):
worker_name = sender.split("@")[-1]
# sender is celery@what_you_put_after_-n
# in this case queue2_name
if 'queue2' in worker_name:
celery_app.config_from_object(config, namespace='queue2')
celery_app.conf.update(worker_concurrency=2)
else:
celery_app.config_from_object(config, namespace='CELERY')
celery_app.conf.update(worker_concurrency=4)
I'm working with celery 5.2.6
|
How can I know the queues created in celery with -Q argument?
|
I want to load a different configuration for Celery workers depending on which queueu I'm initializing. Specially, I want to change its concurrency.
I have seen that concurrency can be changed if I load it in the config. For example, if I do:
celery_app = current_celery_app
# myconfig is a py file with all configuration, including concurrency
celery_app.config_from_object(myconfig, namespace='CELERY')
Then I saw that I can ask for signals, like:
@celeryd_init.connect
def configure_workers(sender=None, **kwargs):
if 'celery' in celery_app.amqp.queues.keys():
celery_app.config_from_object(config, namespace='CELERY')
celery_app.conf.update(worker_concurrency=4)
elif 'queue2' in celery_app.amqp.queues.keys():
celery_app.config_from_object(config, namespace='queue2')
celery_app.conf.update(worker_concurrency=2)
Here I saw that excluding the worker_concurrency from config and changing it with celery_app.conf.update(worker_concurrency=4) also works. However, this solution could fulfill my necessity if I could read the queues I'm starting.
To init the celery app I do:
celery -A run_api.celery worker -Q queue2
But if I print the queues in my first or second code example I'm always getting only one queue when executing celery_app.amqp.queues.keys(): celery (which is the default one). If I try any other signal, such as celeryd_after_setup, worker_ready, worker_start I see the queue queue2 if I execute celery_app.amqp.queues.keys(). However, if I try to do
celery_app.conf.update(worker_concurrency=2)
there's no change in concurrency. I'm out of ideas. How can I read celery queues passed in -Q argument in celeryd_init signal? or how can I change the concurrency after the worker is created?
This project is for FastAPI interconnection. I'm not using Django.
|
[
"I found a workaround. It's not what I would like to, but I think it's more general than initializing celery with --concurrency, which was my last option in case I couldn't find a better one. My workaround:\nI found that you can start celery with -n option. This changes the name of the celery:\ncelery -A run_api.celery worker -Q queue2 -n queue2_name\n\nThen in the signal:\n@celeryd_init.connect\ndef configure_workers(sender=None, **kwargs):\n\n worker_name = sender.split(\"@\")[-1]\n # sender is celery@what_you_put_after_-n\n # in this case queue2_name\n\n if 'queue2' in worker_name:\n celery_app.config_from_object(config, namespace='queue2')\n celery_app.conf.update(worker_concurrency=2)\n else:\n celery_app.config_from_object(config, namespace='CELERY')\n celery_app.conf.update(worker_concurrency=4) \n\nI'm working with celery 5.2.6\n"
] |
[
0
] |
[] |
[] |
[
"celery",
"python"
] |
stackoverflow_0074571031_celery_python.txt
|
Q:
Python How to make a proper string slicing?
I can't figure out how to properly slice a string.
There is a line: "1, 2, 3, 4, 5, 6". The number of characters is unknown, numbers can be either one-digit or three-digit
I need to get the last value up to the nearest comma, that means I need to get the value (6) from the string
A:
Better use str.rsplit, setting maxsplit=1 to avoid unnecessarily splitting more than once:
string = "1, 2, 3, 4, 5, 6"
last = string.rsplit(', ', 1)[-1]
Output: '6'
A:
you can try to split and get last value
string = "1, 2, 3, 4, 5, 6"
string.split(',')[-1]
>>> ' 6'
add strip to get rid of the white spaces
string.split(',')[-1].strip(' ')
>>> '6'
A:
It seems to me the easiest way would be to use the method split and divide your string based on the comma.
In your example:
string = '1, 2, 3, 4, 5, 6'
last_value = string.split(', ')[-1]
print(last_value)
Out[3]: '6'
A:
Here's a function that should do it for you:
def get_last_number(s):
return s.split(',')[-1].strip()
Trying it on a few test strings:
s1 = "1, 2, 3, 4, 5, 6"
s2 = "123, 4, 785, 12"
s3 = "1, 2, 789654 "
...we get:
print (get_last_number(s1))
# 6
print (get_last_number(s2))
# 12
print (get_last_number(s3))
# 789654
A:
First of all you have to split the string:
string = '1, 2, 3, 4, 5, 6'
splitted_str = string.split(',')
Then, you should get the last element:
last_elem = splitted_str[-1]
Finally, you have to delete the unnecessary white spaces:
last_number_str = last_elem.strip()
Clearly this answer is a string type, if you need the numeric value you can cast the type by using
last_elem_int = int(last_elem_str)
Hope that helps
|
Python How to make a proper string slicing?
|
I can't figure out how to properly slice a string.
There is a line: "1, 2, 3, 4, 5, 6". The number of characters is unknown, numbers can be either one-digit or three-digit
I need to get the last value up to the nearest comma, that means I need to get the value (6) from the string
|
[
"Better use str.rsplit, setting maxsplit=1 to avoid unnecessarily splitting more than once:\nstring = \"1, 2, 3, 4, 5, 6\"\nlast = string.rsplit(', ', 1)[-1]\n\nOutput: '6'\n",
"you can try to split and get last value\nstring = \"1, 2, 3, 4, 5, 6\"\nstring.split(',')[-1]\n>>> ' 6'\n\nadd strip to get rid of the white spaces\nstring.split(',')[-1].strip(' ')\n>>> '6'\n\n",
"It seems to me the easiest way would be to use the method split and divide your string based on the comma.\nIn your example:\nstring = '1, 2, 3, 4, 5, 6'\nlast_value = string.split(', ')[-1]\nprint(last_value)\n\nOut[3]: '6'\n\n",
"Here's a function that should do it for you:\ndef get_last_number(s):\n return s.split(',')[-1].strip()\n\nTrying it on a few test strings:\ns1 = \"1, 2, 3, 4, 5, 6\"\ns2 = \"123, 4, 785, 12\"\ns3 = \"1, 2, 789654 \" \n\n...we get:\nprint (get_last_number(s1))\n# 6\nprint (get_last_number(s2))\n# 12\nprint (get_last_number(s3))\n# 789654\n\n",
"First of all you have to split the string:\nstring = '1, 2, 3, 4, 5, 6'\nsplitted_str = string.split(',')\n\nThen, you should get the last element:\nlast_elem = splitted_str[-1]\n\nFinally, you have to delete the unnecessary white spaces:\nlast_number_str = last_elem.strip()\n\nClearly this answer is a string type, if you need the numeric value you can cast the type by using\nlast_elem_int = int(last_elem_str)\n\nHope that helps\n"
] |
[
3,
2,
1,
1,
0
] |
[] |
[] |
[
"python",
"slice",
"string"
] |
stackoverflow_0074570461_python_slice_string.txt
|
Q:
How to split other information from binary string?
I have an image which is a result of a python code and has to be shown in a LabVIEW program. The pixels of the image are sent ( with sys.stdout.buffer.write)as a U32 pixels string, so I used unflatten from string in LabVIEW code to show the image, but the result from python includes other information as shown in the picture below, when I split them "manually" I can get the right picture. My question is, how can I only get the pixels information from python output to get the picture.
A:
You can use the match pattern node twice to cut off the first two lines like this:
Note that you might need to replace \n with \r\n, depending on how your actual input is coded.
|
How to split other information from binary string?
|
I have an image which is a result of a python code and has to be shown in a LabVIEW program. The pixels of the image are sent ( with sys.stdout.buffer.write)as a U32 pixels string, so I used unflatten from string in LabVIEW code to show the image, but the result from python includes other information as shown in the picture below, when I split them "manually" I can get the right picture. My question is, how can I only get the pixels information from python output to get the picture.
|
[
"You can use the match pattern node twice to cut off the first two lines like this:\n\nNote that you might need to replace \\n with \\r\\n, depending on how your actual input is coded.\n"
] |
[
0
] |
[] |
[] |
[
"image",
"labview",
"python",
"stdout"
] |
stackoverflow_0073618367_image_labview_python_stdout.txt
|
Q:
how can i style one cell of QTableWidget without any effect on the other cells?
i am working on a table and i use QTableWidget in my project
and i need to change the color or the style of one cell only or one row only , i do not want to style all of cells.
in the above image i changed all of cells but i want to change one cell or one row only.
is there any chance or way to do it ?
A:
I would implement my own QStyledItemDelegate and set the table to use that (setItemDelegate and friends).
It can be very simple for your needs, probably, just need to re-implement one method, QStyledItemDelegate::initStyleOption() and inside that set the backgroundBrush property of the QStyleOptionViewItem to whatever you need.
Here's a C++ example (sorry):
class BackgroundColorDelegate : public QStyledItemDelegate
{
public:
using QStyledItemDelegate::QStyledItemDelegate;
protected:
void initStyleOption(QStyleOptionViewItem *o, const QModelIndex &idx) const override
{
// first call the base class method
QStyledItemDelegate::initStyleOption(o, idx);
// Now you can override the background color based on some criteria,
// in the data for example, or the Delegate could have a custom
// property which the View sets as needed.
if (idx.data(Qt::UserRole).toString() == "color-me-blue")
o->backgroundBrush = QBrush(Qt::blue);
}
};
ADDED:
Found a Py example here, so the delegate would look something like this (untested):
class BackgroundColorDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
super().initStyleOption(option, index)
if index.data(QtCore.Qt.UserRole).toString() == "color-me-blue"):
option.backgroundBrush = QtGui.QBrush(QtCore.Qt.blue);
class TableView(QtWidgets.QTableView):
def __init__(self, parent=None):
super().__init__(parent)
self.setItemDelegate(BackgroundColorDelegate(self))
ALSO:
Another approach is to set the relevant model item's Qt.BackgroundRole to the desired color. This would work with any view delegate (including the default ones). Depending on how you're building your model, and especially if you're already using a custom model, this may be the better approach.
So for example if you want to set the background color while you're building the model, you could
model.setData(index, QtCore.Qt.BackgroundRole, QtGui.QBrush(Qt.blue))
Or if using a QStandardItem there is a method for that:
item.setBackground(QtGui.QBrush(QtCore.Qt.blue))
Or if you implement your own model then you could return the correct color from the QAbstractItemModel::data() method, something like
def data(self, index, role):
if not index.isValid():
return QtCore.QVariant()
elif role == QtCore.Qt.BackgroundRole:
if index.data(QtCore.Qt.UserRole).toString() == "color-me-blue":
return QtCore.Qt.blue
else:
return QtCore.Qt.transparent
return super().data(index, role)
HTH,
-Max
|
how can i style one cell of QTableWidget without any effect on the other cells?
|
i am working on a table and i use QTableWidget in my project
and i need to change the color or the style of one cell only or one row only , i do not want to style all of cells.
in the above image i changed all of cells but i want to change one cell or one row only.
is there any chance or way to do it ?
|
[
"I would implement my own QStyledItemDelegate and set the table to use that (setItemDelegate and friends).\nIt can be very simple for your needs, probably, just need to re-implement one method, QStyledItemDelegate::initStyleOption() and inside that set the backgroundBrush property of the QStyleOptionViewItem to whatever you need.\nHere's a C++ example (sorry):\nclass BackgroundColorDelegate : public QStyledItemDelegate\n{\n public:\n using QStyledItemDelegate::QStyledItemDelegate;\n\n protected:\n void initStyleOption(QStyleOptionViewItem *o, const QModelIndex &idx) const override\n {\n // first call the base class method\n QStyledItemDelegate::initStyleOption(o, idx);\n // Now you can override the background color based on some criteria,\n // in the data for example, or the Delegate could have a custom\n // property which the View sets as needed.\n if (idx.data(Qt::UserRole).toString() == \"color-me-blue\")\n o->backgroundBrush = QBrush(Qt::blue);\n }\n};\n\nADDED:\nFound a Py example here, so the delegate would look something like this (untested):\nclass BackgroundColorDelegate(QtWidgets.QStyledItemDelegate):\n def initStyleOption(self, option, index):\n super().initStyleOption(option, index)\n if index.data(QtCore.Qt.UserRole).toString() == \"color-me-blue\"):\n option.backgroundBrush = QtGui.QBrush(QtCore.Qt.blue);\n\nclass TableView(QtWidgets.QTableView):\n def __init__(self, parent=None):\n super().__init__(parent)\n self.setItemDelegate(BackgroundColorDelegate(self))\n\nALSO:\nAnother approach is to set the relevant model item's Qt.BackgroundRole to the desired color. This would work with any view delegate (including the default ones). Depending on how you're building your model, and especially if you're already using a custom model, this may be the better approach.\nSo for example if you want to set the background color while you're building the model, you could\nmodel.setData(index, QtCore.Qt.BackgroundRole, QtGui.QBrush(Qt.blue))\nOr if using a QStandardItem there is a method for that:\nitem.setBackground(QtGui.QBrush(QtCore.Qt.blue))\nOr if you implement your own model then you could return the correct color from the QAbstractItemModel::data() method, something like\n def data(self, index, role):\n if not index.isValid():\n return QtCore.QVariant()\n elif role == QtCore.Qt.BackgroundRole:\n if index.data(QtCore.Qt.UserRole).toString() == \"color-me-blue\":\n return QtCore.Qt.blue\n else:\n return QtCore.Qt.transparent\n return super().data(index, role)\n\nHTH,\n-Max\n"
] |
[
1
] |
[] |
[] |
[
"pyqt",
"pyqt5",
"pyqt6",
"python",
"qt"
] |
stackoverflow_0074540335_pyqt_pyqt5_pyqt6_python_qt.txt
|
Q:
Select specific rows/columns xls file
I would like to select specific rows and columns in Python. I already use pandas somewhere in my code so I'd prefer a way to do it with this library.
I tried specific_row = pandas.read_excel('this_file.xls', "Entrees")[3] and specific_row = pandas.read_excel('this_file.xls', "Entrees", index_col = 2)[3] but I can't seem to achieve it.
A:
you can use the "iloc" method and special which rows to select
specific_row = pandas.read_excel('this_file.xls', "Entrees").iloc[:3,:] #select 3 rows and every column
|
Select specific rows/columns xls file
|
I would like to select specific rows and columns in Python. I already use pandas somewhere in my code so I'd prefer a way to do it with this library.
I tried specific_row = pandas.read_excel('this_file.xls', "Entrees")[3] and specific_row = pandas.read_excel('this_file.xls', "Entrees", index_col = 2)[3] but I can't seem to achieve it.
|
[
"you can use the \"iloc\" method and special which rows to select\nspecific_row = pandas.read_excel('this_file.xls', \"Entrees\").iloc[:3,:] #select 3 rows and every column\n\n"
] |
[
0
] |
[] |
[] |
[
"pandas",
"python",
"xls"
] |
stackoverflow_0074571346_pandas_python_xls.txt
|
Q:
Django storages: Need authenticated way of reading static files from google cloud storage
I am trying to read static files from GCP storage using a service account key. The problem is while most of the requests are authenticated django-storages, some of the requests are public.
Developer console: Networks tab
And because of which I am getting a broken Django admin UI.
Broken Django admin UI
Here's my static file settings in settings.py file.
STATIC_URL = "/static/"
if DEPLOYED_URL:
DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage"
STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage"
GS_BUCKET_NAME = env("GS_BUCKET_NAME")
GS_CREDENTIALS = service_account.Credentials.from_service_account_info(
json.loads(get_secret(PROJECT_NAME, "service_account_json"))
)
GS_DEFAULT_ACL = "projectPrivate"
My restrictions are I have Fine-grained: Object-level ACLs enabled bucket on which public access cannot be given.
PS: Since there are restrictions to the project I cannot use a public bucket. Alternate ways other than the usage of django-storages package are also appreciated. The only condition is reads should be authenticated and not public.
A:
At the time of writing this, it's apparently an open bug related to django-storages but on AWS. But similar thing is happening on GCP on further inspection.
I have already deployed my application using whitenoise to overcome this bug and have hosted my application on GCP cloud run.
|
Django storages: Need authenticated way of reading static files from google cloud storage
|
I am trying to read static files from GCP storage using a service account key. The problem is while most of the requests are authenticated django-storages, some of the requests are public.
Developer console: Networks tab
And because of which I am getting a broken Django admin UI.
Broken Django admin UI
Here's my static file settings in settings.py file.
STATIC_URL = "/static/"
if DEPLOYED_URL:
DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage"
STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage"
GS_BUCKET_NAME = env("GS_BUCKET_NAME")
GS_CREDENTIALS = service_account.Credentials.from_service_account_info(
json.loads(get_secret(PROJECT_NAME, "service_account_json"))
)
GS_DEFAULT_ACL = "projectPrivate"
My restrictions are I have Fine-grained: Object-level ACLs enabled bucket on which public access cannot be given.
PS: Since there are restrictions to the project I cannot use a public bucket. Alternate ways other than the usage of django-storages package are also appreciated. The only condition is reads should be authenticated and not public.
|
[
"At the time of writing this, it's apparently an open bug related to django-storages but on AWS. But similar thing is happening on GCP on further inspection.\nI have already deployed my application using whitenoise to overcome this bug and have hosted my application on GCP cloud run.\n"
] |
[
0
] |
[] |
[] |
[
"django",
"django_staticfiles",
"python",
"python_django_storages"
] |
stackoverflow_0073196800_django_django_staticfiles_python_python_django_storages.txt
|
Q:
How to keep certain structure in various text files?
I have some .WOC files like(let's say File1):
Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.?
144 cm/35 Kg/5 YearsOld
45,34,22,26,0
78,74,82,11,0
and other ones like (File 2):
Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.?
126cm/45 Kg/13 YearsOld.
MON/age/sex/hei/weight/tsle/twak/dev/mans/g/sc/sl/br/n
126/13.00/0/158.0/45.2/21.30/7.00/CC:/S/E YearsOld.
45,34,22,26,0
78,74,82,11,0
and another type like (File 3):
Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.?
144 cm/35 Kg/5 YearsOld
S:22W:7;A:r;E:j; RRv:0/0; RRn:0/0
-
nFehl= 12
-
-
129,96,79,10,52
134,99,77,9,52
Using the code below, I am able to convert File 1 to dataframe and my expected output dataframe looks like:
A, B, C, D, E, City, Height, Weight, Age
45,34,22,26,0,NewYork, 144, 35, 5
78,74,82,11,0,NewYork, 144, 35, 5
The code is:
with open('File 1.woc', 'r') as f:
heading_rows = [next(f) for _ in range(5)]
city = re.findall(pattern = ' \w+ ', string = heading_rows[0])[0].strip()
numbers_list = [re.findall(pattern='\d+', string=row) for row in heading_rows if 'cm' and 'kg' in row.lower()][0]
height, weight, age = [int(numbers_lst[i]) for i in range(3)]
df = pd.read_csv('File 1.woc', sep='\s+|;|,', skiprows=2,comment='cm', index_col=None, names=list('ABCDE'))
df.dropna(inplace=True)
How can I edit all text files so that all look like File 1? I do not mind if characters in between are deleted.
A:
The following script will extract the relevant info from each file in question:
Provide the number_of_files - each of which are named File x.woc
To find the lines to keep:
Find the lines starting with "Person"
Find the lines that contain the word "cm"
Find the lines that have 5 numbers separated by a comma (using regex)
Here is the code
import re
pattern = re.compile(r'(\d+,?){5}')
number_of_files = 3
for i in range(number_of_files):
# Open file and extract lines of interest
filename = f"File {i+1}.woc"
with open(filename, 'r') as f:
lines = f.readlines()
lines_to_keep = []
for line in lines:
if line.startswith('Person:') or 'cm' in line or pattern.search(line):
lines_to_keep.append(line)
# Create a new file in the desired format
newfilename = f"new_File {i+1}.woc"
with open(newfilename, 'w') as fp:
for line in lines_to_keep:
fp.write(line)
new_File 1.woc:
Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.?
144 cm/35 Kg/5 YearsOld
45,34,22,26,0
78,74,82,11,0
new_File 2.woc:
Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.?
126cm/45 Kg/13 YearsOld
45,34,22,26,0
78,74,82,11,0
new_File 3.woc:
Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.?
144 cm/35 Kg/5 YearsOld
129,96,79,10,52
134,99,77,9,52
|
How to keep certain structure in various text files?
|
I have some .WOC files like(let's say File1):
Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.?
144 cm/35 Kg/5 YearsOld
45,34,22,26,0
78,74,82,11,0
and other ones like (File 2):
Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.?
126cm/45 Kg/13 YearsOld.
MON/age/sex/hei/weight/tsle/twak/dev/mans/g/sc/sl/br/n
126/13.00/0/158.0/45.2/21.30/7.00/CC:/S/E YearsOld.
45,34,22,26,0
78,74,82,11,0
and another type like (File 3):
Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.?
144 cm/35 Kg/5 YearsOld
S:22W:7;A:r;E:j; RRv:0/0; RRn:0/0
-
nFehl= 12
-
-
129,96,79,10,52
134,99,77,9,52
Using the code below, I am able to convert File 1 to dataframe and my expected output dataframe looks like:
A, B, C, D, E, City, Height, Weight, Age
45,34,22,26,0,NewYork, 144, 35, 5
78,74,82,11,0,NewYork, 144, 35, 5
The code is:
with open('File 1.woc', 'r') as f:
heading_rows = [next(f) for _ in range(5)]
city = re.findall(pattern = ' \w+ ', string = heading_rows[0])[0].strip()
numbers_list = [re.findall(pattern='\d+', string=row) for row in heading_rows if 'cm' and 'kg' in row.lower()][0]
height, weight, age = [int(numbers_lst[i]) for i in range(3)]
df = pd.read_csv('File 1.woc', sep='\s+|;|,', skiprows=2,comment='cm', index_col=None, names=list('ABCDE'))
df.dropna(inplace=True)
How can I edit all text files so that all look like File 1? I do not mind if characters in between are deleted.
|
[
"The following script will extract the relevant info from each file in question:\n\nProvide the number_of_files - each of which are named File x.woc\n\nTo find the lines to keep:\n\nFind the lines starting with \"Person\"\nFind the lines that contain the word \"cm\"\nFind the lines that have 5 numbers separated by a comma (using regex)\n\nHere is the code\nimport re\n\npattern = re.compile(r'(\\d+,?){5}')\n\nnumber_of_files = 3\n\nfor i in range(number_of_files):\n \n # Open file and extract lines of interest\n filename = f\"File {i+1}.woc\"\n with open(filename, 'r') as f:\n lines = f.readlines()\n\n lines_to_keep = []\n for line in lines:\n if line.startswith('Person:') or 'cm' in line or pattern.search(line):\n lines_to_keep.append(line)\n \n # Create a new file in the desired format\n newfilename = f\"new_File {i+1}.woc\"\n with open(newfilename, 'w') as fp:\n for line in lines_to_keep:\n fp.write(line)\n\nnew_File 1.woc:\nPerson:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.?\n144 cm/35 Kg/5 YearsOld\n45,34,22,26,0\n78,74,82,11,0\n\nnew_File 2.woc:\nPerson:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.?\n126cm/45 Kg/13 YearsOld\n45,34,22,26,0\n78,74,82,11,0\n\nnew_File 3.woc:\nPerson:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.?\n144 cm/35 Kg/5 YearsOld\n129,96,79,10,52\n134,99,77,9,52\n\n"
] |
[
1
] |
[] |
[] |
[
"csv",
"pandas",
"python",
"python_re"
] |
stackoverflow_0074570817_csv_pandas_python_python_re.txt
|
Q:
mypy "Incompatible default for argument" with keyword arg defaults
Consider the following illustration of typing.TypeVar straight from the typing docs:
# mypytest.py
from typing import TypeVar
A = TypeVar("A", str, bytes) # I.e. typing.AnyStr
def longest(x: A, y: A) -> A:
"""Return the longest of two strings."""
# https://docs.python.org/3/library/typing.html
return x if len(x) >= len(y) else y
Calling mypy mypytest.py raises no errors and exits 0. The purpose in this example is that A can be either str or bytes, but the return type will agree with the type passed.
However, mypy will raise an error when a default argument is present:
def longest_v2(x: A = "foo", y: A = "bar") -> A:
return x if len(x) >= len(y) else y
Raises:
$ mypy mypytest.py
mypytest.py:11: error: Incompatible default for argument "x" (default has type "str", argument has type "bytes")
mypytest.py:11: error: Incompatible default for argument "y" (default has type "str", argument has type "bytes")
Why does an error occur in this second case?
With line numbers:
1 # mypytest.py
2 from typing import TypeVar
3
4 A = TypeVar("A", str, bytes) # I.e. typing.AnyStr
5
6 def longest(x: A, y: A) -> A:
7 """Return the longest of two strings."""
8 # https://docs.python.org/3/library/typing.html
9 return x if len(x) >= len(y) else y
10
11 def longest_v2(x: A = "foo", y: A = "bar") -> A:
12 return x if len(x) >= len(y) else y
A:
I know this question is old, but it seems to attract enough attention.
The issue you describe is a well-known problem. Here's the tracking issue.
For functions, this is just a mypy limitation (here's why the issue is still open). To make things work without ignore comment, you can introduce two overloads:
from typing import TypeVar, overload
_T = TypeVar("_T", str, bytes) # I.e. typing.AnyStr
@overload
def longest_v2(x: str = ...) -> str: ...
@overload
def longest_v2(x: _T, y: _T) -> _T: ...
def longest_v2(x: str | bytes = 'foo', y: str | bytes = 'bar') -> str | bytes:
return x if len(x) >= len(y) else y
reveal_type(longest_v2()) # N: revealed type is "builtins.str"
reveal_type(longest_v2('foo')) # N: revealed type is "builtins.str"
longest_v2(b'foo') # E: No overload variant of "longest_v2" matches argument type "bytes" [call-overload]
reveal_type(longest_v2('foo', 'bar')) # N: revealed type is "builtins.str"
reveal_type(longest_v2(b'foo', b'bar')) # N: revealed type is "builtins.bytes"
Play with me!
The implementation signature is not important, because it is not visible to external callers. The first overload corresponds to calls with 0 or 1 arguments: second argument has a string default, so _T should resolve to str when it is not given, and it's what we do. The second overload covers cases when both args are provided.
The reason why this feature is not implemented yet, I suppose, is related to overloads in classes, esp. in class "constructors" __new__ and __init__, where similar behaviour is unsafe. Example from the issue:
from collections import OrderedDict
from typing import Generic, Mapping, TypeVar
_T1 = TypeVar('_T1', bound=Mapping)
class RawConfigParser(Generic[_T1]):
def __init__(self, dict_type: type[_T1] = OrderedDict) -> None: ...
def defaults(self) -> _T1: ...
class UserMapping(Mapping):
...
RawConfigParser[UserMapping]() # Oops!
This may be fixed too (by marking such call as invalid), but this requires more changes in mypy implementation.
|
mypy "Incompatible default for argument" with keyword arg defaults
|
Consider the following illustration of typing.TypeVar straight from the typing docs:
# mypytest.py
from typing import TypeVar
A = TypeVar("A", str, bytes) # I.e. typing.AnyStr
def longest(x: A, y: A) -> A:
"""Return the longest of two strings."""
# https://docs.python.org/3/library/typing.html
return x if len(x) >= len(y) else y
Calling mypy mypytest.py raises no errors and exits 0. The purpose in this example is that A can be either str or bytes, but the return type will agree with the type passed.
However, mypy will raise an error when a default argument is present:
def longest_v2(x: A = "foo", y: A = "bar") -> A:
return x if len(x) >= len(y) else y
Raises:
$ mypy mypytest.py
mypytest.py:11: error: Incompatible default for argument "x" (default has type "str", argument has type "bytes")
mypytest.py:11: error: Incompatible default for argument "y" (default has type "str", argument has type "bytes")
Why does an error occur in this second case?
With line numbers:
1 # mypytest.py
2 from typing import TypeVar
3
4 A = TypeVar("A", str, bytes) # I.e. typing.AnyStr
5
6 def longest(x: A, y: A) -> A:
7 """Return the longest of two strings."""
8 # https://docs.python.org/3/library/typing.html
9 return x if len(x) >= len(y) else y
10
11 def longest_v2(x: A = "foo", y: A = "bar") -> A:
12 return x if len(x) >= len(y) else y
|
[
"I know this question is old, but it seems to attract enough attention.\nThe issue you describe is a well-known problem. Here's the tracking issue.\nFor functions, this is just a mypy limitation (here's why the issue is still open). To make things work without ignore comment, you can introduce two overloads:\nfrom typing import TypeVar, overload\n\n_T = TypeVar(\"_T\", str, bytes) # I.e. typing.AnyStr\n\n@overload\ndef longest_v2(x: str = ...) -> str: ...\n@overload\ndef longest_v2(x: _T, y: _T) -> _T: ...\ndef longest_v2(x: str | bytes = 'foo', y: str | bytes = 'bar') -> str | bytes:\n return x if len(x) >= len(y) else y\n\nreveal_type(longest_v2()) # N: revealed type is \"builtins.str\"\nreveal_type(longest_v2('foo')) # N: revealed type is \"builtins.str\"\nlongest_v2(b'foo') # E: No overload variant of \"longest_v2\" matches argument type \"bytes\" [call-overload]\nreveal_type(longest_v2('foo', 'bar')) # N: revealed type is \"builtins.str\"\nreveal_type(longest_v2(b'foo', b'bar')) # N: revealed type is \"builtins.bytes\"\n\nPlay with me!\nThe implementation signature is not important, because it is not visible to external callers. The first overload corresponds to calls with 0 or 1 arguments: second argument has a string default, so _T should resolve to str when it is not given, and it's what we do. The second overload covers cases when both args are provided.\nThe reason why this feature is not implemented yet, I suppose, is related to overloads in classes, esp. in class \"constructors\" __new__ and __init__, where similar behaviour is unsafe. Example from the issue:\nfrom collections import OrderedDict\nfrom typing import Generic, Mapping, TypeVar\n\n_T1 = TypeVar('_T1', bound=Mapping)\n\nclass RawConfigParser(Generic[_T1]):\n def __init__(self, dict_type: type[_T1] = OrderedDict) -> None: ...\n def defaults(self) -> _T1: ...\n\nclass UserMapping(Mapping):\n ...\n\nRawConfigParser[UserMapping]() # Oops!\n\nThis may be fixed too (by marking such call as invalid), but this requires more changes in mypy implementation.\n"
] |
[
0
] |
[] |
[] |
[
"mypy",
"python",
"python_3.x",
"python_typing"
] |
stackoverflow_0057998243_mypy_python_python_3.x_python_typing.txt
|
Q:
I have a string role = "test1,test2" I need to replace the "," with a " "," " so the final output should be like this role = "test1","test2"
repalce a string with python
I have tried the replace function but it gives me an str error
A:
a="test1,test2"
a="\""+a.replace(",","\",\"")+"\""
print(a)
A:
So this is the answer to what you asked.
old_string = "test1,test2"
new_string = old_string.replace(',', '","')
# new_string = 'test1","test2'
When you want to use " in a string, you can use the single quote for the string.
However are you sure you are not looking for the split functionality.
|
I have a string role = "test1,test2" I need to replace the "," with a " "," " so the final output should be like this role = "test1","test2"
|
repalce a string with python
I have tried the replace function but it gives me an str error
|
[
"a=\"test1,test2\"\na=\"\\\"\"+a.replace(\",\",\"\\\",\\\"\")+\"\\\"\"\nprint(a)\n\n",
"So this is the answer to what you asked.\nold_string = \"test1,test2\"\nnew_string = old_string.replace(',', '\",\"')\n# new_string = 'test1\",\"test2'\n\nWhen you want to use \" in a string, you can use the single quote for the string.\nHowever are you sure you are not looking for the split functionality.\n"
] |
[
0,
0
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0074571396_python_python_3.x.txt
|
Q:
Convert a Tensorflow MapDataset to a tf.TensorArray
Suppose I have the following code below:
import numpy as np
import tensorflow as tf
simple_data_samples = np.array([
[1, 1, 1, -1, -1],
[2, 2, 2, -2, -2],
[3, 3, 3, -3, -3],
[4, 4, 4, -4, -4],
[5, 5, 5, -5, -5],
[6, 6, 6, -6, -6],
[7, 7, 7, -7, -7],
[8, 8, 8, -8, -8],
[9, 9, 9, -9, -9],
[10, 10, 10, -10, -10],
[11, 11, 11, -11, -11],
[12, 12, 12, -12, -12],
])
def timeseries_dataset_multistep_combined(features, label_slice, input_sequence_length, output_sequence_length, batch_size):
feature_ds = tf.keras.preprocessing.timeseries_dataset_from_array(features, None, input_sequence_length + output_sequence_length, batch_size=batch_size)
def split_feature_label(x):
x=tf.strings.as_string(x)
return x[:, :input_sequence_length, :], x[:, input_sequence_length:, label_slice]
feature_ds = feature_ds.map(split_feature_label)
return feature_ds
ds = timeseries_dataset_multistep_combined(simple_data_samples, slice(None, None, None), input_sequence_length=4, output_sequence_length=2,
batch_size=1)
def print_dataset(ds):
for inputs, targets in ds:
print("---Batch---")
print("Feature:", inputs.numpy())
print("Label:", targets.numpy())
print("")
print_dataset(ds)
The variable ds denotes a Tensorflow MapDataset. I would like to convert this variable ds into a tf.TensorArray. What would be the fastest and most efficient way?
A:
Assuming you want the output of the iterator as-is, here is the code.
list_array = list(sum(list(ds),()))
feature = tf.squeeze(tf.stack(list_array[::2]))
label = tf.squeeze(tf.stack(list_array[1::2]))
|
Convert a Tensorflow MapDataset to a tf.TensorArray
|
Suppose I have the following code below:
import numpy as np
import tensorflow as tf
simple_data_samples = np.array([
[1, 1, 1, -1, -1],
[2, 2, 2, -2, -2],
[3, 3, 3, -3, -3],
[4, 4, 4, -4, -4],
[5, 5, 5, -5, -5],
[6, 6, 6, -6, -6],
[7, 7, 7, -7, -7],
[8, 8, 8, -8, -8],
[9, 9, 9, -9, -9],
[10, 10, 10, -10, -10],
[11, 11, 11, -11, -11],
[12, 12, 12, -12, -12],
])
def timeseries_dataset_multistep_combined(features, label_slice, input_sequence_length, output_sequence_length, batch_size):
feature_ds = tf.keras.preprocessing.timeseries_dataset_from_array(features, None, input_sequence_length + output_sequence_length, batch_size=batch_size)
def split_feature_label(x):
x=tf.strings.as_string(x)
return x[:, :input_sequence_length, :], x[:, input_sequence_length:, label_slice]
feature_ds = feature_ds.map(split_feature_label)
return feature_ds
ds = timeseries_dataset_multistep_combined(simple_data_samples, slice(None, None, None), input_sequence_length=4, output_sequence_length=2,
batch_size=1)
def print_dataset(ds):
for inputs, targets in ds:
print("---Batch---")
print("Feature:", inputs.numpy())
print("Label:", targets.numpy())
print("")
print_dataset(ds)
The variable ds denotes a Tensorflow MapDataset. I would like to convert this variable ds into a tf.TensorArray. What would be the fastest and most efficient way?
|
[
"Assuming you want the output of the iterator as-is, here is the code.\nlist_array = list(sum(list(ds),()))\nfeature = tf.squeeze(tf.stack(list_array[::2]))\nlabel = tf.squeeze(tf.stack(list_array[1::2]))\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"tensorflow",
"tensorflow2.0",
"tensorflow_datasets"
] |
stackoverflow_0074507493_python_tensorflow_tensorflow2.0_tensorflow_datasets.txt
|
Q:
How to remove similar strings as if they were duplicates from a dataframe?
I have the following df :
df=pd.DataFrame({
'Q0_0': ["A vs. Z", "A vs. Bc", "B vs. Z", "B vs Bc", "Bc vs. A", "Bc vs. B", "Z vs. A", "Z vs. B", "C vs. A", "Bc vs. A"],
'Q1_1': [np.random.randint(1,100) for i in range(10)],
'Q1_2': np.random.random(10),
'Q1_3': np.random.randint(2, size=10),
'Q2_1': [np.random.randint(1,100) for i in range(10)],
'Q2_2': np.random.random(10),
'Q2_3': np.random.randint(2, size=10),
'Q3_1': [np.random.randint(1,100) for i in range(10)],
'Q3_2': np.random.random(10),
'Q3_3': np.random.randint(2, size=10),
'Q4_1': [np.random.randint(1,100) for i in range(10)],
'Q4_2': np.random.random(10),
'Q4_3': np.random.randint(2, size=10)
})
It has the following display:
Q0_0 Q1_1 Q1_2 Q1_3 Q2_1 Q2_2 Q2_3 Q3_1 Q3_2 Q3_3 Q4_1 Q4_2 Q4_3
0 A vs. Z 76 0.475198 0 31 0.785794 0 93 0.713219 0 31 0.549401 0
1 A vs. Bc 36 0.441907 0 28 0.008276 1 79 0.132327 0 61 0.657476 1
2 B vs. Z 68 0.474950 0 49 0.401341 1 1 0.409924 0 13 0.471476 0
3 B vs Bc 74 0.462356 0 42 0.762348 0 16 0.337623 1 76 0.548017 1
4 Bc vs. A 63 0.738769 1 34 0.340055 1 74 0.488053 1 84 0.663768 1
5 Bc vs. B 18 0.384001 1 75 0.188500 1 72 0.464784 1 32 0.355016 1
6 Z vs. A 34 0.700306 1 92 0.348228 1 99 0.347391 0 13 0.810568 0
7 Z vs. B 84 0.262367 0 11 0.217050 0 77 0.144048 0 44 0.262738 0
8 C vs. A 90 0.846719 1 53 0.603059 1 53 0.212426 1 86 0.515018 1
9 Bc vs. A 11 0.492974 0 76 0.351270 0 5 0.297710 1 40 0.185969 1
I want a rule allowing me to consider Z vs. A as duplicate of A vs. Z and so on for each b vs. a as a diplicate of a vs. b in column Q0_0.
Then proceed with removing those considered as duplicates.
Expected output is :
Q0_0 Q1_1 Q1_2 Q1_3 Q2_1 Q2_2 Q2_3 Q3_1 Q3_2 Q3_3 Q4_1 Q4_2 Q4_3
0 A vs. Z 76 0.475198 0 31 0.785794 0 93 0.713219 0 31 0.549401 0
1 A vs. Bc 36 0.441907 0 28 0.008276 1 79 0.132327 0 61 0.657476 1
2 B vs. Z 68 0.474950 0 49 0.401341 1 1 0.409924 0 13 0.471476 0
3 B vs Bc 74 0.462356 0 42 0.762348 0 16 0.337623 1 76 0.548017 1
8 C vs. A 90 0.846719 1 53 0.603059 1 53 0.212426 1 86 0.515018 1
There is a way to do that in my pandas dataframe ?
Any help from your side will be highly appreciated, thanks.
A:
You can use str.extract (or str.split) to get the left/right parts around vs., then convert to frozenset and use duplicated for boolean indexing:
s = df['Q0_0'].str.extract('(\w+)\s*vs\.?\s*(\w+)').agg(frozenset, axis=1)
# or
# s = df['Q0_0'].str.split(r'\s*vs\.?\s*', expand=True).agg(frozenset, axis=1)
out = df[~s.duplicated()]
Output:
Q0_0 Q1_1 Q1_2 Q1_3 Q2_1 Q2_2 Q2_3 Q3_1 Q3_2 Q3_3 Q4_1 Q4_2 Q4_3
0 A vs. Z 88 0.664299 0 99 0.102871 0 55 0.905342 0 55 0.789227 1
1 A vs. Bc 71 0.577607 0 99 0.784006 1 39 0.698947 0 82 0.055739 1
2 B vs. Z 81 0.248065 1 9 0.216285 0 13 0.128918 0 49 0.571096 0
3 B vs Bc 95 0.991130 1 80 0.346051 1 54 0.197197 1 30 0.928300 0
8 C vs. A 97 0.440715 0 88 0.986333 1 75 0.161888 0 42 0.831142 0
Intermediates:
s
0 (Z, A)
1 (Bc, A)
2 (Z, B)
3 (Bc, B)
4 (A, Bc)
5 (B, Bc)
6 (Z, A)
7 (Z, B)
8 (C, A)
9 (A, Bc)
dtype: object
~s.duplicated()
0 True
1 True
2 True
3 True
4 False
5 False
6 False
7 False
8 True
9 False
dtype: bool
A:
I would sort all symbols in the string alphabetically applying function that does something like '.join(sorted(str)) and then just drop_duplicates.
|
How to remove similar strings as if they were duplicates from a dataframe?
|
I have the following df :
df=pd.DataFrame({
'Q0_0': ["A vs. Z", "A vs. Bc", "B vs. Z", "B vs Bc", "Bc vs. A", "Bc vs. B", "Z vs. A", "Z vs. B", "C vs. A", "Bc vs. A"],
'Q1_1': [np.random.randint(1,100) for i in range(10)],
'Q1_2': np.random.random(10),
'Q1_3': np.random.randint(2, size=10),
'Q2_1': [np.random.randint(1,100) for i in range(10)],
'Q2_2': np.random.random(10),
'Q2_3': np.random.randint(2, size=10),
'Q3_1': [np.random.randint(1,100) for i in range(10)],
'Q3_2': np.random.random(10),
'Q3_3': np.random.randint(2, size=10),
'Q4_1': [np.random.randint(1,100) for i in range(10)],
'Q4_2': np.random.random(10),
'Q4_3': np.random.randint(2, size=10)
})
It has the following display:
Q0_0 Q1_1 Q1_2 Q1_3 Q2_1 Q2_2 Q2_3 Q3_1 Q3_2 Q3_3 Q4_1 Q4_2 Q4_3
0 A vs. Z 76 0.475198 0 31 0.785794 0 93 0.713219 0 31 0.549401 0
1 A vs. Bc 36 0.441907 0 28 0.008276 1 79 0.132327 0 61 0.657476 1
2 B vs. Z 68 0.474950 0 49 0.401341 1 1 0.409924 0 13 0.471476 0
3 B vs Bc 74 0.462356 0 42 0.762348 0 16 0.337623 1 76 0.548017 1
4 Bc vs. A 63 0.738769 1 34 0.340055 1 74 0.488053 1 84 0.663768 1
5 Bc vs. B 18 0.384001 1 75 0.188500 1 72 0.464784 1 32 0.355016 1
6 Z vs. A 34 0.700306 1 92 0.348228 1 99 0.347391 0 13 0.810568 0
7 Z vs. B 84 0.262367 0 11 0.217050 0 77 0.144048 0 44 0.262738 0
8 C vs. A 90 0.846719 1 53 0.603059 1 53 0.212426 1 86 0.515018 1
9 Bc vs. A 11 0.492974 0 76 0.351270 0 5 0.297710 1 40 0.185969 1
I want a rule allowing me to consider Z vs. A as duplicate of A vs. Z and so on for each b vs. a as a diplicate of a vs. b in column Q0_0.
Then proceed with removing those considered as duplicates.
Expected output is :
Q0_0 Q1_1 Q1_2 Q1_3 Q2_1 Q2_2 Q2_3 Q3_1 Q3_2 Q3_3 Q4_1 Q4_2 Q4_3
0 A vs. Z 76 0.475198 0 31 0.785794 0 93 0.713219 0 31 0.549401 0
1 A vs. Bc 36 0.441907 0 28 0.008276 1 79 0.132327 0 61 0.657476 1
2 B vs. Z 68 0.474950 0 49 0.401341 1 1 0.409924 0 13 0.471476 0
3 B vs Bc 74 0.462356 0 42 0.762348 0 16 0.337623 1 76 0.548017 1
8 C vs. A 90 0.846719 1 53 0.603059 1 53 0.212426 1 86 0.515018 1
There is a way to do that in my pandas dataframe ?
Any help from your side will be highly appreciated, thanks.
|
[
"You can use str.extract (or str.split) to get the left/right parts around vs., then convert to frozenset and use duplicated for boolean indexing:\ns = df['Q0_0'].str.extract('(\\w+)\\s*vs\\.?\\s*(\\w+)').agg(frozenset, axis=1)\n# or\n# s = df['Q0_0'].str.split(r'\\s*vs\\.?\\s*', expand=True).agg(frozenset, axis=1)\n\nout = df[~s.duplicated()]\n\nOutput:\n Q0_0 Q1_1 Q1_2 Q1_3 Q2_1 Q2_2 Q2_3 Q3_1 Q3_2 Q3_3 Q4_1 Q4_2 Q4_3\n0 A vs. Z 88 0.664299 0 99 0.102871 0 55 0.905342 0 55 0.789227 1\n1 A vs. Bc 71 0.577607 0 99 0.784006 1 39 0.698947 0 82 0.055739 1\n2 B vs. Z 81 0.248065 1 9 0.216285 0 13 0.128918 0 49 0.571096 0\n3 B vs Bc 95 0.991130 1 80 0.346051 1 54 0.197197 1 30 0.928300 0\n8 C vs. A 97 0.440715 0 88 0.986333 1 75 0.161888 0 42 0.831142 0\n\nIntermediates:\ns\n\n0 (Z, A)\n1 (Bc, A)\n2 (Z, B)\n3 (Bc, B)\n4 (A, Bc)\n5 (B, Bc)\n6 (Z, A)\n7 (Z, B)\n8 (C, A)\n9 (A, Bc)\ndtype: object\n\n~s.duplicated()\n\n0 True\n1 True\n2 True\n3 True\n4 False\n5 False\n6 False\n7 False\n8 True\n9 False\ndtype: bool\n\n",
"I would sort all symbols in the string alphabetically applying function that does something like '.join(sorted(str)) and then just drop_duplicates.\n"
] |
[
1,
0
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074571381_dataframe_pandas_python.txt
|
Q:
Clustering near Lines using coordinates in Python
I have a list with x- and y-coordinates of start and Endpoints of some lines.Lines as csv
331,178,486,232
185,215,386,308
172,343,334,419
406,128,570,165
306,106,569,166
159,210,379,299
236,143,526,248
303,83,516,178
409,62,572,106
26,287,372,427
31,288,271,381
193,228,432,330
120,196,432,329
136,200,374,297
111,189,336,289
284,186,560,249
333,202,577,254
229,194,522,219
349,111,553,165
121,322,342,416
78,303,285,391
103,315,340,415
The lines look like this on my example image. Lines plotted
I want to group lines which are close to each other into clusters and create one line for each cluster. For this example i would like to have 5 clusters. After that i want to calculate the distance from each clusterline to the next.
import csv, math
file = open("lines.csv")
csvreader = csv.reader(file)
lines = []
for data in csvreader:
lines.append({'x1':int(data[0]), 'y1':int(data[1]), 'x2':int(data[2]), 'y2':int(data[3])})
def point_delta(p1, p2):
return abs(p1 - p2)
for line in lines[:2]:
for line_rev in lines:
#x_start_delta = abs(line['x1'] - line_rev['x1'])
x_start_delta = point_delta(line['x1'], line_rev['x1'])
y_start_delta = abs(line['y1'] - line_rev['y1'])
start_distance = math.sqrt(x_start_delta**2 + y_start_delta**2)
x_end_delta = abs(line['x2'] - line_rev['x2'])
y_end_delta = abs(line['y2'] - line_rev['y2'])
end_distance = math.sqrt(x_end_delta**2 + y_end_delta**2)
avg_distance = (start_distance + end_distance)/2
cluster = 0
if avg_distance < 100:
print(f"distance: {avg_distance}")
print("############## next line ##############")
I have written some code to calculate the distance between each line but cant find a way to save the lines which are near to each other in different lists.
Does somebody know how to do this or is there another way to create clusters? Im also thinking about using the middlepoint instead of the start-/endpoint
A:
You could throw a clustering on it, but it has trouble with the lonely line at the end
data = [[331,178,486,232],
[185,215,386,308],
[172,343,334,419],
[406,128,570,165],
[306,106,569,166],
[159,210,379,299],
[236,143,526,248],
[303,83,516,178],
[409,62,572,106],
[26,287,372,427],
[31,288,271,381],
[193,228,432,330],
[120,196,432,329],
[136,200,374,297],
[111,189,336,289],
[284,186,560,249],
[333,202,577,254],
[229,194,522,219],
[349,111,553,165],
[121,322,342,416],
[78,303,285,391],
[103,315,340,415]]
import pandas as pd
import sklearn
from sklearn.cluster import MiniBatchKMeans
import numpy as np
lines = pd.DataFrame(data)
CLUSTERS = 5
X = lines.values
kmeans = MiniBatchKMeans(n_clusters=CLUSTERS,max_no_improvement=100).fit(X)
import numpy as np
import pylab as pl
from matplotlib import collections as mc
lines_segments = [ [ (l[0],l[1]),([l[2],l[3]]) ] for l in lines.values]
center_segments = [ [ (l[0],l[1]),([l[2],l[3]]) ] for l in kmeans.cluster_centers_]
line_collection = mc.LineCollection(lines_segments, linewidths=2)
centers = mc.LineCollection(center_segments, colors='red', linewidths=4, alpha=1)
fig, ax = pl.subplots()
ax.add_collection(line_collection)
ax.add_collection(centers)
ax.autoscale()
ax.margins(0.1)
You can see the centers with
kmeans.cluster_centers_
|
Clustering near Lines using coordinates in Python
|
I have a list with x- and y-coordinates of start and Endpoints of some lines.Lines as csv
331,178,486,232
185,215,386,308
172,343,334,419
406,128,570,165
306,106,569,166
159,210,379,299
236,143,526,248
303,83,516,178
409,62,572,106
26,287,372,427
31,288,271,381
193,228,432,330
120,196,432,329
136,200,374,297
111,189,336,289
284,186,560,249
333,202,577,254
229,194,522,219
349,111,553,165
121,322,342,416
78,303,285,391
103,315,340,415
The lines look like this on my example image. Lines plotted
I want to group lines which are close to each other into clusters and create one line for each cluster. For this example i would like to have 5 clusters. After that i want to calculate the distance from each clusterline to the next.
import csv, math
file = open("lines.csv")
csvreader = csv.reader(file)
lines = []
for data in csvreader:
lines.append({'x1':int(data[0]), 'y1':int(data[1]), 'x2':int(data[2]), 'y2':int(data[3])})
def point_delta(p1, p2):
return abs(p1 - p2)
for line in lines[:2]:
for line_rev in lines:
#x_start_delta = abs(line['x1'] - line_rev['x1'])
x_start_delta = point_delta(line['x1'], line_rev['x1'])
y_start_delta = abs(line['y1'] - line_rev['y1'])
start_distance = math.sqrt(x_start_delta**2 + y_start_delta**2)
x_end_delta = abs(line['x2'] - line_rev['x2'])
y_end_delta = abs(line['y2'] - line_rev['y2'])
end_distance = math.sqrt(x_end_delta**2 + y_end_delta**2)
avg_distance = (start_distance + end_distance)/2
cluster = 0
if avg_distance < 100:
print(f"distance: {avg_distance}")
print("############## next line ##############")
I have written some code to calculate the distance between each line but cant find a way to save the lines which are near to each other in different lists.
Does somebody know how to do this or is there another way to create clusters? Im also thinking about using the middlepoint instead of the start-/endpoint
|
[
"You could throw a clustering on it, but it has trouble with the lonely line at the end\n\n\ndata = [[331,178,486,232],\n[185,215,386,308],\n[172,343,334,419],\n[406,128,570,165],\n[306,106,569,166],\n[159,210,379,299],\n[236,143,526,248],\n[303,83,516,178],\n[409,62,572,106],\n[26,287,372,427],\n[31,288,271,381],\n[193,228,432,330],\n[120,196,432,329],\n[136,200,374,297],\n[111,189,336,289],\n[284,186,560,249],\n[333,202,577,254],\n[229,194,522,219],\n[349,111,553,165],\n[121,322,342,416],\n[78,303,285,391],\n[103,315,340,415]]\n\nimport pandas as pd\nimport sklearn\nfrom sklearn.cluster import MiniBatchKMeans\nimport numpy as np\n\nlines = pd.DataFrame(data)\n\nCLUSTERS = 5\n\nX = lines.values\n\nkmeans = MiniBatchKMeans(n_clusters=CLUSTERS,max_no_improvement=100).fit(X)\n\nimport numpy as np\nimport pylab as pl\nfrom matplotlib import collections as mc\n\nlines_segments = [ [ (l[0],l[1]),([l[2],l[3]]) ] for l in lines.values]\ncenter_segments = [ [ (l[0],l[1]),([l[2],l[3]]) ] for l in kmeans.cluster_centers_] \n\n\nline_collection = mc.LineCollection(lines_segments, linewidths=2)\ncenters = mc.LineCollection(center_segments, colors='red', linewidths=4, alpha=1)\n\nfig, ax = pl.subplots()\n\nax.add_collection(line_collection)\nax.add_collection(centers)\nax.autoscale()\nax.margins(0.1)\n\nYou can see the centers with\nkmeans.cluster_centers_\n\n"
] |
[
0
] |
[] |
[] |
[
"cluster_analysis",
"distance",
"line",
"list",
"python"
] |
stackoverflow_0074559073_cluster_analysis_distance_line_list_python.txt
|
Q:
How do I convert a string into a format to compare it with another date?
I used regex to find these dates in a string
matches = ['10 October 2019', '20 October 2019', '10 October 2019', '25 October 2019']
matches[0] and matches[2] are dates that a task was assigned, matches[1] and matches[3] are the due dates for the task. I need to check if the tasks are overdue, so I need to check if matches[1] and matches[3] are before today's date
This is what I have tried
index = 0
for random_value in range(0, len(matches)/2):
assert(matches[index]> date.today())
index += 2
This is the error message I am getting
TypeError: '>' not supported between instances of 'str' and 'datetime.date'
How do I convert the matches[index] into a format to be compared with the current date?
A:
You need to convert that string to actual date. as below code:
datetime.strptime('10 October 2019', '%d %B %Y') > datetime.today()
|
How do I convert a string into a format to compare it with another date?
|
I used regex to find these dates in a string
matches = ['10 October 2019', '20 October 2019', '10 October 2019', '25 October 2019']
matches[0] and matches[2] are dates that a task was assigned, matches[1] and matches[3] are the due dates for the task. I need to check if the tasks are overdue, so I need to check if matches[1] and matches[3] are before today's date
This is what I have tried
index = 0
for random_value in range(0, len(matches)/2):
assert(matches[index]> date.today())
index += 2
This is the error message I am getting
TypeError: '>' not supported between instances of 'str' and 'datetime.date'
How do I convert the matches[index] into a format to be compared with the current date?
|
[
"You need to convert that string to actual date. as below code:\ndatetime.strptime('10 October 2019', '%d %B %Y') > datetime.today()\n\n"
] |
[
0
] |
[] |
[] |
[
"date",
"python"
] |
stackoverflow_0074571394_date_python.txt
|
Q:
PyCharm cannot install packages
Short description: two computers in the same network, in the new one only those python scripts work that use native packages.
I have Pycharm in my old computer and it has worked fine. Now I got a new computer, installed the most recent version of Python and Pycharm, then opened one of my old projects. Both the old and the new computer are in the same network and the project is on a shared folder. So I did the following:
File - Open - selected the project. Got a message that there is no interpreter
Add local interpreter - selected the latest Python 311 exe. So location of the venv is the same as in the old computer (because it's a network folder) but Base interpreter is pointing to the C drive of my new computer.
PyCharm creates a virtual environment and the code runs fine.
I select another project which uses imported packages such as pandas. Again, same steps as above, add local interpreter. Venv is created.
I go to File - Setting - Project and see that pip, setuptools and wheel are listed as Packages. If I double click one of these, I can re-install and get a note that installation is succesful, so nothing seems to be wrong in the connection (after all, both the old and the new computer are in the same network.
I click the plus sign to add a new one, search pandas. Installation fails. Same thing if I try e.g. numpy.
Error message has lots of retrying, then "could not find the version that satisfies the requirement pandas (from versions: none", "not matching distribution found for pandas" (pip etc. have the latest versions).
After few hours of googling for solutions, I have tried the following:
Complety uninstall and reinstall python and PyCharm. Checked that PATH was included in the installation.
Tried launching pip command from shell
Changed http proxy to auto-detect
Typed 'import pandas' in PyCharm, then used the dropdown in the yellow bulb but there is no install option
Started a new project in the new computer, tried to install pandas
All failed. I'm surprised that changing computers is this difficult. Please let me know if there are other options than staying in the old computer...
A:
If you want to use venv in the network, please use SSH interpreter. Pycharm supports this method. Shared folders are not a recommended usage, For pycharm, it will consider this as a local file. If the file map is not downloaded locally, it will make an error.
Another way is to reinstall the project environment on the new computer through requirement.txt. Reasonable use of requirements.txt can effectively avoid many project bugs caused by environment migration or different dependent versions. Before installing some scientific module such as pandas, it is recommended to install visual studio build tools, such as gcc ...
A:
This took a while but here is what happened. Package installation did not work in project settings. Neither did it work when you select Python Packages tab at the bottom of the screen. The only thing that worked was to select the Terminal tab and manually install (pip install) there. We use a trusted repository but for other users, the easier package installation methods work. Not sure why they do not for me but at least there is this manual workaround.
|
PyCharm cannot install packages
|
Short description: two computers in the same network, in the new one only those python scripts work that use native packages.
I have Pycharm in my old computer and it has worked fine. Now I got a new computer, installed the most recent version of Python and Pycharm, then opened one of my old projects. Both the old and the new computer are in the same network and the project is on a shared folder. So I did the following:
File - Open - selected the project. Got a message that there is no interpreter
Add local interpreter - selected the latest Python 311 exe. So location of the venv is the same as in the old computer (because it's a network folder) but Base interpreter is pointing to the C drive of my new computer.
PyCharm creates a virtual environment and the code runs fine.
I select another project which uses imported packages such as pandas. Again, same steps as above, add local interpreter. Venv is created.
I go to File - Setting - Project and see that pip, setuptools and wheel are listed as Packages. If I double click one of these, I can re-install and get a note that installation is succesful, so nothing seems to be wrong in the connection (after all, both the old and the new computer are in the same network.
I click the plus sign to add a new one, search pandas. Installation fails. Same thing if I try e.g. numpy.
Error message has lots of retrying, then "could not find the version that satisfies the requirement pandas (from versions: none", "not matching distribution found for pandas" (pip etc. have the latest versions).
After few hours of googling for solutions, I have tried the following:
Complety uninstall and reinstall python and PyCharm. Checked that PATH was included in the installation.
Tried launching pip command from shell
Changed http proxy to auto-detect
Typed 'import pandas' in PyCharm, then used the dropdown in the yellow bulb but there is no install option
Started a new project in the new computer, tried to install pandas
All failed. I'm surprised that changing computers is this difficult. Please let me know if there are other options than staying in the old computer...
|
[
"If you want to use venv in the network, please use SSH interpreter. Pycharm supports this method. Shared folders are not a recommended usage, For pycharm, it will consider this as a local file. If the file map is not downloaded locally, it will make an error.\nAnother way is to reinstall the project environment on the new computer through requirement.txt. Reasonable use of requirements.txt can effectively avoid many project bugs caused by environment migration or different dependent versions. Before installing some scientific module such as pandas, it is recommended to install visual studio build tools, such as gcc ...\n",
"This took a while but here is what happened. Package installation did not work in project settings. Neither did it work when you select Python Packages tab at the bottom of the screen. The only thing that worked was to select the Terminal tab and manually install (pip install) there. We use a trusted repository but for other users, the easier package installation methods work. Not sure why they do not for me but at least there is this manual workaround.\n"
] |
[
1,
0
] |
[] |
[] |
[
"pandas",
"pycharm",
"python",
"python_3.x",
"windows_10"
] |
stackoverflow_0074377753_pandas_pycharm_python_python_3.x_windows_10.txt
|
Q:
Faster way to package a folder into a file with Python
I would like to package a folder into a file, I do not need compression. All alternatives I tried were slow.
I have tried:
The zipfile library with ZIP_STORED (no compression)
import zipfile
output_filename="folder.zip"
source_dir = "folder"
with zipfile.ZipFile(output_filename, 'w', zipfile.ZIP_STORED) as zipf:
zipdir(source_dir, zipf)
The tarfile library also using w to open the file for writing
without compression
import tarfile
import os
output_filename="folder.tar"
source_dir = "folder"
with tarfile.open(output_filename, "w") as tar:
tar.add(source_dir, arcname=os.path.basename(source_dir))
But both still take ~3-5 minutes to package a folder that is ~5GB and has < 10 files in it.
I am using a Linux machine.
Is there a faster way?
|
Faster way to package a folder into a file with Python
|
I would like to package a folder into a file, I do not need compression. All alternatives I tried were slow.
I have tried:
The zipfile library with ZIP_STORED (no compression)
import zipfile
output_filename="folder.zip"
source_dir = "folder"
with zipfile.ZipFile(output_filename, 'w', zipfile.ZIP_STORED) as zipf:
zipdir(source_dir, zipf)
The tarfile library also using w to open the file for writing
without compression
import tarfile
import os
output_filename="folder.tar"
source_dir = "folder"
with tarfile.open(output_filename, "w") as tar:
tar.add(source_dir, arcname=os.path.basename(source_dir))
But both still take ~3-5 minutes to package a folder that is ~5GB and has < 10 files in it.
I am using a Linux machine.
Is there a faster way?
|
[] |
[] |
[
"I am not quite sure if it is that faster but if you are running linux you could try tar command:\nimport time\nimport os\n\nstart = time.time()\n\nos.system(\"tar -cvf name.tar /path/to/directory\")\n\nend = time.time()\nprint(\"Elapsed time: %s\"%(end - start,))\n\nIf you also need file compression you need to add gzip after the first command:\nos.system(\"gzip name.tar\")\n\n"
] |
[
-1
] |
[
"compression",
"python",
"tar",
"zip"
] |
stackoverflow_0074571456_compression_python_tar_zip.txt
|
Q:
Django FormView and ListView multiple inheritance error
Problem
I mad a AccesCheck Mixin, and view named ListFormView that inherits AccessCheck, FormView and ListView to show list and create/update Worker objects.
But when I try to add new data by POST method, django keeps returning Attribute Error : Worker object has no attribute 'object_list' error.
What is more confusing to me is that whole ListFormView is duplication of another class based view that is used in another app, and the original one is running without any problems. I've doublechecked all my codes and still have no clue to fix this problem.
[AccessCheck]
class AccessCheck(LoginRequiredMixin, UserPassesTestMixin, View):
def test_func(self, *args, **kwargs):
access = [x.id for x in Auth.objects.filter(auth_id = self.kwargs['target'])]
return self.request.user.is_superuser or selr.request.user.id in access
def handle_no_permission(self):
return redirect('index')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['shop'] = Shop.objects.get(shop_id = self.kwars['shop_id'])
return context
[ListFormView]
class ListFormView(AccessCheck, FormView, ListView):
template_name = 'my_template_name.html'
context_object_name = 'workers'
form_class = WorkerForm
success_url = './my_url'
def form_valid(self, form):
data = form.save()
return super().form_valid(form)
def get_queryset(self, *args, **kwargs):
return Worker.objects.filter(shop_id = self.kwargs['shop_id'])
How it was solved
[ListFormView]
class ListFormView(AccessCheck, FormView, ListView):
template_name = 'my_template_name.html'
context_object_name = 'workers'
form_class = WorkerForm
success_url = './my_url'
def get_context_data(self, **kwargs):
self.object_list = Worker.objects.filter(shop_id = self.kwargs['shop_id'])
context = super().get_context_data(**kwargs)
return context
def form_valid(self, form):
data = form.save()
return super().form_valid(form)
def get_queryset(self, *args, **kwargs):
return Worker.objects.filter(shop_id = self.kwargs['shop_id'])
A:
That's classic problem of OOP. You have two inherited classes with the same method get_context_data(). The target class always getting code of the method from first inherited class. In this case ListFormView.get_context_data() has the same code as the AccessCheck.get_context_data() and ListFormView class doesn't konw anithing about code in AccessCheck.get_context_data() method (where self.object_list = ... is defined).
Here is example:
class First:
def f(self):
print('Code from First')
class Second:
def f(self):
print('Code from Second')
class A(First, Second):
pass
A().f() >>> "Code from First"
The possible solutions is to move correct class to the top of inheritance list:
# ╔═══════╗ swithch them
class A(Second, First):
pass
A().f() >>> "Code from Second"
Or you can define your own f method in class A and use super with argument to define where you wanted to start method resoulution. To define what to write as first argument of super run A.__mro__ and chose class before target in this list:
class A(First, Second):
def f(self):
super(First, self).f()
A.__mro__ >>> (<class '__main__.A'>, <class '__main__.First'>, <class '__main__.Second'>, <class 'object'>)
A().f() >>> "Code from Second"
I recommended you to read about OOP in python and multiple inheritance.
* your possible solution is
# make from this line
class ListFormView(AccessCheck, FormView, ListView)
# this one
class ListFormView(ListView, AccessCheck, FormView)
A:
Multiple inheritance is a rich source of bugs if you don't make everything except the last superclass a Mixin class (derived from object). I'd have suggested
class AccessCheckMixin(LoginRequiredMixin, UserPassesTestMixin):
# merging two mixins and adding methods is fine
def test_func(self, *args, **kwargs):
access = [x.id for x in Auth.objects.filter(auth_id = self.kwargs['target'])]
return self.request.user.is_superuser or selr.request.user.id in access
def handle_no_permission(self):
return redirect('index')
# get_context_data belongs in a View subclass
class ListFormView(AccessCheckMixin, FormView, ListView):
# I have misgivings about merging FormView and ListView, but maybe
...
def get_context_data(self, **kwargs):
# it belongs here, but super() is going to invoke only one of the
# get_context_data implemenations in one of its parents.
Bookmark Classy Class-based views for browsing what's in the Django CBVs.
|
Django FormView and ListView multiple inheritance error
|
Problem
I mad a AccesCheck Mixin, and view named ListFormView that inherits AccessCheck, FormView and ListView to show list and create/update Worker objects.
But when I try to add new data by POST method, django keeps returning Attribute Error : Worker object has no attribute 'object_list' error.
What is more confusing to me is that whole ListFormView is duplication of another class based view that is used in another app, and the original one is running without any problems. I've doublechecked all my codes and still have no clue to fix this problem.
[AccessCheck]
class AccessCheck(LoginRequiredMixin, UserPassesTestMixin, View):
def test_func(self, *args, **kwargs):
access = [x.id for x in Auth.objects.filter(auth_id = self.kwargs['target'])]
return self.request.user.is_superuser or selr.request.user.id in access
def handle_no_permission(self):
return redirect('index')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['shop'] = Shop.objects.get(shop_id = self.kwars['shop_id'])
return context
[ListFormView]
class ListFormView(AccessCheck, FormView, ListView):
template_name = 'my_template_name.html'
context_object_name = 'workers'
form_class = WorkerForm
success_url = './my_url'
def form_valid(self, form):
data = form.save()
return super().form_valid(form)
def get_queryset(self, *args, **kwargs):
return Worker.objects.filter(shop_id = self.kwargs['shop_id'])
How it was solved
[ListFormView]
class ListFormView(AccessCheck, FormView, ListView):
template_name = 'my_template_name.html'
context_object_name = 'workers'
form_class = WorkerForm
success_url = './my_url'
def get_context_data(self, **kwargs):
self.object_list = Worker.objects.filter(shop_id = self.kwargs['shop_id'])
context = super().get_context_data(**kwargs)
return context
def form_valid(self, form):
data = form.save()
return super().form_valid(form)
def get_queryset(self, *args, **kwargs):
return Worker.objects.filter(shop_id = self.kwargs['shop_id'])
|
[
"That's classic problem of OOP. You have two inherited classes with the same method get_context_data(). The target class always getting code of the method from first inherited class. In this case ListFormView.get_context_data() has the same code as the AccessCheck.get_context_data() and ListFormView class doesn't konw anithing about code in AccessCheck.get_context_data() method (where self.object_list = ... is defined).\nHere is example:\nclass First:\n def f(self):\n print('Code from First')\n\nclass Second:\n def f(self):\n print('Code from Second')\n\nclass A(First, Second):\n pass\n\n\nA().f() >>> \"Code from First\"\n\nThe possible solutions is to move correct class to the top of inheritance list:\n# ╔═══════╗ swithch them\nclass A(Second, First):\n pass\n\nA().f() >>> \"Code from Second\"\n\nOr you can define your own f method in class A and use super with argument to define where you wanted to start method resoulution. To define what to write as first argument of super run A.__mro__ and chose class before target in this list:\nclass A(First, Second): \n def f(self):\n super(First, self).f()\n\nA.__mro__ >>> (<class '__main__.A'>, <class '__main__.First'>, <class '__main__.Second'>, <class 'object'>)\nA().f() >>> \"Code from Second\"\n\nI recommended you to read about OOP in python and multiple inheritance.\n* your possible solution is\n# make from this line\nclass ListFormView(AccessCheck, FormView, ListView)\n# this one\nclass ListFormView(ListView, AccessCheck, FormView)\n\n",
"Multiple inheritance is a rich source of bugs if you don't make everything except the last superclass a Mixin class (derived from object). I'd have suggested\nclass AccessCheckMixin(LoginRequiredMixin, UserPassesTestMixin):\n # merging two mixins and adding methods is fine\n def test_func(self, *args, **kwargs):\n access = [x.id for x in Auth.objects.filter(auth_id = self.kwargs['target'])]\n return self.request.user.is_superuser or selr.request.user.id in access\n\n def handle_no_permission(self):\n return redirect('index')\n\n # get_context_data belongs in a View subclass\n\nclass ListFormView(AccessCheckMixin, FormView, ListView):\n # I have misgivings about merging FormView and ListView, but maybe \n ...\n def get_context_data(self, **kwargs):\n # it belongs here, but super() is going to invoke only one of the\n # get_context_data implemenations in one of its parents. \n\nBookmark Classy Class-based views for browsing what's in the Django CBVs.\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0074567629_django_python.txt
|
Q:
What is the special file that each package in Python must contain?
Please answer of this question.
special file in Python ?
A:
I think you are referring to a
__init__.py
file. Often left blank.
|
What is the special file that each package in Python must contain?
|
Please answer of this question.
special file in Python ?
|
[
"I think you are referring to a\n\n__init__.py\n\nfile. Often left blank.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"python_2.7"
] |
stackoverflow_0074571570_python_python_2.7.txt
|
Q:
if .isin() dataframe one, check condition in dataframe 2, append new dataframe with checked conditions
i have two dataframes
df1 has a list of ids and dates
id
e1
e2
e3
1
2012-09-12
2001-03-06
1999-09-03
2
2009-09-07
2002-04-06
2003-01-02
3
2005-08-09
2005-06-04
2008-01-02
df2 has the same ids, and other values
id
e1
e2
e3
1
A120
B130
C122
2
BD43
A200
A111
3
C890
B123
A190
I want to iterate through df2, look for values that start with 'A' (for example (A120, A200..etc) in each column, once I find the value, I will go to df1 in the same rowxcolumn and see if the date is >= 2005-01-01, and add all the ids that checks those two conditions to a new dataframe.
so the ideal results would be something like this:
id
e1
e2
e3
1
A120
B130
C112
3
C890
B123
A190
the only way I could manage was a for loop looping through both matrices, but it is very slow since the dataframes are very large. is there a different approach to this problem
A:
You can use boolean indexing:
ref = '2005-01-01'
# is the date < ref?
m1 = df1.set_index('id').le(ref)
# is the string starting with A?
m2 = df2.set_index('id').apply(lambda s: s.str.startswith('A'))
# if both conditions are matched anywhere in the row, drop it
out = df1[~(m1&m2).any(axis=1).to_numpy()]
NB. if id is the index, don't perform the set_index('id') step.
Output:
id e1 e2 e3
0 1 2012-09-12 2001-03-06 1999-09-03
2 3 2005-08-09 2005-06-04 2008-01-02
|
if .isin() dataframe one, check condition in dataframe 2, append new dataframe with checked conditions
|
i have two dataframes
df1 has a list of ids and dates
id
e1
e2
e3
1
2012-09-12
2001-03-06
1999-09-03
2
2009-09-07
2002-04-06
2003-01-02
3
2005-08-09
2005-06-04
2008-01-02
df2 has the same ids, and other values
id
e1
e2
e3
1
A120
B130
C122
2
BD43
A200
A111
3
C890
B123
A190
I want to iterate through df2, look for values that start with 'A' (for example (A120, A200..etc) in each column, once I find the value, I will go to df1 in the same rowxcolumn and see if the date is >= 2005-01-01, and add all the ids that checks those two conditions to a new dataframe.
so the ideal results would be something like this:
id
e1
e2
e3
1
A120
B130
C112
3
C890
B123
A190
the only way I could manage was a for loop looping through both matrices, but it is very slow since the dataframes are very large. is there a different approach to this problem
|
[
"You can use boolean indexing:\nref = '2005-01-01'\n\n# is the date < ref?\nm1 = df1.set_index('id').le(ref)\n# is the string starting with A?\nm2 = df2.set_index('id').apply(lambda s: s.str.startswith('A'))\n\n# if both conditions are matched anywhere in the row, drop it\nout = df1[~(m1&m2).any(axis=1).to_numpy()]\n\nNB. if id is the index, don't perform the set_index('id') step.\nOutput:\n id e1 e2 e3\n0 1 2012-09-12 2001-03-06 1999-09-03\n2 3 2005-08-09 2005-06-04 2008-01-02\n\n"
] |
[
0
] |
[] |
[] |
[
"dataframe",
"for_loop",
"pandas",
"python"
] |
stackoverflow_0074571438_dataframe_for_loop_pandas_python.txt
|
Q:
working outside of application context - Flask
def get_db(self,dbfile):
if hasattr(g, 'sqlite_db'): self.close_db(g.sqlite_db)
try:
g.sqlite_db = self.connect_db('{}/{}'.format(app.root_path, dbfile))
except sqlite3.OperationalError as e:
raise e
return g.sqlite_db
Hi this code is located inside DB class, The error I get is
RuntimeError: working outside of application context
the error occurs on this line
g.sqlite_db = self.connect_db('{}/{}'.format(app.root_path, dbfile))
I think the problem is with g, it is imported like that from flask import g
How this error can be fixed?
Thanks.
A:
Maybe you need to call your function inside an application context:
with app.app_context():
# call your method here
A:
From the Flask source code in flask/globals.py:
_app_ctx_err_msg = '''\
Working outside of application context.
This typically means that you attempted to use functionality that needed
to interface with the current application object in a way. To solve
this set up an application context with app.app_context(). See the
documentation for more information.\
'''
Following the documentation, you can see that you need to make flask.current_app point to your application and it currently doesn't.
You're probably calling your DB function before Flask has initialized. My guess is that your app object has not been created yet with the Flask constructor.
A:
When creating your app, use:
app.app_context().push()
for example like this:
from yourapp import create_app
app = create_app()
app.app_context().push()
for further information
A:
Simple Example To Avoid This Error
Please check out the Purpose of context
#filename = run.py (inside root directory)
from flaskblog import create_app
app = create_app()
if __name__ == "__main__":
app.run(debug=True)
Inside flaskblog folder
filename = __init __.py (inside flaskblog folder)
app = Flask(__name__)
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.login_view = "users.login"
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
from flaskblog.user.routes import users
app.register_blueprint(users)
return app
filename = config.py (inside flaskblog folder)
class Config:
SECRET_KEY = 'your secret key'
SQLALCHEMY_DATABASE_URI = 'your db uri'
filename = models.py
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
users folder (inside flaskblog)
users folder contain one __init__.py file
Filename = form.py (inside users folder)
class LoginForm(FlaskForm):
# define your field
pass
Filename = routes.py (inside users folder)
users = Blueprint('users',__name__)
@users.route('/login', methods=['GET', 'POST'])
def login():
# do your stuff
pass
A:
To expand on @VadimK's answer. If you want to prevent your code from executing outside of an app_context you can use flask.has_app_context() to see if the code is currently inside an app context:
See also: flask.has_request_context()
A:
Other users have pointed out how to solve the immediate problem, however you might consider modifying how the database connection is created to solve this issue.
Instead of having a method within you DB class instantiate the database connection you could have the connection created in the controller before every request. Then use the teardown_request decorator to close the connection.
Then when within a route you could pass the connection to the DB class as part of instantiating a new DB object.
This would ensure that you never create a database connection unless you need one. And it prevent you from accessing Flask globals out of the app context.
@app.before_request
def before_request():
try:
g.sqlite_db = self.connect_db('{}/{}'.format(app.root_path, dbfile))
except sqlite3.OperationalError as e:
raise e
@app.teardown_request
def teardown_request(e):
if hasattr(g, 'sqlite_db'): self.close_db(g.sqlite_db)
@app.route('/someroute', methods=["GET"]:
def someroute():
db_obj = DB(g.sqlite_db)
.
.
.
A:
Use
pip install flask-sqlalchemy==2.5.1
This might solve the error
A:
Two possible solution
First method
Instead of calling create_all() in your code, call manually in the flask shell which is CLI
Go to your terminal
type flask shell, then
db.create_all()
Second method
As it says in the runtime error message
This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context().
Open the python terminal in your project directory and manually add a context
from project_name import app, db
app.app_context().push()
db.create_all()
Check out this video for better understanding.
YouTube Video
A:
I had the same issue while doing some unit testing.
Adding the following function to my test class solved my issue:
@classmethod
def setUpClass(self):
self.app = create_app("testing")
self.client = self.app.test_client()
A:
This is what fixed it for me. I hope it helps someone else.
if __name__ == "__main__":
with app.app_context():
db.create_all()
app.run(debug=True)
|
working outside of application context - Flask
|
def get_db(self,dbfile):
if hasattr(g, 'sqlite_db'): self.close_db(g.sqlite_db)
try:
g.sqlite_db = self.connect_db('{}/{}'.format(app.root_path, dbfile))
except sqlite3.OperationalError as e:
raise e
return g.sqlite_db
Hi this code is located inside DB class, The error I get is
RuntimeError: working outside of application context
the error occurs on this line
g.sqlite_db = self.connect_db('{}/{}'.format(app.root_path, dbfile))
I think the problem is with g, it is imported like that from flask import g
How this error can be fixed?
Thanks.
|
[
"Maybe you need to call your function inside an application context:\nwith app.app_context():\n # call your method here\n\n",
"From the Flask source code in flask/globals.py: \n_app_ctx_err_msg = '''\\\nWorking outside of application context.\n\nThis typically means that you attempted to use functionality that needed\nto interface with the current application object in a way. To solve\nthis set up an application context with app.app_context(). See the\ndocumentation for more information.\\\n'''\n\nFollowing the documentation, you can see that you need to make flask.current_app point to your application and it currently doesn't.\nYou're probably calling your DB function before Flask has initialized. My guess is that your app object has not been created yet with the Flask constructor.\n",
"When creating your app, use: \napp.app_context().push()\n\nfor example like this:\nfrom yourapp import create_app\n\napp = create_app()\n\napp.app_context().push()\n\nfor further information\n",
"Simple Example To Avoid This Error\nPlease check out the Purpose of context\n#filename = run.py (inside root directory)\nfrom flaskblog import create_app\n\napp = create_app()\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n\nInside flaskblog folder\nfilename = __init __.py (inside flaskblog folder)\napp = Flask(__name__)\n\ndb = SQLAlchemy()\nlogin_manager = LoginManager()\nlogin_manager.login_view = \"users.login\"\n\ndef create_app(config_class=Config):\n app = Flask(__name__)\n app.config.from_object(Config)\n db.init_app(app)\n\n from flaskblog.user.routes import users \n app.register_blueprint(users)\n return app\n\nfilename = config.py (inside flaskblog folder)\nclass Config:\n SECRET_KEY = 'your secret key'\n SQLALCHEMY_DATABASE_URI = 'your db uri'\n\nfilename = models.py\n@login_manager.user_loader\ndef load_user(user_id):\n return User.query.get(int(user_id))\n\nclass User(db.Model, UserMixin):\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(20), unique=True, nullable=False)\n\nusers folder (inside flaskblog)\nusers folder contain one __init__.py file\nFilename = form.py (inside users folder)\nclass LoginForm(FlaskForm):\n # define your field\n pass\n\nFilename = routes.py (inside users folder)\nusers = Blueprint('users',__name__)\n\n@users.route('/login', methods=['GET', 'POST']) \ndef login():\n # do your stuff\n pass\n\n",
"To expand on @VadimK's answer. If you want to prevent your code from executing outside of an app_context you can use flask.has_app_context() to see if the code is currently inside an app context:\nSee also: flask.has_request_context()\n",
"Other users have pointed out how to solve the immediate problem, however you might consider modifying how the database connection is created to solve this issue.\nInstead of having a method within you DB class instantiate the database connection you could have the connection created in the controller before every request. Then use the teardown_request decorator to close the connection.\nThen when within a route you could pass the connection to the DB class as part of instantiating a new DB object.\nThis would ensure that you never create a database connection unless you need one. And it prevent you from accessing Flask globals out of the app context.\n@app.before_request\ndef before_request():\n try:\n g.sqlite_db = self.connect_db('{}/{}'.format(app.root_path, dbfile))\n except sqlite3.OperationalError as e:\n raise e\n\n@app.teardown_request\ndef teardown_request(e):\n if hasattr(g, 'sqlite_db'): self.close_db(g.sqlite_db)\n\n@app.route('/someroute', methods=[\"GET\"]:\ndef someroute():\n db_obj = DB(g.sqlite_db)\n .\n .\n .\n\n",
"Use\npip install flask-sqlalchemy==2.5.1\n\nThis might solve the error\n",
"Two possible solution\nFirst method\n\nInstead of calling create_all() in your code, call manually in the flask shell which is CLI\n\n\nGo to your terminal\n\n\ntype flask shell, then\ndb.create_all()\n\nSecond method\n\nAs it says in the runtime error message\n\n\nThis typically means that you attempted to use functionality that needed\nthe current application. To solve this, set up an application context\nwith app.app_context().\n\nOpen the python terminal in your project directory and manually add a context\nfrom project_name import app, db\napp.app_context().push()\ndb.create_all()\n\nCheck out this video for better understanding.\nYouTube Video\n",
"I had the same issue while doing some unit testing.\nAdding the following function to my test class solved my issue:\n@classmethod\ndef setUpClass(self):\n self.app = create_app(\"testing\")\n self.client = self.app.test_client()\n\n",
"This is what fixed it for me. I hope it helps someone else.\nif __name__ == \"__main__\":\nwith app.app_context():\n db.create_all()\n app.run(debug=True)\n\n"
] |
[
32,
22,
20,
3,
2,
2,
1,
1,
0,
0
] |
[
"Install this version of flask using\npip install flask-sqlalchemy==2.5.1\n\nthen run db.create_all() and it will run.\n",
"ERROR:This typically means that you attempted to use functionality that needed\nto interface with the current application object in a way. To solve\nthis set up an application context with app.app_context(). See the\ndocumentation for more information.\n"
] |
[
-1,
-33
] |
[
"flask",
"python"
] |
stackoverflow_0034122949_flask_python.txt
|
Q:
How to stop a loop when i press a button in python
In the code in the follow lines is tried to implement an average calculator which calculate the average of given numbers with the division of the sum of given numbers through the count of multitude of them. The problem is that when is pressed the S button does not break the loop which count the multitude of numbers count. In addition, it is preferable to have the line which ask the numbers and the letter which stop the procedure in one line
import itertools
total=0
numbers=[]
for i in itertools.count(1):
numbers.append (input ("Enter number:")))
print("You give" , i)
s=str(input("If you want to stop press S:"))
#i = i + 1
s=False
if s is True:
break
total=sum(numbers)/i
print (" ")
print (" ")
print ("Average is", total)
A:
Try this:
import itertools
total=0
numbers=[]
for i in itertools.count(1):
numbers.append(int(input ("Enter number:")))
print("You give" , i)
s=str(input("If you want to stop press S:"))
if s.lower() == "s":
total = sum(numbers)/i
print (" ")
print (" ")
print ("Average is", total)
break
|
How to stop a loop when i press a button in python
|
In the code in the follow lines is tried to implement an average calculator which calculate the average of given numbers with the division of the sum of given numbers through the count of multitude of them. The problem is that when is pressed the S button does not break the loop which count the multitude of numbers count. In addition, it is preferable to have the line which ask the numbers and the letter which stop the procedure in one line
import itertools
total=0
numbers=[]
for i in itertools.count(1):
numbers.append (input ("Enter number:")))
print("You give" , i)
s=str(input("If you want to stop press S:"))
#i = i + 1
s=False
if s is True:
break
total=sum(numbers)/i
print (" ")
print (" ")
print ("Average is", total)
|
[
"Try this:\nimport itertools\ntotal=0\nnumbers=[]\n\nfor i in itertools.count(1):\n numbers.append(int(input (\"Enter number:\")))\n\n print(\"You give\" , i)\n\n s=str(input(\"If you want to stop press S:\"))\n if s.lower() == \"s\":\n total = sum(numbers)/i\n print (\" \")\n print (\" \")\n print (\"Average is\", total)\n break\n\n"
] |
[
0
] |
[] |
[] |
[
"average",
"character",
"iteration",
"python"
] |
stackoverflow_0074571522_average_character_iteration_python.txt
|
Q:
Why isnt the append() working in this block of code?
I've broken down the pieces of this code individually and it all works fine. Yet the append() method only appends once and then refuses to add anything else. I am absolutely losing my mind over this.
x = input("Input Password: ")
epicfail = []
def numberchecker(b):
return any(i.isdigit() for i in b)
def spacechecker(c):
return any(o.isspace() for o in c)
def passwordvalidator(a):
if len(a) < 12:
epicfail.append("Your password is too short!")
elif a.islower() == True:
epicfail.append("Your password contains zero uppercase letters!")
elif a.isupper() == True:
epicfail.append("Your password contains zero lowercase letters!")
elif numberchecker(x) == False:
epicfail.append("Your password contains zero numbers!")
elif spacechecker(x) == True:
epicfail.append("Your password contains a whitespace!")
return epicfail
print(passwordvalidator(x))
I expect the append() method to append to the epicfail list every time it is activated. Yet is only appends once. I have tried breaking down every piece of the code individually and it all works fine.
A:
As you use elif, when one condition is met, all the others are ignored. If you want multiple to trigger, just use if instead.
Furthermore, you can remove "== True" when you are checking a boolean, and replace "if xxx == False:" by "if not xxx:".
|
Why isnt the append() working in this block of code?
|
I've broken down the pieces of this code individually and it all works fine. Yet the append() method only appends once and then refuses to add anything else. I am absolutely losing my mind over this.
x = input("Input Password: ")
epicfail = []
def numberchecker(b):
return any(i.isdigit() for i in b)
def spacechecker(c):
return any(o.isspace() for o in c)
def passwordvalidator(a):
if len(a) < 12:
epicfail.append("Your password is too short!")
elif a.islower() == True:
epicfail.append("Your password contains zero uppercase letters!")
elif a.isupper() == True:
epicfail.append("Your password contains zero lowercase letters!")
elif numberchecker(x) == False:
epicfail.append("Your password contains zero numbers!")
elif spacechecker(x) == True:
epicfail.append("Your password contains a whitespace!")
return epicfail
print(passwordvalidator(x))
I expect the append() method to append to the epicfail list every time it is activated. Yet is only appends once. I have tried breaking down every piece of the code individually and it all works fine.
|
[
"As you use elif, when one condition is met, all the others are ignored. If you want multiple to trigger, just use if instead.\nFurthermore, you can remove \"== True\" when you are checking a boolean, and replace \"if xxx == False:\" by \"if not xxx:\".\n"
] |
[
1
] |
[] |
[] |
[
"methods",
"new_operator",
"python"
] |
stackoverflow_0074571480_methods_new_operator_python.txt
|
Q:
How to delete/not save files when Jupyter notebook in ran with plotly pio.renderers.default = "iframe"?
I am plotting a plot using plotly python (inside jupyter notebook) like below-
fig = make_subplots(rows=1, cols=1, vertical_spacing=0.00)
fig.add_trace(
go.Scatter(
x=data.index,
y=data.col_name,
name="col_name",
line=dict(color="#90EE90"),
),
row=1,
col=1,
)
fig.show()
and I have imported and setup plotly like below
import plotly.io as pio
import plotly.offline as pyo
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# Notebook setup
pyo.init_notebook_mode()
pio.renderers.default = "iframe"
Without pio.renderers.default = "iframe" jupyter notebook does not even render the plot. By using iframe I can render the plot, but it starts saving every plot as HTML file with average of 3-4 MB in size on my local machine. How can I avoid that? Is there any better way to render plotly charts which will spare me all other things to deal with?
Thanks!
A:
Try adding these into the import section:
from plotly.offline import plot, iplot, init_notebook_mode
init_notebook_mode(connected=True)
pio.renderers
|
How to delete/not save files when Jupyter notebook in ran with plotly pio.renderers.default = "iframe"?
|
I am plotting a plot using plotly python (inside jupyter notebook) like below-
fig = make_subplots(rows=1, cols=1, vertical_spacing=0.00)
fig.add_trace(
go.Scatter(
x=data.index,
y=data.col_name,
name="col_name",
line=dict(color="#90EE90"),
),
row=1,
col=1,
)
fig.show()
and I have imported and setup plotly like below
import plotly.io as pio
import plotly.offline as pyo
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# Notebook setup
pyo.init_notebook_mode()
pio.renderers.default = "iframe"
Without pio.renderers.default = "iframe" jupyter notebook does not even render the plot. By using iframe I can render the plot, but it starts saving every plot as HTML file with average of 3-4 MB in size on my local machine. How can I avoid that? Is there any better way to render plotly charts which will spare me all other things to deal with?
Thanks!
|
[
"Try adding these into the import section:\nfrom plotly.offline import plot, iplot, init_notebook_mode\ninit_notebook_mode(connected=True)\npio.renderers\n\n"
] |
[
1
] |
[] |
[] |
[
"jupyter_notebook",
"plotly",
"plotly_python",
"python"
] |
stackoverflow_0074571546_jupyter_notebook_plotly_plotly_python_python.txt
|
Q:
multiply values from two different dataframes
I have two dataframes:
number 1
word
weight
book
0.2
water
0.5
number two
description
book
water
xyz
1
0
abc
0
1
I would like to simply multiply each word weight with the values in the second dataframe and paste them in the second dataframe - instead of 1/0
A:
If match columns names in df2 without description with column df1.word you can use:
df = df2.set_index('description').mul(df1.set_index('word')['weight']).reset_index()
print (df)
description book water
0 xyz 0.2 0.0
1 abc 0.0 0.5
Or if need multiple only matched columns use:
m = df2.columns.isin(df1['word'])
df2.loc[:, m] = df2.loc[:, m].mul(df1.set_index('word')['weight'])
print (df2)
description book water
0 xyz 0.2 0.0
1 abc 0.0 0.5
|
multiply values from two different dataframes
|
I have two dataframes:
number 1
word
weight
book
0.2
water
0.5
number two
description
book
water
xyz
1
0
abc
0
1
I would like to simply multiply each word weight with the values in the second dataframe and paste them in the second dataframe - instead of 1/0
|
[
"If match columns names in df2 without description with column df1.word you can use:\ndf = df2.set_index('description').mul(df1.set_index('word')['weight']).reset_index()\nprint (df)\n description book water\n0 xyz 0.2 0.0\n1 abc 0.0 0.5\n\nOr if need multiple only matched columns use:\nm = df2.columns.isin(df1['word'])\ndf2.loc[:, m] = df2.loc[:, m].mul(df1.set_index('word')['weight'])\nprint (df2)\n description book water\n0 xyz 0.2 0.0\n1 abc 0.0 0.5\n\n"
] |
[
1
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074571601_dataframe_pandas_python.txt
|
Q:
I would like to know how to not reinstall the app every time you start a new test
I'm performing E2E mobile tests with Appium and Pytest. I would like to know how to not reinstall the app every time you start a new test. I already tried using noReset and it didn't solve my problem. I've also tried using the scope='class' in the driver setup in the conftest, but if I put that in, the tests that run after the first test break, because they stay on the first test screen and don't go to the second screen.
what can I do?
A:
First of all you should make sure to reuse the driver in every test. The initialisation of the driver (which will happen in the first test) should take care of the app install. Take a look at noReset and fullReset, see here for the specifics, you might need to use both?
Then after every test, make sure to get to the preferred state for the next test. Perhaps you want to be logged out? Then make sure to end every test with a logout. Etc... I'm not clear to what you mean with first test screen and second screen, so feel free to elaborate with more specifics if you want a more specific answer.
|
I would like to know how to not reinstall the app every time you start a new test
|
I'm performing E2E mobile tests with Appium and Pytest. I would like to know how to not reinstall the app every time you start a new test. I already tried using noReset and it didn't solve my problem. I've also tried using the scope='class' in the driver setup in the conftest, but if I put that in, the tests that run after the first test break, because they stay on the first test screen and don't go to the second screen.
what can I do?
|
[
"First of all you should make sure to reuse the driver in every test. The initialisation of the driver (which will happen in the first test) should take care of the app install. Take a look at noReset and fullReset, see here for the specifics, you might need to use both?\nThen after every test, make sure to get to the preferred state for the next test. Perhaps you want to be logged out? Then make sure to end every test with a logout. Etc... I'm not clear to what you mean with first test screen and second screen, so feel free to elaborate with more specifics if you want a more specific answer.\n"
] |
[
0
] |
[] |
[] |
[
"appium",
"automated_tests",
"mobile",
"pytest",
"python"
] |
stackoverflow_0074546638_appium_automated_tests_mobile_pytest_python.txt
|
Q:
calculate diff between two values and then % difference associated to unique references month by month in pandas dataframe
I have a pandas dataframe;
ID
MONTH
TOTAL
0
REF1
1
500
1
REF1
2
501
2
REF1
3
620
3
REF2
8
5001
4
REF2
9
5101
5
REF2
10
5701
6
REF2
11
7501
7
REF2
7
6501
8
REF2
6
1501
I need to do a comparison between of difference between the ID's previous month's TOTAL.
At the moment I can calculate the difference between the row above but the comparison doesn't take into account the ID/MONTH. Would this need to be a where loop?
I have tried the below, but this returns NaN in all cells of the 'Variance' & 'Variance%' columns;
df_all.sort_values(['ID', 'MONTH'], inplace=True)
df_all['Variance'] = df_all['TOTAL'] - df_all.groupby(['ID', 'MONTH'])['TOTAL'].shift()
df_all['Variance%'] = df_all['TOTAL'] - df_all.groupby(['ID', 'MONTH'])['TOTAL'].pct_change()
The desired outcome is;
ID
MONTH
TOTAL
Variance
Variance %
0
REF1
1
500
0
0
1
REF1
2
501
1
0.2
A:
You can shift the Month by adding 1 (eventually use a more complex logic if you have real dates), then perform a self-merge and subtract:
df['diff'] = df['TOTAL'].sub(
df[['ID', 'MONTH']]
.merge(df.assign(MONTH=df['MONTH'].add(1)),
how='left')['TOTAL']
)
Output:
ID MONTH TOTAL diff
0 REF1 1 500 NaN
1 REF1 2 501 1.0
2 REF1 3 620 119.0
3 REF2 8 5001 -1500.0 # 5001 - 6501
4 REF2 9 5101 100.0
5 REF2 10 5701 600.0
6 REF2 11 7501 1800.0
7 REF2 7 6501 5000.0 # 6501 - 1501
8 REF2 6 1501 NaN
|
calculate diff between two values and then % difference associated to unique references month by month in pandas dataframe
|
I have a pandas dataframe;
ID
MONTH
TOTAL
0
REF1
1
500
1
REF1
2
501
2
REF1
3
620
3
REF2
8
5001
4
REF2
9
5101
5
REF2
10
5701
6
REF2
11
7501
7
REF2
7
6501
8
REF2
6
1501
I need to do a comparison between of difference between the ID's previous month's TOTAL.
At the moment I can calculate the difference between the row above but the comparison doesn't take into account the ID/MONTH. Would this need to be a where loop?
I have tried the below, but this returns NaN in all cells of the 'Variance' & 'Variance%' columns;
df_all.sort_values(['ID', 'MONTH'], inplace=True)
df_all['Variance'] = df_all['TOTAL'] - df_all.groupby(['ID', 'MONTH'])['TOTAL'].shift()
df_all['Variance%'] = df_all['TOTAL'] - df_all.groupby(['ID', 'MONTH'])['TOTAL'].pct_change()
The desired outcome is;
ID
MONTH
TOTAL
Variance
Variance %
0
REF1
1
500
0
0
1
REF1
2
501
1
0.2
|
[
"You can shift the Month by adding 1 (eventually use a more complex logic if you have real dates), then perform a self-merge and subtract:\ndf['diff'] = df['TOTAL'].sub(\n df[['ID', 'MONTH']]\n .merge(df.assign(MONTH=df['MONTH'].add(1)),\n how='left')['TOTAL']\n )\n\nOutput:\n ID MONTH TOTAL diff\n0 REF1 1 500 NaN\n1 REF1 2 501 1.0\n2 REF1 3 620 119.0\n3 REF2 8 5001 -1500.0 # 5001 - 6501\n4 REF2 9 5101 100.0\n5 REF2 10 5701 600.0\n6 REF2 11 7501 1800.0\n7 REF2 7 6501 5000.0 # 6501 - 1501\n8 REF2 6 1501 NaN\n\n"
] |
[
1
] |
[] |
[] |
[
"compare",
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074571682_compare_dataframe_pandas_python.txt
|
Q:
How do I return the value of a key that is nested in an anonymous JSON block with jsonpath?
I am trying to extract the value of a key that is nested in an anonymous JSON block. This is what the JSON block looks like after result:
"extras": [
{
"key": "alternative_name",
"value": "catr"
},
{
"key": "lineage",
"value": "This dataset was amalgamated, optimised and published by the Spatial hub. For more information visit www.spatialhub.scot."
},
{
"key": "ssdi_link",
"value": "https://www.spatialdata.gov.scot/geonetwork/srv/eng/catalog.search#/metadata/4826c148-c1eb-4eaa-abad-ca4b1ec65230"
},
{
"key": "update_frequency",
"value": "annually"
}
],
What I am trying to do is extract the value annually but I can't use index because some other datasets have more keys under the extras section. I am trying to write a jsonpath expression that extracts value where key is update_frequency
So far what I have tried is:
$.result.extras[*].value[?(key='update_frequency')]
And still no luck.
Any idea what could be wrong?
A:
This should work:
$.result.extras[?(@.key=="update_frequency")].value
|
How do I return the value of a key that is nested in an anonymous JSON block with jsonpath?
|
I am trying to extract the value of a key that is nested in an anonymous JSON block. This is what the JSON block looks like after result:
"extras": [
{
"key": "alternative_name",
"value": "catr"
},
{
"key": "lineage",
"value": "This dataset was amalgamated, optimised and published by the Spatial hub. For more information visit www.spatialhub.scot."
},
{
"key": "ssdi_link",
"value": "https://www.spatialdata.gov.scot/geonetwork/srv/eng/catalog.search#/metadata/4826c148-c1eb-4eaa-abad-ca4b1ec65230"
},
{
"key": "update_frequency",
"value": "annually"
}
],
What I am trying to do is extract the value annually but I can't use index because some other datasets have more keys under the extras section. I am trying to write a jsonpath expression that extracts value where key is update_frequency
So far what I have tried is:
$.result.extras[*].value[?(key='update_frequency')]
And still no luck.
Any idea what could be wrong?
|
[
"This should work:\n$.result.extras[?(@.key==\"update_frequency\")].value\n\n"
] |
[
1
] |
[] |
[] |
[
"jsonpath",
"python"
] |
stackoverflow_0074571085_jsonpath_python.txt
|
Q:
How to display the values above markers in plotly scatter graph object?
I can’t seem to find the argument to always display the scatter y values above the points in python plotly.
I tried to search for it and failed. I just want something like that hover number to always be on.
A:
Do you need something similar to this in the docs?
https://plotly.com/python/line-and-scatter/#connected-scatterplots
import plotly.express as px
df = px.data.gapminder().query("country in ['Canada', 'Botswana']")
fig = px.scatter(
df, x="lifeExp", y="gdpPercap", color="country", text="year"
).update_traces(textposition="top center")
fig.show()
|
How to display the values above markers in plotly scatter graph object?
|
I can’t seem to find the argument to always display the scatter y values above the points in python plotly.
I tried to search for it and failed. I just want something like that hover number to always be on.
|
[
"Do you need something similar to this in the docs?\nhttps://plotly.com/python/line-and-scatter/#connected-scatterplots\nimport plotly.express as px\n\ndf = px.data.gapminder().query(\"country in ['Canada', 'Botswana']\")\n\nfig = px.scatter(\n df, x=\"lifeExp\", y=\"gdpPercap\", color=\"country\", text=\"year\"\n ).update_traces(textposition=\"top center\")\nfig.show()\n\n\n"
] |
[
0
] |
[] |
[] |
[
"plotly",
"plotly.graph_objects",
"plotly_python",
"python",
"scatter_plot"
] |
stackoverflow_0074567368_plotly_plotly.graph_objects_plotly_python_python_scatter_plot.txt
|
Q:
Why does this dictionary go out of range?
So in my school, we are working on an encoding project making a compression algorithm. I'm working on one that uses a mixture of dictionaries and RLE. I'm currently testing out making an embedded dictionary and placing values into it using pandas. Issue is, something goes out of range somewhere and expands the pd DataFrame, causing the image to be of the wrong shape.
I'm working in Google colab, hence the cv2_imshow import
import pandas as pd
import cv2
from google.colab.patches import cv2_imshow
'''
so the idea is you have a dictionary, with 255 keys for all the different shades of gray and the values for each key has coordinates where each colours belongs per frame
'''
frame_count = 512 # for example, creating a 512x512 dictionary
d = {}
for i in range(512):
d[i]=0
allframesdict = {}
for frame in range(frame_count):
allframesdict[frame+1] = d
df = pd.DataFrame(allframesdict)
# printing df.shape print (512,512)
for x in range(512): # ??
df.at[x,0]=255 # trying to create a white line as a test
# strangely, assigning x to a variable and printing the variable prints 511
array = df.to_numpy()
# so i decided to try a few things to see what was going wrong
print(type(array)) # prints <class 'numpy.ndarray'>
print(array.shape) # prints (512, 513)
print(array)
'''
prints:
[[ 0. 0. 0. ... 0. 0. 255.]
[ 0. 0. 0. ... 0. 0. 255.]
[ 0. 0. 0. ... 0. 0. 255.]
...
[ 0. 0. 0. ... 0. 0. 255.]
[ 0. 0. 0. ... 0. 0. 255.]
[ 0. 0. 0. ... 0. 0. nan]]
'''
cv2_imshow(array)
cv2_imshow(array) shows (https://i.stack.imgur.com/gzLWb.png)
I don't have a clue what's going wrong. Neither does my teacher.
Tried changing (line commented # ??) for x in range(512) to for x in range(511). Same issue, not much changes other than the x variable ending up as 510.
Tried changing df.at[x,0] to df.at[x+1,0]. Just causes the dictionary to go even further out of range, changing print(array.shape) from (512,513) to (513,513)
Edit:: Even better question that is spur of the moment and I haven't put any thought into, why does the line show on the right side of the array/dictionary/image?
A:
After this line
df = pd.DataFrame(allframesdict)
df will contains 1-based columns
>>> df.columns
Int64Index([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
...
503, 504, 505, 506, 507, 508, 509, 510, 511, 512],
dtype='int64', length=512)
And code
for x in range(512): # ??
df.at[x,0]=255 # trying to create a white line as a test
will add one more column 0 at after 512 column.
>>> for x in range(512): # ??
... df.at[x,0]=255 # trying to create a white line as a test
...
>>> df.columns
Int64Index([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
...
504, 505, 506, 507, 508, 509, 510, 511, 512, 0],
dtype='int64', length=513)
Try
for x in range(512): # ??
df.at[x,1]=255 # trying to create a white line as a test
|
Why does this dictionary go out of range?
|
So in my school, we are working on an encoding project making a compression algorithm. I'm working on one that uses a mixture of dictionaries and RLE. I'm currently testing out making an embedded dictionary and placing values into it using pandas. Issue is, something goes out of range somewhere and expands the pd DataFrame, causing the image to be of the wrong shape.
I'm working in Google colab, hence the cv2_imshow import
import pandas as pd
import cv2
from google.colab.patches import cv2_imshow
'''
so the idea is you have a dictionary, with 255 keys for all the different shades of gray and the values for each key has coordinates where each colours belongs per frame
'''
frame_count = 512 # for example, creating a 512x512 dictionary
d = {}
for i in range(512):
d[i]=0
allframesdict = {}
for frame in range(frame_count):
allframesdict[frame+1] = d
df = pd.DataFrame(allframesdict)
# printing df.shape print (512,512)
for x in range(512): # ??
df.at[x,0]=255 # trying to create a white line as a test
# strangely, assigning x to a variable and printing the variable prints 511
array = df.to_numpy()
# so i decided to try a few things to see what was going wrong
print(type(array)) # prints <class 'numpy.ndarray'>
print(array.shape) # prints (512, 513)
print(array)
'''
prints:
[[ 0. 0. 0. ... 0. 0. 255.]
[ 0. 0. 0. ... 0. 0. 255.]
[ 0. 0. 0. ... 0. 0. 255.]
...
[ 0. 0. 0. ... 0. 0. 255.]
[ 0. 0. 0. ... 0. 0. 255.]
[ 0. 0. 0. ... 0. 0. nan]]
'''
cv2_imshow(array)
cv2_imshow(array) shows (https://i.stack.imgur.com/gzLWb.png)
I don't have a clue what's going wrong. Neither does my teacher.
Tried changing (line commented # ??) for x in range(512) to for x in range(511). Same issue, not much changes other than the x variable ending up as 510.
Tried changing df.at[x,0] to df.at[x+1,0]. Just causes the dictionary to go even further out of range, changing print(array.shape) from (512,513) to (513,513)
Edit:: Even better question that is spur of the moment and I haven't put any thought into, why does the line show on the right side of the array/dictionary/image?
|
[
"After this line\ndf = pd.DataFrame(allframesdict)\n\ndf will contains 1-based columns\n>>> df.columns\nInt64Index([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,\n ...\n 503, 504, 505, 506, 507, 508, 509, 510, 511, 512],\n dtype='int64', length=512)\n\nAnd code\nfor x in range(512): # ??\n df.at[x,0]=255 # trying to create a white line as a test\n\nwill add one more column 0 at after 512 column.\n>>> for x in range(512): # ??\n... df.at[x,0]=255 # trying to create a white line as a test\n...\n>>> df.columns\nInt64Index([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,\n ...\n 504, 505, 506, 507, 508, 509, 510, 511, 512, 0],\n dtype='int64', length=513)\n\nTry\nfor x in range(512): # ??\n df.at[x,1]=255 # trying to create a white line as a test\n\n"
] |
[
0
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074571449_pandas_python.txt
|
Q:
Web Scrapping via python show AttributeError: 'NoneType' object has no attribute 'full_text'
Scrap the data from the website by using python.
from requests_html import HTMLSession
import http.client
http.client._MAXHEADERS = 1000
url='https://agedcarestore.com.au/product-category/physio-products/arthritis/'
s=HTMLSession()
r=s.get(url)
print(r.html.find('#header'))
items=r.html.find('div.product-small.box')
print(items)
def get_links(url):
r=s.get(url)
items=r.html.find('div.product-small.box')
links=[]
for item in items:
links.append(item.find('a',first=True).attrs['href'])
return links
print(get_links(url))
def get_product(link):
r=s.get(link)
title=r.html.find('h1',first=True).full_text
price=r.html.find('span.woocommerce-Price-amount.amount bdi')[1].full_text
sku=r.html.find('nav.ruk_rating_snippet data-sku',first=True).full_text
tag = r.html.find('a[rel=tag]', first=True).full_text
sku = r.html.find('span.sku', first=True).full_text
product = {
'title': title.strip(),
'price': price.strip(),
'tag': tag.strip(),
'sku': sku.strip()
}
print(product)
return product
results = []
links = get_links(url)
for link in links:
results.append(get_product(link))
time.sleep(1)
with open('version1.csv', 'w', encoding='utf8', newline='') as f:
fc = csv.DictWriter(f, fieldnames=results[0].keys(),)
fc.writeheader()
I want extract the data from the website which built on woocommerce, but my python code showed the error: AttributeError: 'NoneType' object has no attribute 'full_text'
how to solve it?
A:
You shouldn't try to get .full_text without checking if find returned something. You should remove the .full_text part from the lines and just build product with the checks, like
product = {
'title': title.full_text.strip() if title else 'DEFAULT_TITLE',
'price': price[0].full_text.strip() if price else 'DEFAULT_PRICE', # remove [0] from find as well
'tag': tag.full_text.strip() if tag else 'DEFAULT_TAG',
'sku': sku.full_text.strip() if sku else 'DEFAULT_SKU',
}
[Btw, why are there 2 sku lines? The first line gets over-written by the second, so it's not really doing anything...]
[Also, in get_links, you should maybe change the selector to 'div.product-small.box:has(a[href])' and item.find('a[href]',first=True) to be safer and avoid None-type errors there as well.]
|
Web Scrapping via python show AttributeError: 'NoneType' object has no attribute 'full_text'
|
Scrap the data from the website by using python.
from requests_html import HTMLSession
import http.client
http.client._MAXHEADERS = 1000
url='https://agedcarestore.com.au/product-category/physio-products/arthritis/'
s=HTMLSession()
r=s.get(url)
print(r.html.find('#header'))
items=r.html.find('div.product-small.box')
print(items)
def get_links(url):
r=s.get(url)
items=r.html.find('div.product-small.box')
links=[]
for item in items:
links.append(item.find('a',first=True).attrs['href'])
return links
print(get_links(url))
def get_product(link):
r=s.get(link)
title=r.html.find('h1',first=True).full_text
price=r.html.find('span.woocommerce-Price-amount.amount bdi')[1].full_text
sku=r.html.find('nav.ruk_rating_snippet data-sku',first=True).full_text
tag = r.html.find('a[rel=tag]', first=True).full_text
sku = r.html.find('span.sku', first=True).full_text
product = {
'title': title.strip(),
'price': price.strip(),
'tag': tag.strip(),
'sku': sku.strip()
}
print(product)
return product
results = []
links = get_links(url)
for link in links:
results.append(get_product(link))
time.sleep(1)
with open('version1.csv', 'w', encoding='utf8', newline='') as f:
fc = csv.DictWriter(f, fieldnames=results[0].keys(),)
fc.writeheader()
I want extract the data from the website which built on woocommerce, but my python code showed the error: AttributeError: 'NoneType' object has no attribute 'full_text'
how to solve it?
|
[
"You shouldn't try to get .full_text without checking if find returned something. You should remove the .full_text part from the lines and just build product with the checks, like\n product = {\n 'title': title.full_text.strip() if title else 'DEFAULT_TITLE',\n 'price': price[0].full_text.strip() if price else 'DEFAULT_PRICE', # remove [0] from find as well\n 'tag': tag.full_text.strip() if tag else 'DEFAULT_TAG',\n 'sku': sku.full_text.strip() if sku else 'DEFAULT_SKU',\n }\n\n[Btw, why are there 2 sku lines? The first line gets over-written by the second, so it's not really doing anything...]\n[Also, in get_links, you should maybe change the selector to 'div.product-small.box:has(a[href])' and item.find('a[href]',first=True) to be safer and avoid None-type errors there as well.]\n"
] |
[
0
] |
[] |
[] |
[
"image",
"python",
"web_scraping",
"woocommerce"
] |
stackoverflow_0074525951_image_python_web_scraping_woocommerce.txt
|
Q:
Screenshots of iframes taking by python selenium are cropped (both chrome and firefox webdrivers)
I am trying to screenshot an image located inside an iframe in an ads creative in headless mode.
Indeed, I will have to screenshot many of such iframes and the final script will run on a remote server.
No matter what I have tried, screenshots always seem to be cropped when I use the headless mode of selenium.
I have seen that a few posts exist on this subject, but none of them have solved my issue.
Here is a list of things I already tried:
Using either Firefox or Chrome webdrivers didn't help.
Using different combinations of waits conditions didn't help either.
Below, there is a MWE of the code I am trying to run:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.options import Options as OptionsFirefox
from selenium.webdriver.chrome.options import Options as OptionsChrome
from PIL import Image
from io import BytesIO
test_url = "https://cdn-creatives.adikteev.com/Creatives/demoLink/MLEngine/index.html?MRAID_320X480_AWEM_CradleEmpires_Aug20/creative-e03f09e5.min.js"
id_iframe = "mainIframe"
# Setting up the driver.
# options = OptionsFirefox()
# options.headless = True
# driver = webdriver.Firefox(options=options)
options = OptionsChrome()
options.headless = True
driver = webdriver.Chrome(options=options)
# Getting the url.
driver.get(test_url)
WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.ID, id_iframe)))
# Getiing the iframe with its informations:
elem = driver.find_element(By.ID, id_iframe)
#
location = elem.location
size = elem.size
left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']
ic(elem.location)
ic(elem.size)
# Waits (might help ?).
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it(id_iframe))
# Saving screenshots:
# Complete screenshot.
img_png = driver.get_screenshot_as_png()
driver.save_screenshot("full_screen_headless_on.png")
img_crop = Image.open(BytesIO(img_png))
img_crop = img_crop.crop((left, top, right, bottom)) # defines crop points
# Screenshot cropped to the Iframe.
img_crop.save( "iframe_screen_headless_on.png" ) # saves new cropped image
driver.quit()
If someone has a solution, that will be greatly appreciated :-) !
A:
I had the same issue with Selenuium.
In my case additional waiting after resolving the URL helped, for instance:
...
driver.get(url)
time.sleep(10)
WebDriverWait(driver, 20).until(
EC.frame_to_be_available_and_switch_to_it((By.ID, id_iframe))
)
...
I can't actually explain why it works like that, I didn't deep into the docs, but it helped.
|
Screenshots of iframes taking by python selenium are cropped (both chrome and firefox webdrivers)
|
I am trying to screenshot an image located inside an iframe in an ads creative in headless mode.
Indeed, I will have to screenshot many of such iframes and the final script will run on a remote server.
No matter what I have tried, screenshots always seem to be cropped when I use the headless mode of selenium.
I have seen that a few posts exist on this subject, but none of them have solved my issue.
Here is a list of things I already tried:
Using either Firefox or Chrome webdrivers didn't help.
Using different combinations of waits conditions didn't help either.
Below, there is a MWE of the code I am trying to run:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.options import Options as OptionsFirefox
from selenium.webdriver.chrome.options import Options as OptionsChrome
from PIL import Image
from io import BytesIO
test_url = "https://cdn-creatives.adikteev.com/Creatives/demoLink/MLEngine/index.html?MRAID_320X480_AWEM_CradleEmpires_Aug20/creative-e03f09e5.min.js"
id_iframe = "mainIframe"
# Setting up the driver.
# options = OptionsFirefox()
# options.headless = True
# driver = webdriver.Firefox(options=options)
options = OptionsChrome()
options.headless = True
driver = webdriver.Chrome(options=options)
# Getting the url.
driver.get(test_url)
WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.ID, id_iframe)))
# Getiing the iframe with its informations:
elem = driver.find_element(By.ID, id_iframe)
#
location = elem.location
size = elem.size
left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']
ic(elem.location)
ic(elem.size)
# Waits (might help ?).
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it(id_iframe))
# Saving screenshots:
# Complete screenshot.
img_png = driver.get_screenshot_as_png()
driver.save_screenshot("full_screen_headless_on.png")
img_crop = Image.open(BytesIO(img_png))
img_crop = img_crop.crop((left, top, right, bottom)) # defines crop points
# Screenshot cropped to the Iframe.
img_crop.save( "iframe_screen_headless_on.png" ) # saves new cropped image
driver.quit()
If someone has a solution, that will be greatly appreciated :-) !
|
[
"I had the same issue with Selenuium.\nIn my case additional waiting after resolving the URL helped, for instance:\n...\n\ndriver.get(url)\ntime.sleep(10)\n\nWebDriverWait(driver, 20).until(\n EC.frame_to_be_available_and_switch_to_it((By.ID, id_iframe))\n)\n\n...\n\nI can't actually explain why it works like that, I didn't deep into the docs, but it helped.\n"
] |
[
0
] |
[] |
[] |
[
"iframe",
"python",
"python_imaging_library",
"selenium",
"selenium_webdriver"
] |
stackoverflow_0074292472_iframe_python_python_imaging_library_selenium_selenium_webdriver.txt
|
Q:
How to create and deploy AWS lambda from boto3 for node.js app in python
I am uploading NodeJS file to s3 bucket now I want to run the node.js files uploaded to s3 bucket
Here is my current code:
s3=boto3.client('s3', zone,aws_access_key_id=aws_access_key,aws_secret_access_key=aws_secret_key)
with open(generatedfolder1+"package.json", "rb") as f:
s3.upload_fileobj(f, bucket, gendirname+'/package.json')
with open(generatedfolder1+"index.js", "rb") as f:
s3.upload_fileobj(f, bucket, gendirname+'/index.js')
A:
It sounds like your goal is to deploy a Lambda programatically. Use the boto3 Lambda client's create_function API to do this. The Lambda service indeed uses S3 to store the function artefacts, but you wouldn't typically interact with S3 directly. The docs have a step-by-step create-function example using the CLI. The CLI uses boto3 under the hood.
FYI, boto3 is simply the original project name of the AWS SDK for Python. There are other AWS language SDKs, including the AWS SDK for JavaScript. In the JS SDK, you'd create your Lambda with the CreateFunctionCommand class. All the SDKs do the same things, but only the Python SDK has a great nickname!
|
How to create and deploy AWS lambda from boto3 for node.js app in python
|
I am uploading NodeJS file to s3 bucket now I want to run the node.js files uploaded to s3 bucket
Here is my current code:
s3=boto3.client('s3', zone,aws_access_key_id=aws_access_key,aws_secret_access_key=aws_secret_key)
with open(generatedfolder1+"package.json", "rb") as f:
s3.upload_fileobj(f, bucket, gendirname+'/package.json')
with open(generatedfolder1+"index.js", "rb") as f:
s3.upload_fileobj(f, bucket, gendirname+'/index.js')
|
[
"It sounds like your goal is to deploy a Lambda programatically. Use the boto3 Lambda client's create_function API to do this. The Lambda service indeed uses S3 to store the function artefacts, but you wouldn't typically interact with S3 directly. The docs have a step-by-step create-function example using the CLI. The CLI uses boto3 under the hood.\nFYI, boto3 is simply the original project name of the AWS SDK for Python. There are other AWS language SDKs, including the AWS SDK for JavaScript. In the JS SDK, you'd create your Lambda with the CreateFunctionCommand class. All the SDKs do the same things, but only the Python SDK has a great nickname!\n"
] |
[
1
] |
[] |
[] |
[
"amazon_s3",
"aws_lambda",
"boto3",
"python"
] |
stackoverflow_0074560718_amazon_s3_aws_lambda_boto3_python.txt
|
Q:
Problem in skimage rgb2hed when applied to part of a matrix
I am trying to convert an image from RBG to HED using the rgb2hed function from skimage. My image is very big and if I just try and put the whole thing into the rgb2hed function then I run out of memory. To get around this I have written some code to split the image into sections and apply rgb2hed to each section, but I get very different results when doing so. Getting a matrix of almost all 0's when splitting up the function. Minimal reprex given below.
import numpy as np
from skimage.color import rgb2hed
np.random.seed(42)
sample = np.random.randint(0, 255, size=(100, 100, 3))
n_splits = 10
x_split_inds = np.linspace(0, sample.shape[0], n_splits + 1, dtype=int)
for x in range(len(x_split_inds) - 1):
x_start = x_split_inds[x]
x_end = x_split_inds[x + 1]
sample[x_start:x_end, :, :] = rgb2hed(sample[x_start:x_end, :, :])
print(rgb2hed(sample))
print()
print(sample)
This is the first matrix I get
[[[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
...
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]]
[[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
...
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]]
[[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
...
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]]
...
[[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
...
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]]
[[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
...
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]]
[[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
...
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]]]
and this is the second
[[[1 0 0]
[1 0 0]
[1 0 0]
...
[1 0 0]
[1 0 0]
[1 0 0]]
[[1 0 0]
[1 0 0]
[1 0 0]
...
[1 0 0]
[1 0 0]
[1 0 0]]
[[1 0 0]
[1 0 0]
[1 0 0]
...
[1 0 0]
[1 0 0]
[1 0 0]]
...
[[1 0 0]
[1 0 0]
[1 0 0]
...
[1 0 0]
[1 0 0]
[1 0 0]]
[[1 0 0]
[1 0 0]
[1 0 0]
...
[1 0 0]
[1 0 0]
[1 0 0]]
[[1 0 0]
[1 0 0]
[1 0 0]
...
[1 0 0]
[1 0 0]
[1 0 0]]]
A:
The issue is related to dtype mismatching:
The dtype of sample = np.random.randint(...) is 'int32'
The dtype of rgb2hed(...) is float64
When updating a slice of NumPy array, the data is converted to the type of that updated NumPy array.
The expression sample[x_start:x_end, :, :] = rgb2hed(...) automatically converts from float64 to 'int32' type.
The cast from float64 to 'int32' converts 1.21016731 to 1 and 0.88195046 to 0...
We may solve it by avoiding "in place" processing:
output_sample = np.zeros((100, 100, 3), np.float64) # Allocate output_sample
...
output_sample[x_start:x_end, :, :] = rgb2hed(sample[x_start:x_end, :, :])
Does it require too much RAM?
We may also solve it by converting type of sample to np.float64:
import numpy as np
from skimage.color import rgb2hed
np.random.seed(42)
sample = np.random.randint(0, 255, size=(4, 4, 3)).astype(np.uint8)
sample_copy = sample.copy()
sample = sample.astype(np.float64) / 255.0 # Divide by 255, because rgb2hed expects range [0, 1] for float64 type
n_splits = 4 #10
x_split_inds = np.linspace(0, sample.shape[0], n_splits + 1, dtype=int)
for x in range(len(x_split_inds) - 1):
x_start = x_split_inds[x]
x_end = x_split_inds[x + 1]
sample[x_start:x_end, :, :] = rgb2hed(sample[x_start:x_end, :, :])
print(rgb2hed(sample_copy))
print()
print(sample)
Output of print(rgb2hed(sample_copy)):
[[[-0.46103368 0.07251299 -0.31709355]
[-0.34690713 0.05235859 -0.33691324]
[-0.57147719 0.26278779 -0.31203784]
[-0.43647159 0.10270586 -0.43322983]]
...
Output of print(sample)):
[[[-0.46103368 0.07251299 -0.31709355]
[-0.34690713 0.05235859 -0.33691324]
[-0.57147719 0.26278779 -0.31203784]
[-0.43647159 0.10270586 -0.43322983]]
Saving memory:
Each float64 elements is 8 bytes in RAM.
For saving memory space, we may use float32 type that is only 4 bytes in RAM.
Example: sample = np.random.randint(0, 255, size=(4, 4, 3)).astype(np.float32) / 255.0...
For saving more RAM in expense of accuracy, we may use int16 type with scaling and rounding.
Example:
import numpy as np
from skimage.color import rgb2hed
np.random.seed(42)
sample = np.random.randint(0, 255, size=(4, 4, 3)).astype(np.uint8)
sample_copy = sample.copy()
sample = sample.astype(np.int16) # Convert to int16 (used for "in place" processing).
n_splits = 4 #10
x_split_inds = np.linspace(0, sample.shape[0], n_splits + 1, dtype=int)
for x in range(len(x_split_inds) - 1):
x_start = x_split_inds[x]
x_end = x_split_inds[x + 1]
# Scale by 10000 and convert to int16 with rounding and clipping:
sample[x_start:x_end, :, :] = np.round(rgb2hed(sample[x_start:x_end, :, :].astype(np.uint8))*10000).clip(-32768, 32767).astype(np.int16)
print(rgb2hed(sample_copy))
print()
print(sample*1e-4) # Divide by 10000
Output of print(sample*1e-4):
[[[-0.461 0.0725 -0.3171]
[-0.3469 0.0524 -0.3369]
[-0.5715 0.2628 -0.312 ]
[-0.4365 0.1027 -0.4332]]
As you can see, the accuracy is reduced to 4 decimal digits.
|
Problem in skimage rgb2hed when applied to part of a matrix
|
I am trying to convert an image from RBG to HED using the rgb2hed function from skimage. My image is very big and if I just try and put the whole thing into the rgb2hed function then I run out of memory. To get around this I have written some code to split the image into sections and apply rgb2hed to each section, but I get very different results when doing so. Getting a matrix of almost all 0's when splitting up the function. Minimal reprex given below.
import numpy as np
from skimage.color import rgb2hed
np.random.seed(42)
sample = np.random.randint(0, 255, size=(100, 100, 3))
n_splits = 10
x_split_inds = np.linspace(0, sample.shape[0], n_splits + 1, dtype=int)
for x in range(len(x_split_inds) - 1):
x_start = x_split_inds[x]
x_end = x_split_inds[x + 1]
sample[x_start:x_end, :, :] = rgb2hed(sample[x_start:x_end, :, :])
print(rgb2hed(sample))
print()
print(sample)
This is the first matrix I get
[[[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
...
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]]
[[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
...
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]]
[[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
...
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]]
...
[[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
...
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]]
[[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
...
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]]
[[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
...
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]
[1.21016731 0. 0.88195046]]]
and this is the second
[[[1 0 0]
[1 0 0]
[1 0 0]
...
[1 0 0]
[1 0 0]
[1 0 0]]
[[1 0 0]
[1 0 0]
[1 0 0]
...
[1 0 0]
[1 0 0]
[1 0 0]]
[[1 0 0]
[1 0 0]
[1 0 0]
...
[1 0 0]
[1 0 0]
[1 0 0]]
...
[[1 0 0]
[1 0 0]
[1 0 0]
...
[1 0 0]
[1 0 0]
[1 0 0]]
[[1 0 0]
[1 0 0]
[1 0 0]
...
[1 0 0]
[1 0 0]
[1 0 0]]
[[1 0 0]
[1 0 0]
[1 0 0]
...
[1 0 0]
[1 0 0]
[1 0 0]]]
|
[
"The issue is related to dtype mismatching:\n\nThe dtype of sample = np.random.randint(...) is 'int32'\nThe dtype of rgb2hed(...) is float64\n\nWhen updating a slice of NumPy array, the data is converted to the type of that updated NumPy array.\nThe expression sample[x_start:x_end, :, :] = rgb2hed(...) automatically converts from float64 to 'int32' type.\nThe cast from float64 to 'int32' converts 1.21016731 to 1 and 0.88195046 to 0...\n\nWe may solve it by avoiding \"in place\" processing:\noutput_sample = np.zeros((100, 100, 3), np.float64) # Allocate output_sample\n...\noutput_sample[x_start:x_end, :, :] = rgb2hed(sample[x_start:x_end, :, :])\n\nDoes it require too much RAM?\n\nWe may also solve it by converting type of sample to np.float64:\nimport numpy as np\nfrom skimage.color import rgb2hed\n\nnp.random.seed(42)\nsample = np.random.randint(0, 255, size=(4, 4, 3)).astype(np.uint8)\nsample_copy = sample.copy()\nsample = sample.astype(np.float64) / 255.0 # Divide by 255, because rgb2hed expects range [0, 1] for float64 type\n\nn_splits = 4 #10\nx_split_inds = np.linspace(0, sample.shape[0], n_splits + 1, dtype=int)\n\nfor x in range(len(x_split_inds) - 1):\n x_start = x_split_inds[x]\n x_end = x_split_inds[x + 1]\n sample[x_start:x_end, :, :] = rgb2hed(sample[x_start:x_end, :, :])\n\nprint(rgb2hed(sample_copy))\n\nprint()\n\nprint(sample)\n\n\nOutput of print(rgb2hed(sample_copy)):\n[[[-0.46103368 0.07251299 -0.31709355]\n [-0.34690713 0.05235859 -0.33691324]\n [-0.57147719 0.26278779 -0.31203784]\n [-0.43647159 0.10270586 -0.43322983]]\n\n...\nOutput of print(sample)):\n[[[-0.46103368 0.07251299 -0.31709355]\n [-0.34690713 0.05235859 -0.33691324]\n [-0.57147719 0.26278779 -0.31203784]\n [-0.43647159 0.10270586 -0.43322983]]\n\n\nSaving memory:\nEach float64 elements is 8 bytes in RAM.\nFor saving memory space, we may use float32 type that is only 4 bytes in RAM.\nExample: sample = np.random.randint(0, 255, size=(4, 4, 3)).astype(np.float32) / 255.0...\nFor saving more RAM in expense of accuracy, we may use int16 type with scaling and rounding.\nExample:\nimport numpy as np\nfrom skimage.color import rgb2hed\n \nnp.random.seed(42)\nsample = np.random.randint(0, 255, size=(4, 4, 3)).astype(np.uint8)\nsample_copy = sample.copy()\nsample = sample.astype(np.int16) # Convert to int16 (used for \"in place\" processing).\n \nn_splits = 4 #10\nx_split_inds = np.linspace(0, sample.shape[0], n_splits + 1, dtype=int)\n \nfor x in range(len(x_split_inds) - 1):\n x_start = x_split_inds[x]\n x_end = x_split_inds[x + 1]\n \n # Scale by 10000 and convert to int16 with rounding and clipping:\n sample[x_start:x_end, :, :] = np.round(rgb2hed(sample[x_start:x_end, :, :].astype(np.uint8))*10000).clip(-32768, 32767).astype(np.int16)\n \nprint(rgb2hed(sample_copy))\n \nprint()\n \nprint(sample*1e-4) # Divide by 10000\n\n\nOutput of print(sample*1e-4):\n[[[-0.461 0.0725 -0.3171]\n [-0.3469 0.0524 -0.3369]\n [-0.5715 0.2628 -0.312 ]\n [-0.4365 0.1027 -0.4332]]\n\nAs you can see, the accuracy is reduced to 4 decimal digits.\n"
] |
[
0
] |
[] |
[] |
[
"image_processing",
"python",
"scikit_image"
] |
stackoverflow_0074567827_image_processing_python_scikit_image.txt
|
Q:
Allign left and right in python?
I've seen a question on justifying a 'print' right, but could I have text left and right on the same line, for a --help? It'd look like this in the terminal:
| |
|Left Right|
| |
A:
I think you can use sys.stdout for this:
import sys
def stdout(message):
sys.stdout.write(message)
sys.stdout.write('\b' * len(message)) # \b: non-deleting backspace
def demo():
stdout('Right'.rjust(50))
stdout('Left')
sys.stdout.flush()
print()
demo()
You can replace 50 with the exact console width, which you can get from https://stackoverflow.com/a/943921/711085
A:
Here is a pretty simple method:
>>> left, right = 'Left', 'Right'
>>> print '|{}{}{}|'.format(left, ' '*(50-len(left+right)), right)
|Left Right|
As a function:
def lr_justify(left, right, width):
return '{}{}{}'.format(left, ' '*(width-len(left+right)), right)
>>> lr_justify('Left', '', 50)
'Left '
>>> lr_justify('', 'Right', 50)
' Right'
>>> lr_justify('Left', 'Right', 50)
'Left Right'
>>> lr_justify('', '', 50)
' '
A:
I know this is an old thread but I'd like to propose a more elegant solution that "fails gracefully" when the combined text's length exceeds the desired length.
def align_left_right(left: str, right: str, total_len: int = 80) -> str:
left_size = max(0, total_len - len(right) - 1) # -1 to account for the space
return format(left, f"<{left_size}") + " " + right
def main():
print("1.", align_left_right("|left", "right|"))
print("2.", align_left_right("|", "right|"))
print("3.", align_left_right("|left", "|"))
print("4.", align_left_right("|left", "right|", total_len=20))
print("5.", align_left_right("|left", "a longer text that doesn't fit|", total_len=20))
if __name__ == "__main__":
main()
output :
1. |left right|
2. | right|
3. |left |
4. |left right|
5. |left a longer text that doesn't fit|
You could make a more full-fledged version using textwrap.shorten to keep the total size constant even when one or both strings are too long.
|
Allign left and right in python?
|
I've seen a question on justifying a 'print' right, but could I have text left and right on the same line, for a --help? It'd look like this in the terminal:
| |
|Left Right|
| |
|
[
"I think you can use sys.stdout for this:\nimport sys\n\ndef stdout(message):\n sys.stdout.write(message)\n sys.stdout.write('\\b' * len(message)) # \\b: non-deleting backspace\n\ndef demo():\n stdout('Right'.rjust(50))\n stdout('Left')\n sys.stdout.flush()\n print()\n\ndemo()\n\nYou can replace 50 with the exact console width, which you can get from https://stackoverflow.com/a/943921/711085\n",
"Here is a pretty simple method:\n>>> left, right = 'Left', 'Right'\n>>> print '|{}{}{}|'.format(left, ' '*(50-len(left+right)), right)\n|Left Right|\n\nAs a function:\ndef lr_justify(left, right, width):\n return '{}{}{}'.format(left, ' '*(width-len(left+right)), right)\n\n>>> lr_justify('Left', '', 50)\n'Left '\n>>> lr_justify('', 'Right', 50)\n' Right'\n>>> lr_justify('Left', 'Right', 50)\n'Left Right'\n>>> lr_justify('', '', 50)\n' '\n\n",
"I know this is an old thread but I'd like to propose a more elegant solution that \"fails gracefully\" when the combined text's length exceeds the desired length.\ndef align_left_right(left: str, right: str, total_len: int = 80) -> str:\n left_size = max(0, total_len - len(right) - 1) # -1 to account for the space\n return format(left, f\"<{left_size}\") + \" \" + right\n\n\ndef main():\n print(\"1.\", align_left_right(\"|left\", \"right|\"))\n print(\"2.\", align_left_right(\"|\", \"right|\"))\n print(\"3.\", align_left_right(\"|left\", \"|\"))\n print(\"4.\", align_left_right(\"|left\", \"right|\", total_len=20))\n print(\"5.\", align_left_right(\"|left\", \"a longer text that doesn't fit|\", total_len=20))\n\n\nif __name__ == \"__main__\":\n main()\n\noutput :\n1. |left right|\n2. | right|\n3. |left |\n4. |left right|\n5. |left a longer text that doesn't fit|\n\nYou could make a more full-fledged version using textwrap.shorten to keep the total size constant even when one or both strings are too long.\n"
] |
[
4,
3,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0009640109_python.txt
|
Q:
400 Bad request with json object of curl POST command while flask is running
I just made flask API. OS is Win10. python version is 3.9.13. While the flask is running, I sent the following command.
curl -X POST http://127.0.0.1:5000/detect -H "Content-Type: application/json" -d '{"filename": "xxx.jpg"}'
However, I received 400 BAD Request.
<!doctype html>
<html lang=en>
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Failed to decode JSON: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)</p>
The codes of python have not received the request.
I googled a lot. Also, I checked the curl commands.
There is api directly.
---name of python= ___init___.py
from api import flask_test
from flask import Blueprint, jsonify, request
api = Blueprint("api", __name__)
@api.get("/")
def index():
return jsonify({"column": "value"}), 201
@api.post("/detect")
def detection():
return flask_test.detection(request)
The next file is follows;
---name of python flask_test.py
def load_image(request):
print('----')
filename = request.json["filename"]
print(filename)
dir_image = str(basedir / "data" / "original" / filename)
image = Image.open(dir_image).convert('RGB')
return image, filename
def detection(request):
print("test")
load_image(request)
Running flask codes are as follows;
----app.py
import os
from flask import Flask
from api import api
class Config:
TESTING = False
DEBUG = False
LABELS = [
"people",
"Population"
]
class LocalConfig(Config):
TESTING = True
DEBUG = True
config = {
"base": Config,
"local": LocalConfig,
}
config_name = os.environ.get("CONFIG", "local")
app = Flask(__name__)
app.config.from_object(config[config_name])
app.register_blueprint(api)
At api directory, you need the following commands(Win10)
$FLASK_APP="app.py"
$FLASK_ENV="development"
flask run
You will see json file at pot 5000.
{
"column": "value"
}
You see the following terminal screen;
enter image description here
Yuu see the following console screen;
enter image description here
You see "test", "----". But, you can't see the result of print(filename)
So that, request.json["filename"]
doesn't work well.
A:
you are returning a non-json response.
try this:-
@api.post("/detect")
def detection():
return jsonify({"response":flask_test.detection(request)})
|
400 Bad request with json object of curl POST command while flask is running
|
I just made flask API. OS is Win10. python version is 3.9.13. While the flask is running, I sent the following command.
curl -X POST http://127.0.0.1:5000/detect -H "Content-Type: application/json" -d '{"filename": "xxx.jpg"}'
However, I received 400 BAD Request.
<!doctype html>
<html lang=en>
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Failed to decode JSON: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)</p>
The codes of python have not received the request.
I googled a lot. Also, I checked the curl commands.
There is api directly.
---name of python= ___init___.py
from api import flask_test
from flask import Blueprint, jsonify, request
api = Blueprint("api", __name__)
@api.get("/")
def index():
return jsonify({"column": "value"}), 201
@api.post("/detect")
def detection():
return flask_test.detection(request)
The next file is follows;
---name of python flask_test.py
def load_image(request):
print('----')
filename = request.json["filename"]
print(filename)
dir_image = str(basedir / "data" / "original" / filename)
image = Image.open(dir_image).convert('RGB')
return image, filename
def detection(request):
print("test")
load_image(request)
Running flask codes are as follows;
----app.py
import os
from flask import Flask
from api import api
class Config:
TESTING = False
DEBUG = False
LABELS = [
"people",
"Population"
]
class LocalConfig(Config):
TESTING = True
DEBUG = True
config = {
"base": Config,
"local": LocalConfig,
}
config_name = os.environ.get("CONFIG", "local")
app = Flask(__name__)
app.config.from_object(config[config_name])
app.register_blueprint(api)
At api directory, you need the following commands(Win10)
$FLASK_APP="app.py"
$FLASK_ENV="development"
flask run
You will see json file at pot 5000.
{
"column": "value"
}
You see the following terminal screen;
enter image description here
Yuu see the following console screen;
enter image description here
You see "test", "----". But, you can't see the result of print(filename)
So that, request.json["filename"]
doesn't work well.
|
[
"you are returning a non-json response.\ntry this:-\n@api.post(\"/detect\")\ndef detection():\nreturn jsonify({\"response\":flask_test.detection(request)})\n\n"
] |
[
0
] |
[] |
[] |
[
"curl",
"flask",
"json",
"python",
"python_3.x"
] |
stackoverflow_0074469709_curl_flask_json_python_python_3.x.txt
|
Q:
how do I find a continuos number in dataframe and apply to new column
I have a huge dataframe around 5000 rows, I need to find out how many times a pattern occur in a column and add a new column for it, I am able to use np.where to get the pattern to 1 but I don't know how to count the pattern and add to new column, I did a search online try to use loop but I can't figure out how to use loop with dataframe
df['P'] = np.where((df['val2'] > df['val1']) & (df['val2']> df['val1'].shift(1)),1,0 )
Date val1 val2 P [new column] (
0 2015-02-24 294 68 0 0
1 2015-02-25 155 31 0 0
2 2015-02-26 168 290 1 1 pattern occur 1 time
3 2015-02-27 273 108 0 0
4 2015-02-28 55 9 0 0
5 2015-03-01 273 123 0 0
6 2015-03-02 200 46 0 0
7 2015-03-03 80 83 0 0
8 2015-03-04 181 208 1 1 pattern occur 1 time
9 2015-03-05 195 41 0 0
10 2015-03-06 50 261 1 1 pattern occur 1 time
11 2015-03-07 50 177 0 0
12 2015-03-08 215 60 1 0
13 2015-03-09 13 290 1 2 pattern occur 2 times
14 2015-03-10 208 41 0 0
15 2015-03-11 49 263 1 0
16 2015-03-12 171 244 1 0
17 2015-03-13 218 266 1 0
18 2015-03-14 188 219 1 3 pattern occur 3 times
19 2015-03-15 232 171 0 0
20 2015-03-16 116 196 0 0
21 2015-03-17 262 102 0 0
22 2015-03-18 263 159 0 0
23 2015-03-19 227 160 0 0
24 2015-03-20 103 236 1 0
25 2015-03-21 55 104 1 0
26 2015-03-22 97 109 1 0
27 2015-03-23 38 118 1 4 pattern occur 4 times
28 2015-03-24 163 116 0 0
29 2015-03-25 256 16 0 0
A:
you can use:
df['new_column'] = (df.P != df.P.shift()).cumsum() #get an id according to P
mask=df.groupby('new_column')['P'].sum() #what is the total value for each group
duplicated = df.duplicated('new_column',keep='last')
df.loc[~duplicated, ['new_column']] = np.nan #set nan to last rows for each group. We will replace nans with mask
df['new_column'] = df['new_column'].astype(str).replace('\d+', 0,regex=True).replace('nan',np.nan) #convert not nans to zero
mask.index=df[df['new_column'].isnull()].index.to_list()
#If you want to fill the nan values with a series, the index values must be the same. So I replace the index values of the mask series with the index numbers of the nan values in df.
df['new_column']=df['new_column'].fillna(mask).astype(int)
df
'''
Date val1 val2 P new_column
0 2015-02-24 294 68 0 0
1 2015-02-25 155 31 0 0
2 2015-02-26 168 290 1 1
3 2015-02-27 273 108 0 0
4 2015-02-28 55 9 0 0
5 2015-03-01 273 123 0 0
6 2015-03-02 200 46 0 0
7 2015-03-03 80 83 0 0
8 2015-03-04 181 208 1 1
9 2015-03-05 195 41 0 0
10 2015-03-06 50 261 1 1
11 2015-03-07 50 177 0 0
12 2015-03-08 215 60 1 0
13 2015-03-09 13 290 1 2
14 2015-03-10 208 41 0 0
15 2015-03-11 49 263 1 0
16 2015-03-12 171 244 1 0
17 2015-03-13 218 266 1 0
18 2015-03-14 188 219 1 4
19 2015-03-15 232 171 0 0
20 2015-03-16 116 196 0 0
21 2015-03-17 262 102 0 0
22 2015-03-18 263 159 0 0
23 2015-03-19 227 160 0 0
24 2015-03-20 103 236 1 0
25 2015-03-21 55 104 1 0
26 2015-03-22 97 109 1 0
27 2015-03-23 38 118 1 4
28 2015-03-24 163 116 0 0
29 2015-03-25 256 16 0 0
'''
A:
I'm sure there is a better way to do this, considering using df.iterrows() is almost never the right way, but it works and you only have 5000 rows of data so efficiency is not paramount.
import pandas as pd
import numpy as np
df = pd.DataFrame({'Date': {0: '2015-02-24', 1: '2015-02-25', 2: '2015-02-26', 3: '2015-02-27', 4: '2015-02-28', 5: '2015-03-01', 6: '2015-03-02', 7: '2015-03-03', 8: '2015-03-04', 9: '2015-03-05', 10: '2015-03-06', 11: '2015-03-07', 12: '2015-03-08', 13: '2015-03-09', 14: '2015-03-10', 15: '2015-03-11', 16: '2015-03-12', 17: '2015-03-13', 18: '2015-03-14', 19: '2015-03-15', 20: '2015-03-16', 21: '2015-03-17', 22: '2015-03-18', 23: '2015-03-19', 24: '2015-03-20', 25: '2015-03-21', 26: '2015-03-22', 27: '2015-03-23', 28: '2015-03-24', 29: '2015-03-25'}, 'val1': {0: 294, 1: 155, 2: 168, 3: 273, 4: 55, 5: 273, 6: 200, 7: 80, 8: 181, 9: 195, 10: 50, 11: 50, 12: 215, 13: 13, 14: 208, 15: 49, 16: 171, 17: 218, 18: 188, 19: 232, 20: 116, 21: 262, 22: 263, 23: 227, 24: 103, 25: 55, 26: 97, 27: 38, 28: 163, 29: 256}, 'val2': {0: 68, 1: 31, 2: 290, 3: 108, 4: 9, 5: 123, 6: 46, 7: 83, 8: 208, 9: 41, 10: 261, 11: 177, 12: 60, 13: 290, 14: 41, 15: 263, 16: 244, 17: 266, 18: 219, 19: 171, 20: 196, 21: 102, 22: 159, 23: 160, 24: 236, 25: 104, 26: 109, 27: 118, 28: 116, 29: 16}})
df['P'] = np.where((df['val2'] > df['val1']) & (df['val2']> df['val1'].shift(1)),1,0 )
df['new_column'] = 0
counter = 0
for i, row, in df.iterrows():
if row.P == 1:
counter += 1
else:
counter = 0
df.loc[i, 'new_column'] = counter
df.new_column = df.new_column * [1 if x == 0 else 0 for x in df.new_column.shift(-1) ]
gives
Date val1 val2 P new_column
0 2015-02-24 294 68 0 0
1 2015-02-25 155 31 0 0
2 2015-02-26 168 290 1 1
3 2015-02-27 273 108 0 0
4 2015-02-28 55 9 0 0
5 2015-03-01 273 123 0 0
6 2015-03-02 200 46 0 0
7 2015-03-03 80 83 0 0
8 2015-03-04 181 208 1 1
9 2015-03-05 195 41 0 0
10 2015-03-06 50 261 1 0
11 2015-03-07 50 177 1 2
12 2015-03-08 215 60 0 0
13 2015-03-09 13 290 1 1
14 2015-03-10 208 41 0 0
15 2015-03-11 49 263 1 0
16 2015-03-12 171 244 1 0
17 2015-03-13 218 266 1 0
18 2015-03-14 188 219 1 4
19 2015-03-15 232 171 0 0
20 2015-03-16 116 196 0 0
21 2015-03-17 262 102 0 0
22 2015-03-18 263 159 0 0
23 2015-03-19 227 160 0 0
24 2015-03-20 103 236 1 0
25 2015-03-21 55 104 1 0
26 2015-03-22 97 109 1 0
27 2015-03-23 38 118 1 4
28 2015-03-24 163 116 0 0
29 2015-03-25 256 16 0 0
|
how do I find a continuos number in dataframe and apply to new column
|
I have a huge dataframe around 5000 rows, I need to find out how many times a pattern occur in a column and add a new column for it, I am able to use np.where to get the pattern to 1 but I don't know how to count the pattern and add to new column, I did a search online try to use loop but I can't figure out how to use loop with dataframe
df['P'] = np.where((df['val2'] > df['val1']) & (df['val2']> df['val1'].shift(1)),1,0 )
Date val1 val2 P [new column] (
0 2015-02-24 294 68 0 0
1 2015-02-25 155 31 0 0
2 2015-02-26 168 290 1 1 pattern occur 1 time
3 2015-02-27 273 108 0 0
4 2015-02-28 55 9 0 0
5 2015-03-01 273 123 0 0
6 2015-03-02 200 46 0 0
7 2015-03-03 80 83 0 0
8 2015-03-04 181 208 1 1 pattern occur 1 time
9 2015-03-05 195 41 0 0
10 2015-03-06 50 261 1 1 pattern occur 1 time
11 2015-03-07 50 177 0 0
12 2015-03-08 215 60 1 0
13 2015-03-09 13 290 1 2 pattern occur 2 times
14 2015-03-10 208 41 0 0
15 2015-03-11 49 263 1 0
16 2015-03-12 171 244 1 0
17 2015-03-13 218 266 1 0
18 2015-03-14 188 219 1 3 pattern occur 3 times
19 2015-03-15 232 171 0 0
20 2015-03-16 116 196 0 0
21 2015-03-17 262 102 0 0
22 2015-03-18 263 159 0 0
23 2015-03-19 227 160 0 0
24 2015-03-20 103 236 1 0
25 2015-03-21 55 104 1 0
26 2015-03-22 97 109 1 0
27 2015-03-23 38 118 1 4 pattern occur 4 times
28 2015-03-24 163 116 0 0
29 2015-03-25 256 16 0 0
|
[
"you can use:\ndf['new_column'] = (df.P != df.P.shift()).cumsum() #get an id according to P\nmask=df.groupby('new_column')['P'].sum() #what is the total value for each group\n\nduplicated = df.duplicated('new_column',keep='last')\ndf.loc[~duplicated, ['new_column']] = np.nan #set nan to last rows for each group. We will replace nans with mask\n\ndf['new_column'] = df['new_column'].astype(str).replace('\\d+', 0,regex=True).replace('nan',np.nan) #convert not nans to zero\nmask.index=df[df['new_column'].isnull()].index.to_list()\n#If you want to fill the nan values with a series, the index values must be the same. So I replace the index values of the mask series with the index numbers of the nan values in df.\n\ndf['new_column']=df['new_column'].fillna(mask).astype(int)\ndf\n'''\n Date val1 val2 P new_column\n0 2015-02-24 294 68 0 0\n1 2015-02-25 155 31 0 0\n2 2015-02-26 168 290 1 1\n3 2015-02-27 273 108 0 0\n4 2015-02-28 55 9 0 0\n5 2015-03-01 273 123 0 0\n6 2015-03-02 200 46 0 0\n7 2015-03-03 80 83 0 0\n8 2015-03-04 181 208 1 1\n9 2015-03-05 195 41 0 0\n10 2015-03-06 50 261 1 1\n11 2015-03-07 50 177 0 0\n12 2015-03-08 215 60 1 0\n13 2015-03-09 13 290 1 2\n14 2015-03-10 208 41 0 0\n15 2015-03-11 49 263 1 0\n16 2015-03-12 171 244 1 0\n17 2015-03-13 218 266 1 0\n18 2015-03-14 188 219 1 4\n19 2015-03-15 232 171 0 0\n20 2015-03-16 116 196 0 0\n21 2015-03-17 262 102 0 0\n22 2015-03-18 263 159 0 0\n23 2015-03-19 227 160 0 0\n24 2015-03-20 103 236 1 0\n25 2015-03-21 55 104 1 0\n26 2015-03-22 97 109 1 0\n27 2015-03-23 38 118 1 4\n28 2015-03-24 163 116 0 0\n29 2015-03-25 256 16 0 0\n\n'''\n\n",
"I'm sure there is a better way to do this, considering using df.iterrows() is almost never the right way, but it works and you only have 5000 rows of data so efficiency is not paramount.\nimport pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({'Date': {0: '2015-02-24', 1: '2015-02-25', 2: '2015-02-26', 3: '2015-02-27', 4: '2015-02-28', 5: '2015-03-01', 6: '2015-03-02', 7: '2015-03-03', 8: '2015-03-04', 9: '2015-03-05', 10: '2015-03-06', 11: '2015-03-07', 12: '2015-03-08', 13: '2015-03-09', 14: '2015-03-10', 15: '2015-03-11', 16: '2015-03-12', 17: '2015-03-13', 18: '2015-03-14', 19: '2015-03-15', 20: '2015-03-16', 21: '2015-03-17', 22: '2015-03-18', 23: '2015-03-19', 24: '2015-03-20', 25: '2015-03-21', 26: '2015-03-22', 27: '2015-03-23', 28: '2015-03-24', 29: '2015-03-25'}, 'val1': {0: 294, 1: 155, 2: 168, 3: 273, 4: 55, 5: 273, 6: 200, 7: 80, 8: 181, 9: 195, 10: 50, 11: 50, 12: 215, 13: 13, 14: 208, 15: 49, 16: 171, 17: 218, 18: 188, 19: 232, 20: 116, 21: 262, 22: 263, 23: 227, 24: 103, 25: 55, 26: 97, 27: 38, 28: 163, 29: 256}, 'val2': {0: 68, 1: 31, 2: 290, 3: 108, 4: 9, 5: 123, 6: 46, 7: 83, 8: 208, 9: 41, 10: 261, 11: 177, 12: 60, 13: 290, 14: 41, 15: 263, 16: 244, 17: 266, 18: 219, 19: 171, 20: 196, 21: 102, 22: 159, 23: 160, 24: 236, 25: 104, 26: 109, 27: 118, 28: 116, 29: 16}})\n\ndf['P'] = np.where((df['val2'] > df['val1']) & (df['val2']> df['val1'].shift(1)),1,0 )\n\ndf['new_column'] = 0\ncounter = 0\n\nfor i, row, in df.iterrows():\n if row.P == 1:\n counter += 1\n else:\n counter = 0\n df.loc[i, 'new_column'] = counter\n\ndf.new_column = df.new_column * [1 if x == 0 else 0 for x in df.new_column.shift(-1) ]\n\ngives\n Date val1 val2 P new_column\n0 2015-02-24 294 68 0 0\n1 2015-02-25 155 31 0 0\n2 2015-02-26 168 290 1 1\n3 2015-02-27 273 108 0 0\n4 2015-02-28 55 9 0 0\n5 2015-03-01 273 123 0 0\n6 2015-03-02 200 46 0 0\n7 2015-03-03 80 83 0 0\n8 2015-03-04 181 208 1 1\n9 2015-03-05 195 41 0 0\n10 2015-03-06 50 261 1 0\n11 2015-03-07 50 177 1 2\n12 2015-03-08 215 60 0 0\n13 2015-03-09 13 290 1 1\n14 2015-03-10 208 41 0 0\n15 2015-03-11 49 263 1 0\n16 2015-03-12 171 244 1 0\n17 2015-03-13 218 266 1 0\n18 2015-03-14 188 219 1 4\n19 2015-03-15 232 171 0 0\n20 2015-03-16 116 196 0 0\n21 2015-03-17 262 102 0 0\n22 2015-03-18 263 159 0 0\n23 2015-03-19 227 160 0 0\n24 2015-03-20 103 236 1 0\n25 2015-03-21 55 104 1 0\n26 2015-03-22 97 109 1 0\n27 2015-03-23 38 118 1 4\n28 2015-03-24 163 116 0 0\n29 2015-03-25 256 16 0 0\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"dataframe",
"design_patterns",
"numpy",
"pandas",
"python"
] |
stackoverflow_0074567984_dataframe_design_patterns_numpy_pandas_python.txt
|
Q:
need to generate a new data frame with more no. of similar record from an existing data frame
I have the below dataframe data sample,
val df= spark.read.option("inferSchema",true).orc("abc/path/abc.snappy.orc")
df.show()
ID, date, timestamp, count, idcount, unit, code, Pcode, ccode, bid, vcode
12345432,10-11-2011,11:11:12.555,0,0,XVC_AS,12,14,19,123454323,qweds
I want to write a pyspark code to generate more no. of record by just incrementing the ID and remaining column as it is.
Example
12345432,10-11-2011,11:11:12.555,0,0,XVC_AS,12,14,19,123454323,qweds
12345433,10-11-2011,11:11:12.555,0,0,XVC_AS,12,14,19,123454323,qweds
12345434,10-11-2011,11:11:12.555,0,0,XVC_AS,12,14,19,123454323,qweds
12345435,10-11-2011,11:11:12.555,0,0,XVC_AS,12,14,19,123454323,qweds
12345436,10-11-2011,11:11:12.555,0,0,XVC_AS,12,14,19,123454323,qweds
12345437,10-11-2011,11:11:12.555,0,0,XVC_AS,12,14,19,123454323,qweds
I tried using lit, but not able to arrive at exact code
A:
After the update my solution seems to be quite cumnbersome but this is all i can offer so far.
Assuming you have your ID column as dataframe index, you can simply do:
import numpy as np
incr = 10
df = df.reindex(np.append(df.index.values,
range(df.index.max()+1, df.index.max()+incr)),
method="ffill")
and get:
date timestamp count idcount unit code Pcode ccode bid vcode
ID
12345432 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds
12345433 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds
12345434 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds
12345435 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds
12345436 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds
12345437 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds
12345438 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds
12345439 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds
12345440 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds
12345441 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds
12345442 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds
this is the proper way of reindexinf in case you already have a daraframe with more the one rows.
UPDATE due to question additions:
if you need to increment columns that are not index, i have nothing to offer more original than this:
incr = 10
df = df.reindex(np.append(df.index.values,
range(df.index.max()+1, df.index.max()+incr)))#,
cols_to_incr = ["Pcode", "code"]
df = df.apply(lambda x: x.ffill() if x.name not in cols_to_incr else x)
for col in cols_to_incr:
df.loc[df[col].idxmax()+1:,col] = np.arange(df[col].max()+1, df[col].max()+1+len(df.loc[df[col].idxmax()+1:,col]))
date timestamp count idcount unit code Pcode ccode bid vcode
ID
12345432 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 12.0 14.0 19.0 123454323.0 qweds
12345433 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 13.0 15.0 19.0 123454323.0 qweds
12345434 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 14.0 16.0 19.0 123454323.0 qweds
12345435 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 15.0 17.0 19.0 123454323.0 qweds
12345436 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 16.0 18.0 19.0 123454323.0 qweds
12345437 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 17.0 19.0 19.0 123454323.0 qweds
12345438 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 18.0 20.0 19.0 123454323.0 qweds
12345439 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 19.0 21.0 19.0 123454323.0 qweds
12345440 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 20.0 22.0 19.0 123454323.0 qweds
12345441 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 21.0 23.0 19.0 123454323.0 qweds
12345442 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 22.0 24.0 19.0 123454323.0 qweds
|
need to generate a new data frame with more no. of similar record from an existing data frame
|
I have the below dataframe data sample,
val df= spark.read.option("inferSchema",true).orc("abc/path/abc.snappy.orc")
df.show()
ID, date, timestamp, count, idcount, unit, code, Pcode, ccode, bid, vcode
12345432,10-11-2011,11:11:12.555,0,0,XVC_AS,12,14,19,123454323,qweds
I want to write a pyspark code to generate more no. of record by just incrementing the ID and remaining column as it is.
Example
12345432,10-11-2011,11:11:12.555,0,0,XVC_AS,12,14,19,123454323,qweds
12345433,10-11-2011,11:11:12.555,0,0,XVC_AS,12,14,19,123454323,qweds
12345434,10-11-2011,11:11:12.555,0,0,XVC_AS,12,14,19,123454323,qweds
12345435,10-11-2011,11:11:12.555,0,0,XVC_AS,12,14,19,123454323,qweds
12345436,10-11-2011,11:11:12.555,0,0,XVC_AS,12,14,19,123454323,qweds
12345437,10-11-2011,11:11:12.555,0,0,XVC_AS,12,14,19,123454323,qweds
I tried using lit, but not able to arrive at exact code
|
[
"After the update my solution seems to be quite cumnbersome but this is all i can offer so far.\nAssuming you have your ID column as dataframe index, you can simply do:\nimport numpy as np\nincr = 10\ndf = df.reindex(np.append(df.index.values,\n range(df.index.max()+1, df.index.max()+incr)),\n method=\"ffill\")\n\nand get:\n date timestamp count idcount unit code Pcode ccode bid vcode\nID \n12345432 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds\n12345433 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds\n12345434 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds\n12345435 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds\n12345436 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds\n12345437 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds\n12345438 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds\n12345439 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds\n12345440 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds\n12345441 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds\n12345442 10-11-2011 11:11:12.555 0 0 XVC_AS 12 14 19 123454323 qweds\n\nthis is the proper way of reindexinf in case you already have a daraframe with more the one rows.\nUPDATE due to question additions:\nif you need to increment columns that are not index, i have nothing to offer more original than this:\nincr = 10\n\ndf = df.reindex(np.append(df.index.values,\n range(df.index.max()+1, df.index.max()+incr)))#,\ncols_to_incr = [\"Pcode\", \"code\"]\ndf = df.apply(lambda x: x.ffill() if x.name not in cols_to_incr else x)\n\nfor col in cols_to_incr:\n df.loc[df[col].idxmax()+1:,col] = np.arange(df[col].max()+1, df[col].max()+1+len(df.loc[df[col].idxmax()+1:,col]))\n\n date timestamp count idcount unit code Pcode ccode bid vcode\nID \n12345432 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 12.0 14.0 19.0 123454323.0 qweds\n12345433 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 13.0 15.0 19.0 123454323.0 qweds\n12345434 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 14.0 16.0 19.0 123454323.0 qweds\n12345435 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 15.0 17.0 19.0 123454323.0 qweds\n12345436 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 16.0 18.0 19.0 123454323.0 qweds\n12345437 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 17.0 19.0 19.0 123454323.0 qweds\n12345438 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 18.0 20.0 19.0 123454323.0 qweds\n12345439 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 19.0 21.0 19.0 123454323.0 qweds\n12345440 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 20.0 22.0 19.0 123454323.0 qweds\n12345441 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 21.0 23.0 19.0 123454323.0 qweds\n12345442 10-11-2011 11:11:12.555 0.0 0.0 XVC_AS 22.0 24.0 19.0 123454323.0 qweds\n\n"
] |
[
0
] |
[] |
[] |
[
"apache_spark",
"pyspark",
"python"
] |
stackoverflow_0074571730_apache_spark_pyspark_python.txt
|
Q:
Upload Images To S3 Via URL Python
im just searching for a method to upload images to S3 directly via an URL with Python.
What i mean by that is:
I have an URL e.g. https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/1200px-Google_2015_logo.svg.png
now i want my code to take that image url and save the image in my S3 bucket with my desired key.
So when i go to my S3 Bucket i want there to be a img file with my key and i can download it.
Is it somehow possible to accomplish this with Python?
Thank you very much. I tried the s3.upload_file function but it just seems to work locally.
A:
If it's working only through EC2, it might be a permission/firewall issue?
This might be of help.
https://aws.amazon.com/premiumsupport/knowledge-center/api-gateway-upload-image-s3/
boto3 would be the way to go for Python.
https://boto3.amazonaws.com/v1/documentation/api/latest/index.html
Someone has done something similar here:
Most efficient way to upload image to Amazon S3 with Python using Boto3
|
Upload Images To S3 Via URL Python
|
im just searching for a method to upload images to S3 directly via an URL with Python.
What i mean by that is:
I have an URL e.g. https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/1200px-Google_2015_logo.svg.png
now i want my code to take that image url and save the image in my S3 bucket with my desired key.
So when i go to my S3 Bucket i want there to be a img file with my key and i can download it.
Is it somehow possible to accomplish this with Python?
Thank you very much. I tried the s3.upload_file function but it just seems to work locally.
|
[
"If it's working only through EC2, it might be a permission/firewall issue?\nThis might be of help.\nhttps://aws.amazon.com/premiumsupport/knowledge-center/api-gateway-upload-image-s3/\nboto3 would be the way to go for Python.\nhttps://boto3.amazonaws.com/v1/documentation/api/latest/index.html\nSomeone has done something similar here:\nMost efficient way to upload image to Amazon S3 with Python using Boto3\n"
] |
[
0
] |
[] |
[] |
[
"amazon_s3",
"amazon_web_services",
"python"
] |
stackoverflow_0074571997_amazon_s3_amazon_web_services_python.txt
|
Q:
Google Calendar API event time update without changing date
Is there any way to update the current time of an event without changing the current date using google calendar API with python?
I'm working on a project that sync zoho people calendar with google calendar and I've to update the all day Leave event and set a duration of 9 hours (9AM to 6PM). I've done the synching part and all and I'm able to change the time and duration also, but I can't change the time without changing the event date [datetime.now()]. What I want is to keep the date of the event as it is and just change the time of event.
A:
Using gcsa, this would look like:
from gcsa.google_calendar import GoogleCalendar
from datetime import datetime, time
gc = GoogleCalendar('path/to/credentials.json')
event = gc.get_event('event_id')
event.start = datetime.combine(event.start, time(hour=9))
event.end = datetime.combine(event.end, time(hour=18))
gc.update_event(event)
|
Google Calendar API event time update without changing date
|
Is there any way to update the current time of an event without changing the current date using google calendar API with python?
I'm working on a project that sync zoho people calendar with google calendar and I've to update the all day Leave event and set a duration of 9 hours (9AM to 6PM). I've done the synching part and all and I'm able to change the time and duration also, but I can't change the time without changing the event date [datetime.now()]. What I want is to keep the date of the event as it is and just change the time of event.
|
[
"Using gcsa, this would look like:\nfrom gcsa.google_calendar import GoogleCalendar\nfrom datetime import datetime, time\n\ngc = GoogleCalendar('path/to/credentials.json')\n\nevent = gc.get_event('event_id')\nevent.start = datetime.combine(event.start, time(hour=9))\nevent.end = datetime.combine(event.end, time(hour=18))\n\ngc.update_event(event)\n\n"
] |
[
0
] |
[] |
[] |
[
"google_calendar_api",
"python",
"zoho"
] |
stackoverflow_0074558603_google_calendar_api_python_zoho.txt
|
Q:
Replicate Random Numbers from Visual Basic with Python
I have a code in Visual Basic that generates a vector of random numbers for a given seed (456 in my case). I need to replicate that code in Python and I am thinking if it is possible to generate with Python the same vector of random numbers, that is, to select the same seed as in VBA.
Let me show an example:
In VBA I have the following code:
Function rnd_seed(seed)
Dim x(1 To 10) As Double
Rnd (-1)
Randomize seed
For i = 1 To 10
x(i) = Rnd
Next i
rnd_seed = x
End Function
With this function, I obtain the values (for seed 456):
0.014666617
0.462389946
0.098651111
0.189074159
0.107685387
0.219710588
0.967558324
0.409745097
0.213494837
0.848815441
In Python, I use the following code (as suggested by K-D-G):
seed = 456
import random
random.seed(seed)
arr=[]
for i in range(10):
arr.append(random.random())
With this Python code, I obtain the following values:
[0.7482025358782363,
0.9665873085424435,
0.4352093219057409,
0.7942997804992433,
0.6481497216250237,
0.6174050474978059,
0.8222710780743806,
0.7895737180242367,
0.8864808985728122,
0.3264489135810307]
I see that the values obtained for VBA and Python are different. My question is if it is possible to generate with Python the same random numbers that I have generated with VBA. Is there any way to map the VBA and Python seeds?
Many thanks in advance!
A:
Something like this:
import random
random.seed(seed)
arr=[]
for i in range(n):
arr.append(random.random())
Note random.random() returns value between 0 and 1 if you want integers over a range use random.randint(start, stop)
|
Replicate Random Numbers from Visual Basic with Python
|
I have a code in Visual Basic that generates a vector of random numbers for a given seed (456 in my case). I need to replicate that code in Python and I am thinking if it is possible to generate with Python the same vector of random numbers, that is, to select the same seed as in VBA.
Let me show an example:
In VBA I have the following code:
Function rnd_seed(seed)
Dim x(1 To 10) As Double
Rnd (-1)
Randomize seed
For i = 1 To 10
x(i) = Rnd
Next i
rnd_seed = x
End Function
With this function, I obtain the values (for seed 456):
0.014666617
0.462389946
0.098651111
0.189074159
0.107685387
0.219710588
0.967558324
0.409745097
0.213494837
0.848815441
In Python, I use the following code (as suggested by K-D-G):
seed = 456
import random
random.seed(seed)
arr=[]
for i in range(10):
arr.append(random.random())
With this Python code, I obtain the following values:
[0.7482025358782363,
0.9665873085424435,
0.4352093219057409,
0.7942997804992433,
0.6481497216250237,
0.6174050474978059,
0.8222710780743806,
0.7895737180242367,
0.8864808985728122,
0.3264489135810307]
I see that the values obtained for VBA and Python are different. My question is if it is possible to generate with Python the same random numbers that I have generated with VBA. Is there any way to map the VBA and Python seeds?
Many thanks in advance!
|
[
"Something like this:\nimport random\nrandom.seed(seed)\narr=[]\nfor i in range(n):\n arr.append(random.random())\n\nNote random.random() returns value between 0 and 1 if you want integers over a range use random.randint(start, stop)\n"
] |
[
0
] |
[] |
[] |
[
"python",
"random_seed",
"vba"
] |
stackoverflow_0074572032_python_random_seed_vba.txt
|
Q:
DataFrame.set_index returns 'str' object is not callable
I'm not looking for a solution here as I found a workaround; mostly I'd just like to understand why my original approach didn't work given that the work around did.
I have a dataframe of 2803 rows with the default numeric key. I want to replace that with the values in column 0, namely TKR.
So I use f.set_index('TKR') and get
f.set_index('TKR')
Traceback (most recent call last):
File "<ipython-input-4-39232ca70c3d>", line 1, in <module>
f.set_index('TKR')
TypeError: 'str' object is not callable
So I think maybe there's some noise in my TKR column and rather than scrolling through 2803 rows I try f.head().set_index('TKR')
When that works I try f.head(100).set_index('TKR') which also works. I continue with parameters of 500, 1000, and 1500 all of which work. So do 2800, 2801, 2802 and 2803. Finally I settle on
f.head(len(f)).set_index('TKR')
which works and will handle a different size dataframe next month. I would just like to understand why this works and the original, simpler, and (I thought) by the book method doesn't.
I'm using Python 3.6 (64 bit) and Pandas 0.18.1 on a Windows 10 machine
A:
You might have accidentally assigned the pd.DataFrame.set_index() to a value.
example of this mistake: f.set_index = 'intended_col_name'
As a result for the rest of your code .set_index was changed into a str, which is not callable, resulting in this error.
Try restarting your notebook, remove the wrong code and replace it with f.set_index('TKR')
A:
I know it's been a long while, but I think some people may need the answer in the future.
What you do with f.set_index('TKR') is totally right as long as 'TKR' is a column of DataFrame f.
That is to say, this is a bug you are not supposed to have. It is always because that you redefine some build-in function methods or functions of python in your former steps(Possibly 'set_index'). So, the way to fix is to review your code to find out which part is wrong.
If you are using Jupiter notebook, restart it and run this block only can fix this problem.
A:
I believe I have a solution for you.
I ran into the same problem and I was constructing my dataframes from a dictionary, like this:
df_beta = df['Beta']
df_returns = df['Returns']
then, trying to do df_beta.set_index(Date) would fail. My workaround was
df_beta = df['Beta'].copy()
df_returns = df['Returns'].copy()
So apparently, if you build your dataframes as a "view" of another existing dataframe, you can't set index and it will raise 'Series not callable' error. If instead you create an explicit new object copying the original dataframes, then you can call reset_index, which is what you kind of do when you compute the head.
Hope this helps, 2 years later :)
A:
I have the same problem here.
import tushare as ts
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
ts.set_token('*************************************')
tspro = ts.pro_api()
gjyx = tspro.daily(ts_code='000516.SZ', start_date='20190101')
# this doesn't work
# out:'str' object is not callable
gjyx = gjyx.set_index('trade_date')
# this works
gjyx = gjyx.head(len(gjyx)).set_index('trade_date')
jupyter notebook 6.1.6, python 3.9.1, miniconda3, win10
But when I upload this ipynb to ubuntu on AWS, it works.
A:
I once had this same issue.
This simple line of code keep throwing TypeError: 'series' object is not callable error again and again.
df = df.set_index('Date')
I had to shutdown my kernel and restart the jupyter notebook to fix it.
|
DataFrame.set_index returns 'str' object is not callable
|
I'm not looking for a solution here as I found a workaround; mostly I'd just like to understand why my original approach didn't work given that the work around did.
I have a dataframe of 2803 rows with the default numeric key. I want to replace that with the values in column 0, namely TKR.
So I use f.set_index('TKR') and get
f.set_index('TKR')
Traceback (most recent call last):
File "<ipython-input-4-39232ca70c3d>", line 1, in <module>
f.set_index('TKR')
TypeError: 'str' object is not callable
So I think maybe there's some noise in my TKR column and rather than scrolling through 2803 rows I try f.head().set_index('TKR')
When that works I try f.head(100).set_index('TKR') which also works. I continue with parameters of 500, 1000, and 1500 all of which work. So do 2800, 2801, 2802 and 2803. Finally I settle on
f.head(len(f)).set_index('TKR')
which works and will handle a different size dataframe next month. I would just like to understand why this works and the original, simpler, and (I thought) by the book method doesn't.
I'm using Python 3.6 (64 bit) and Pandas 0.18.1 on a Windows 10 machine
|
[
"You might have accidentally assigned the pd.DataFrame.set_index() to a value.\nexample of this mistake: f.set_index = 'intended_col_name'\nAs a result for the rest of your code .set_index was changed into a str, which is not callable, resulting in this error.\nTry restarting your notebook, remove the wrong code and replace it with f.set_index('TKR')\n",
"I know it's been a long while, but I think some people may need the answer in the future.\nWhat you do with f.set_index('TKR') is totally right as long as 'TKR' is a column of DataFrame f.\nThat is to say, this is a bug you are not supposed to have. It is always because that you redefine some build-in function methods or functions of python in your former steps(Possibly 'set_index'). So, the way to fix is to review your code to find out which part is wrong.\nIf you are using Jupiter notebook, restart it and run this block only can fix this problem.\n",
"I believe I have a solution for you.\nI ran into the same problem and I was constructing my dataframes from a dictionary, like this:\ndf_beta = df['Beta']\ndf_returns = df['Returns']\n\nthen, trying to do df_beta.set_index(Date) would fail. My workaround was\ndf_beta = df['Beta'].copy()\ndf_returns = df['Returns'].copy()\n\nSo apparently, if you build your dataframes as a \"view\" of another existing dataframe, you can't set index and it will raise 'Series not callable' error. If instead you create an explicit new object copying the original dataframes, then you can call reset_index, which is what you kind of do when you compute the head.\nHope this helps, 2 years later :)\n",
"I have the same problem here.\nimport tushare as ts\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nts.set_token('*************************************')\n\ntspro = ts.pro_api()\n\ngjyx = tspro.daily(ts_code='000516.SZ', start_date='20190101')\n\n# this doesn't work\n# out:'str' object is not callable\ngjyx = gjyx.set_index('trade_date')\n\n\n# this works\ngjyx = gjyx.head(len(gjyx)).set_index('trade_date')\n\njupyter notebook 6.1.6, python 3.9.1, miniconda3, win10\nBut when I upload this ipynb to ubuntu on AWS, it works.\n",
"I once had this same issue.\nThis simple line of code keep throwing TypeError: 'series' object is not callable error again and again.\ndf = df.set_index('Date')\n\nI had to shutdown my kernel and restart the jupyter notebook to fix it.\n"
] |
[
6,
1,
0,
0,
0
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0044593223_pandas_python.txt
|
Q:
Automatically delete items from multiple lists at once
I currently have a small problem with the processing of some data that I recover.
I'm getting data that's constantly changing and it's displayed as a list like this:
[['test', 'test', 'test', 'test'], ['test', 'test', 'test', 'test'], ['test', 'test', 'test', ' test']]
I would like to know how it is possible to automatically delete the second element of each list given that the number of lists can vary depending on the result of the query and that its value can also vary.
A:
You could either use .pop(index) or del arr[index]. But since you said it can vary I would use len(arr) to make sure the arr length goes up to the index you are trying to delete
|
Automatically delete items from multiple lists at once
|
I currently have a small problem with the processing of some data that I recover.
I'm getting data that's constantly changing and it's displayed as a list like this:
[['test', 'test', 'test', 'test'], ['test', 'test', 'test', 'test'], ['test', 'test', 'test', ' test']]
I would like to know how it is possible to automatically delete the second element of each list given that the number of lists can vary depending on the result of the query and that its value can also vary.
|
[
"You could either use .pop(index) or del arr[index]. But since you said it can vary I would use len(arr) to make sure the arr length goes up to the index you are trying to delete\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074572094_python.txt
|
Q:
matplotlib logarithmic colormap for logarithmic surface plot
I'm using python to create a 3D surface map, I have an array of data I'm trying to plot as a 3D surface, the issue is that I have logged the Z axis (necessary to show peaks in data) which means the default colormap doesn't work (displays one continous color). I've tried using the LogNorm to normalise the colormap but again this produces one continous color. I'm not sure whether I should be using the logged values to normalise the map, but if i do this the max is negative and produces an error?
fig=plt.figure(figsize=(10,10))
ax=plt.axes(projection='3d')
def log_tick_formatter(val, pos=None):
return "{:.2e}".format(10**val)
ax.zaxis.set_major_formatter(mticker.FuncFormatter(log_tick_formatter))
X=np.arange(0,2,1)
Y=np.arange(0,3,1)
X,Y=np.meshgrid(X,Y)
Z=[[1.2e-11,1.3e-11,-1.8e-11],[6e-13,1.3e-13,2e-15]]
Z_min=np.amin(Z)
Z_max=np.amax(Z)
norm = colors.LogNorm(vmin=1e-15,vmax=(Z_max),clip=False)
ax.plot_surface(X,Y,np.transpose(np.log10(Z)),norm=norm,cmap='rainbow')
A:
Edit: to solve your problem you are taking the log of the data then you are taking it again when calculating the norm, simply remove the norm and apply vmin and vmax directly to the drawing function
ax.plot_surface(X, Y, np.transpose(np.log10(Z)), cmap='rainbow',vmin=np.log10(1e-15),vmax=np.log10(Z_max))
you can use the facecolor argument of plot_surface to define color for each face independent of z, here's a simplified example
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
x = np.linspace(0,10,100)
y = np.linspace(0,10,100)
x,y = np.meshgrid(x,y)
z = np.sin(x+y)
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
cmap = matplotlib.cm.get_cmap('rainbow')
def rescale_0_to_1(item):
max_z = np.amax(item)
min_z = np.amin(item)
return (item - min_z)/(max_z-min_z)
rgba = cmap(rescale_0_to_1(z)) # some values of z to calculate color with
real_z = np.log(z+1) # real values of z to draw
surf = ax.plot_surface(x, y, real_z, cmap='rainbow', facecolors=rgba)
plt.show()
you can modify it to calculate colors based on x or y or something completely unrelated.
A:
Just an example of the logarithmic colors and logarithmic data:
#!/usr/bin/env ipython
import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt
import matplotlib.colors as colors
# ------------------
X=np.arange(0,401,1);nx= np.size(X)
Y=np.arange(40,200,1);ny = np.size(Y)
X,Y=np.meshgrid(X,Y)
Z = 10000*np.random.random((ny,nx))
Z=np.array(Z)
# ------------------------------------------------------------
Z_min=np.amin(Z)
Z_max=np.amax(Z)
# ------------------------------------------------------------
norm = colors.LogNorm(vmin=np.nanmin(Z),vmax=np.nanmax(Z),clip=False)
# ------------------------------------------------------------
fig = plt.figure(figsize=(15,5));axs = [fig.add_subplot(131),fig.add_subplot(132),fig.add_subplot(133)]
p0 = axs[0].pcolormesh(X,Y,np.log10(Z),cmap='rainbow',norm=norm);plt.colorbar(p0,ax=axs[0]);
axs[0].set_title('Original method: NOT TO DO!')
p1 = axs[1].pcolormesh(X,Y,Z,cmap='rainbow',norm=norm);plt.colorbar(p1,ax=axs[1])
axs[1].set_title('Normalized colorbar, original data')
p2 = axs[2].pcolormesh(X,Y,np.log10(Z),cmap='rainbow');plt.colorbar(p2,ax=axs[2])
axs[2].set_title('Logarithmic data, original colormap')
plt.savefig('test.png',bbox_inches='tight')
# --------------------------------------------------------------
So the result is like this:
In the first case, we have used logarithmic colormap and also taken the logarithm of the data, so the colorbar does not work anymore as the values on the map are small and we have used large limits for the colorbar.
In the middle image, we use the normalized colorbar or logarithmic colorbar so that it is quite natively understood what is on the image and what are the values. The third case is when we take the logarithm from the data and the colorbar is just showing the power of the 10th we have to use in order to interpret the coloured value on the plot.
So, in the end, I would suggest the middle method: use the logarithmic colorbar and original data.
|
matplotlib logarithmic colormap for logarithmic surface plot
|
I'm using python to create a 3D surface map, I have an array of data I'm trying to plot as a 3D surface, the issue is that I have logged the Z axis (necessary to show peaks in data) which means the default colormap doesn't work (displays one continous color). I've tried using the LogNorm to normalise the colormap but again this produces one continous color. I'm not sure whether I should be using the logged values to normalise the map, but if i do this the max is negative and produces an error?
fig=plt.figure(figsize=(10,10))
ax=plt.axes(projection='3d')
def log_tick_formatter(val, pos=None):
return "{:.2e}".format(10**val)
ax.zaxis.set_major_formatter(mticker.FuncFormatter(log_tick_formatter))
X=np.arange(0,2,1)
Y=np.arange(0,3,1)
X,Y=np.meshgrid(X,Y)
Z=[[1.2e-11,1.3e-11,-1.8e-11],[6e-13,1.3e-13,2e-15]]
Z_min=np.amin(Z)
Z_max=np.amax(Z)
norm = colors.LogNorm(vmin=1e-15,vmax=(Z_max),clip=False)
ax.plot_surface(X,Y,np.transpose(np.log10(Z)),norm=norm,cmap='rainbow')
|
[
"Edit: to solve your problem you are taking the log of the data then you are taking it again when calculating the norm, simply remove the norm and apply vmin and vmax directly to the drawing function\nax.plot_surface(X, Y, np.transpose(np.log10(Z)), cmap='rainbow',vmin=np.log10(1e-15),vmax=np.log10(Z_max))\n\nyou can use the facecolor argument of plot_surface to define color for each face independent of z, here's a simplified example\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nx = np.linspace(0,10,100)\ny = np.linspace(0,10,100)\n\nx,y = np.meshgrid(x,y)\nz = np.sin(x+y)\n\nfig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"})\n\ncmap = matplotlib.cm.get_cmap('rainbow')\n\ndef rescale_0_to_1(item):\n max_z = np.amax(item)\n min_z = np.amin(item)\n return (item - min_z)/(max_z-min_z)\n\nrgba = cmap(rescale_0_to_1(z)) # some values of z to calculate color with\n\nreal_z = np.log(z+1) # real values of z to draw\n\nsurf = ax.plot_surface(x, y, real_z, cmap='rainbow', facecolors=rgba)\nplt.show()\n\nyou can modify it to calculate colors based on x or y or something completely unrelated.\n\n",
"Just an example of the logarithmic colors and logarithmic data:\n#!/usr/bin/env ipython\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pylab as plt\nimport matplotlib.colors as colors\n# ------------------\nX=np.arange(0,401,1);nx= np.size(X)\nY=np.arange(40,200,1);ny = np.size(Y)\nX,Y=np.meshgrid(X,Y)\nZ = 10000*np.random.random((ny,nx))\nZ=np.array(Z)\n# ------------------------------------------------------------ \nZ_min=np.amin(Z)\nZ_max=np.amax(Z)\n# ------------------------------------------------------------\nnorm = colors.LogNorm(vmin=np.nanmin(Z),vmax=np.nanmax(Z),clip=False)\n# ------------------------------------------------------------\nfig = plt.figure(figsize=(15,5));axs = [fig.add_subplot(131),fig.add_subplot(132),fig.add_subplot(133)]\np0 = axs[0].pcolormesh(X,Y,np.log10(Z),cmap='rainbow',norm=norm);plt.colorbar(p0,ax=axs[0]);\naxs[0].set_title('Original method: NOT TO DO!')\np1 = axs[1].pcolormesh(X,Y,Z,cmap='rainbow',norm=norm);plt.colorbar(p1,ax=axs[1])\naxs[1].set_title('Normalized colorbar, original data')\np2 = axs[2].pcolormesh(X,Y,np.log10(Z),cmap='rainbow');plt.colorbar(p2,ax=axs[2])\naxs[2].set_title('Logarithmic data, original colormap')\nplt.savefig('test.png',bbox_inches='tight') \n# --------------------------------------------------------------\n\nSo the result is like this:\nIn the first case, we have used logarithmic colormap and also taken the logarithm of the data, so the colorbar does not work anymore as the values on the map are small and we have used large limits for the colorbar.\nIn the middle image, we use the normalized colorbar or logarithmic colorbar so that it is quite natively understood what is on the image and what are the values. The third case is when we take the logarithm from the data and the colorbar is just showing the power of the 10th we have to use in order to interpret the coloured value on the plot.\nSo, in the end, I would suggest the middle method: use the logarithmic colorbar and original data.\n"
] |
[
2,
2
] |
[] |
[] |
[
"matplotlib",
"numpy",
"python"
] |
stackoverflow_0074571588_matplotlib_numpy_python.txt
|
Q:
How to create a 3D image with series of 2D Image
I have series of 2D tiff images of a sample, I want to create or reproduce 3D image/volume using those 2d image for 3D visualization.
I found this link Reconstructing 3D image from 2D image have similar question but It discussed about CT reconstruction using backprojection algorithm. But I already have 2D view of sample in image form.
I want to know how can I reproduce 3D image from those 2D slices(Tiff image) using python or Matlab.
A:
I wanna check that this is what you're looking for before I go on a long explanation of something that could be irrelevant.
I have a series of 2d images of a tumor. I'm constructing a 3d shell from the image slices and creating a .ply file from that shell.
2D slices
3D Reconstruction
Is this the sort of thing that you're looking for?
Edit:
I downloaded the dataset and ran it through the program.
I set the resolution of the image to 100x100 to reduce the number of points in the .ply file. You can increase it or decrease it as you like.
Program for creating the .ply file
import cv2
import math
import numpy as np
import os
# creates a point cloud file (.ply) from numpy array
def createPointCloud(filename, arr):
# open file and write boilerplate header
file = open(filename, 'w');
file.write("ply\n");
file.write("format ascii 1.0\n");
# count number of vertices
num_verts = arr.shape[0];
file.write("element vertex " + str(num_verts) + "\n");
file.write("property float32 x\n");
file.write("property float32 y\n");
file.write("property float32 z\n");
file.write("end_header\n");
# write points
point_count = 0;
for point in arr:
# progress check
point_count += 1;
if point_count % 1000 == 0:
print("Point: " + str(point_count) + " of " + str(len(arr)));
# create file string
out_str = "";
for axis in point:
out_str += str(axis) + " ";
out_str = out_str[:-1]; # dump the extra space
out_str += "\n";
file.write(out_str);
file.close();
# extracts points from mask and adds to list
def addPoints(mask, points_list, depth):
mask_points = np.where(mask == 255);
for ind in range(len(mask_points[0])):
# get point
x = mask_points[1][ind];
y = mask_points[0][ind];
point = [x,y,depth];
points_list.append(point);
def main():
# tweakables
slice_thickness = .2; # distance between slices
xy_scale = 1; # rescale of xy distance
# load images
folder = "images/";
files = os.listdir(folder);
images = [];
for file in files:
if file[-4:] == ".tif":
img = cv2.imread(folder + file, cv2.IMREAD_GRAYSCALE);
img = cv2.resize(img, (100, 100)); # change here for more or less resolution
images.append(img);
# keep a blank mask
blank_mask = np.zeros_like(images[0], np.uint8);
# create masks
masks = [];
masks.append(blank_mask);
for image in images:
# mask
mask = cv2.inRange(image, 0, 100);
# show
cv2.imshow("Mask", mask);
cv2.waitKey(1);
masks.append(mask);
masks.append(blank_mask);
cv2.destroyAllWindows();
# go through and get points
depth = 0;
points = [];
for index in range(1,len(masks)-1):
# progress check
print("Index: " + str(index) + " of " + str(len(masks)));
# get three masks
prev = masks[index - 1];
curr = masks[index];
after = masks[index + 1];
# do a slice on previous
prev_mask = np.zeros_like(curr);
prev_mask[prev == 0] = curr[prev == 0];
addPoints(prev_mask, points, depth);
# # do a slice on after
next_mask = np.zeros_like(curr);
next_mask[after == 0] = curr[after == 0];
addPoints(next_mask, points, depth);
# get contour points (_, contours) in OpenCV 2.* or 4.*
_, contours, _ = cv2.findContours(curr, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE);
for con in contours:
for point in con:
p = point[0]; # contours have an extra layer of brackets
points.append([p[0], p[1], depth]);
# increment depth
depth += slice_thickness;
# rescale x,y points
for ind in range(len(points)):
# unpack
x,y,z = points[ind];
# scale
x *= xy_scale;
y *= xy_scale;
points[ind] = [x,y,z];
# convert points to numpy and dump duplicates
points = np.array(points).astype(np.float32);
points = np.unique(points.reshape(-1, points.shape[-1]), axis=0);
print(points.shape);
# save to point cloud file
createPointCloud("test.ply", points);
if __name__ == "__main__":
main();
A:
Another option is to apply open-source library MeshLib, which can be called both from C++ and python code.
Assuming we have bunch of slices like following:
On Windows, the simplest way to install it in python 3.10 is
py -3.10 -m pip install --upgrade meshlib
And the code for constructing 3D object from a series of images will look like
import meshlib.mrmeshpy as mr
settings = mr.LoadingTiffSettings()
# load images from specified directory
settings.dir="C:/slices"
# specifiy size of 3D image element
settings.voxelSize=mr.Vector3f(1,1,5)
#create voxel object from the series of images
volume=mr.loadTiffDir(settings)
#define ISO value to build surface
iso=127.0
#convert voxel object to mesh
mesh=mr.gridToMesh(volume.value(), iso)
#save mesh to .stl file
mr.saveMesh(mesh.value(), mr.Path("C:/slices/mesh.stl"))
Finally, result looks like
|
How to create a 3D image with series of 2D Image
|
I have series of 2D tiff images of a sample, I want to create or reproduce 3D image/volume using those 2d image for 3D visualization.
I found this link Reconstructing 3D image from 2D image have similar question but It discussed about CT reconstruction using backprojection algorithm. But I already have 2D view of sample in image form.
I want to know how can I reproduce 3D image from those 2D slices(Tiff image) using python or Matlab.
|
[
"I wanna check that this is what you're looking for before I go on a long explanation of something that could be irrelevant.\nI have a series of 2d images of a tumor. I'm constructing a 3d shell from the image slices and creating a .ply file from that shell.\n2D slices\n\n3D Reconstruction\n\nIs this the sort of thing that you're looking for?\nEdit:\nI downloaded the dataset and ran it through the program.\n\nI set the resolution of the image to 100x100 to reduce the number of points in the .ply file. You can increase it or decrease it as you like.\nProgram for creating the .ply file\nimport cv2\nimport math\nimport numpy as np\nimport os\n\n# creates a point cloud file (.ply) from numpy array\ndef createPointCloud(filename, arr):\n # open file and write boilerplate header\n file = open(filename, 'w');\n file.write(\"ply\\n\");\n file.write(\"format ascii 1.0\\n\");\n\n # count number of vertices\n num_verts = arr.shape[0];\n file.write(\"element vertex \" + str(num_verts) + \"\\n\");\n file.write(\"property float32 x\\n\");\n file.write(\"property float32 y\\n\");\n file.write(\"property float32 z\\n\");\n file.write(\"end_header\\n\");\n\n # write points\n point_count = 0;\n for point in arr:\n # progress check\n point_count += 1;\n if point_count % 1000 == 0:\n print(\"Point: \" + str(point_count) + \" of \" + str(len(arr)));\n\n # create file string\n out_str = \"\";\n for axis in point:\n out_str += str(axis) + \" \";\n out_str = out_str[:-1]; # dump the extra space\n out_str += \"\\n\";\n file.write(out_str);\n file.close();\n\n\n# extracts points from mask and adds to list\ndef addPoints(mask, points_list, depth):\n mask_points = np.where(mask == 255);\n for ind in range(len(mask_points[0])):\n # get point\n x = mask_points[1][ind];\n y = mask_points[0][ind];\n point = [x,y,depth];\n points_list.append(point);\n\ndef main():\n # tweakables\n slice_thickness = .2; # distance between slices\n xy_scale = 1; # rescale of xy distance\n\n # load images\n folder = \"images/\";\n files = os.listdir(folder);\n images = [];\n for file in files:\n if file[-4:] == \".tif\":\n img = cv2.imread(folder + file, cv2.IMREAD_GRAYSCALE);\n img = cv2.resize(img, (100, 100)); # change here for more or less resolution\n images.append(img);\n\n # keep a blank mask\n blank_mask = np.zeros_like(images[0], np.uint8);\n\n # create masks\n masks = [];\n masks.append(blank_mask);\n for image in images:\n # mask\n mask = cv2.inRange(image, 0, 100);\n\n # show\n cv2.imshow(\"Mask\", mask);\n cv2.waitKey(1);\n masks.append(mask);\n masks.append(blank_mask);\n cv2.destroyAllWindows();\n\n # go through and get points\n depth = 0;\n points = [];\n for index in range(1,len(masks)-1):\n # progress check\n print(\"Index: \" + str(index) + \" of \" + str(len(masks)));\n\n # get three masks\n prev = masks[index - 1];\n curr = masks[index];\n after = masks[index + 1];\n\n # do a slice on previous\n prev_mask = np.zeros_like(curr);\n prev_mask[prev == 0] = curr[prev == 0];\n addPoints(prev_mask, points, depth);\n\n # # do a slice on after\n next_mask = np.zeros_like(curr);\n next_mask[after == 0] = curr[after == 0];\n addPoints(next_mask, points, depth);\n\n # get contour points (_, contours) in OpenCV 2.* or 4.*\n _, contours, _ = cv2.findContours(curr, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE);\n for con in contours:\n for point in con:\n p = point[0]; # contours have an extra layer of brackets\n points.append([p[0], p[1], depth]);\n\n # increment depth\n depth += slice_thickness;\n\n # rescale x,y points\n for ind in range(len(points)):\n # unpack\n x,y,z = points[ind];\n\n # scale\n x *= xy_scale;\n y *= xy_scale;\n points[ind] = [x,y,z];\n\n # convert points to numpy and dump duplicates\n points = np.array(points).astype(np.float32);\n points = np.unique(points.reshape(-1, points.shape[-1]), axis=0);\n print(points.shape);\n\n # save to point cloud file\n createPointCloud(\"test.ply\", points);\n\nif __name__ == \"__main__\":\n main();\n\n",
"Another option is to apply open-source library MeshLib, which can be called both from C++ and python code.\nAssuming we have bunch of slices like following:\n\nOn Windows, the simplest way to install it in python 3.10 is\npy -3.10 -m pip install --upgrade meshlib\n\nAnd the code for constructing 3D object from a series of images will look like\nimport meshlib.mrmeshpy as mr\nsettings = mr.LoadingTiffSettings()\n# load images from specified directory\nsettings.dir=\"C:/slices\"\n# specifiy size of 3D image element\nsettings.voxelSize=mr.Vector3f(1,1,5)\n#create voxel object from the series of images\nvolume=mr.loadTiffDir(settings)\n#define ISO value to build surface\niso=127.0\n#convert voxel object to mesh\nmesh=mr.gridToMesh(volume.value(), iso)\n#save mesh to .stl file\nmr.saveMesh(mesh.value(), mr.Path(\"C:/slices/mesh.stl\"))\n\nFinally, result looks like\n\n"
] |
[
6,
1
] |
[] |
[] |
[
"3d_reconstruction",
"image_processing",
"python"
] |
stackoverflow_0066699525_3d_reconstruction_image_processing_python.txt
|
Q:
TypeError: Cannot join tz-naive with tz-aware DatetimeIndex
all!
I am trying to generate results of this repo
https://github.com/ArnaudBu/stock-returns-prediction
for stocks price prediction based on financial analysis. Running the very first step
1_get_data.py
I come across an error: TypeError: Cannot join tz-naive with tz-aware DatetimeIndex
The code is
# -*- coding: utf-8 -*-
from yfinance import Ticker
import pandas as pd
from yahoofinancials import YahooFinancials
import requests
from tqdm import tqdm
import time
import pickle
# with open('tmp.pickle', 'rb') as f:
# statements, tickers_done = pickle.load(f)
# Download function
def _download_one(ticker, start=None, end=None,
auto_adjust=False, back_adjust=False,
actions=False, period="max", interval="1d",
prepost=False, proxy=None, rounding=False):
return Ticker(ticker).history(period=period, interval=interval,
start=start, end=end, prepost=prepost,
actions=actions, auto_adjust=auto_adjust,
back_adjust=back_adjust, proxy=proxy,
rounding=rounding, many=True)
# Modify project and reference index according to your needs
tickers_all = []
# for project in ["sp500", "nyse", "nasdaq"]:
for project in ["nasdaq"]:
print(project)
ref_index = ["^GSPC", "^IXIC"]
# Load tickers
companies = pd.read_csv(f"data/{project}/{project}.csv", sep=",")
# companies = companies.drop(companies.index[companies['Symbol'].index[companies['Symbol'].isnull()][0]]) # the row with Nan value
tickers = companies.Symbol.tolist()
tickers = [a for a in tickers if a not in tickers_all and "^" not in a and r"/" not in a]
tickers_all += tickers
# Download prices
full_data = {}
for ticker in tqdm(tickers + ref_index):
tckr = _download_one(ticker,
period="7y",
actions=True)
full_data[ticker] = tckr
ohlc = pd.concat(full_data.values(), axis=1,
keys=full_data.keys())
ohlc.columns = ohlc.columns.swaplevel(0, 1)
ohlc.sort_index(level=0, axis=1, inplace=True)
prices = ohlc["Adj Close"]
dividends = ohlc["Dividends"]
prices.to_csv(f"data/{project}/prices_daily.csv")
dividends.to_csv(f"data/{project}/dividends.csv")
statements = {}
tickers_done = []
for ticker in tqdm(tickers):
# Get statements
if ticker in tickers_done:
continue
yahoo_financials = YahooFinancials(ticker)
stmts_codes = ['income', 'cash', 'balance']
all_statement_data = yahoo_financials.get_financial_stmts('annual',
stmts_codes)
# build statements dictionnary
for a in all_statement_data.keys():
if a not in statements:
statements[a] = list()
for b in all_statement_data[a]:
try:
for result in all_statement_data[a][b]:
extracted_date = list(result)[0]
dataframe_row = list(result.values())[0]
dataframe_row['date'] = extracted_date
dataframe_row['symbol'] = b
statements[a].append(dataframe_row)
except Exception as e:
print("Error on " + ticker + " : " + a)
tickers_done.append(ticker)
with open('tmp.pickle', 'wb') as f:
pickle.dump([statements, tickers_done], f)
# save dataframes
for a in all_statement_data.keys():
df = pd.DataFrame(statements[a]).set_index('date')
df.to_csv(f"data/{project}/{a}.csv")
# Donwload shares
shares = []
tickers_done = []
for ticker in tqdm(tickers):
if ticker in tickers_done:
continue
d = requests.get(f"https://query1.finance.yahoo.com/ws/fundamentals-timeseries/v1/finance/timeseries/{ticker}?symbol={ticker}&padTimeSeries=true&type=annualPreferredSharesNumber,annualOrdinarySharesNumber&merge=false&period1=0&period2=2013490868")
if not d.ok:
time.sleep(300)
d = requests.get(f"https://query1.finance.yahoo.com/ws/fundamentals-timeseries/v1/finance/timeseries/{ticker}?symbol={ticker}&padTimeSeries=true&type=annualPreferredSharesNumber,annualOrdinarySharesNumber&merge=false&period1=0&period2=2013490868")
ctn = d.json()['timeseries']['result']
dct = dict()
for n in ctn:
type = n['meta']['type'][0]
dct[type] = dict()
if type in n:
for o in n[type]:
if o is not None:
dct[type][o['asOfDate']] = o['reportedValue']['raw']
df = pd.DataFrame.from_dict(dct)
df['symbol'] = ticker
shares.append(df)
tickers_done.append(ticker)
time.sleep(1)
# save dataframe
df = pd.concat(shares)
df['date'] = df.index
df.to_csv(f"data/{project}/shares.csv", index=False)
# https://query1.finance.yahoo.com/ws/fundamentals-timeseries/v1/finance/timeseries/MSFT?symbol=MSFT&padTimeSeries=true&type=annualTreasurySharesNumber,trailingTreasurySharesNumber,annualPreferredSharesNumber,trailingPreferredSharesNumber,annualOrdinarySharesNumber,trailingOrdinarySharesNumber,annualShareIssued,trailingShareIssued,annualNetDebt,trailingNetDebt,annualTotalDebt,trailingTotalDebt,annualTangibleBookValue,trailingTangibleBookValue,annualInvestedCapital,trailingInvestedCapital,annualWorkingCapital,trailingWorkingCapital,annualNetTangibleAssets,trailingNetTangibleAssets,annualCapitalLeaseObligations,trailingCapitalLeaseObligations,annualCommonStockEquity,trailingCommonStockEquity,annualPreferredStockEquity,trailingPreferredStockEquity,annualTotalCapitalization,trailingTotalCapitalization,annualTotalEquityGrossMinorityInterest,trailingTotalEquityGrossMinorityInterest,annualMinorityInterest,trailingMinorityInterest,annualStockholdersEquity,trailingStockholdersEquity,annualOtherEquityInterest,trailingOtherEquityInterest,annualGainsLossesNotAffectingRetainedEarnings,trailingGainsLossesNotAffectingRetainedEarnings,annualOtherEquityAdjustments,trailingOtherEquityAdjustments,annualFixedAssetsRevaluationReserve,trailingFixedAssetsRevaluationReserve,annualForeignCurrencyTranslationAdjustments,trailingForeignCurrencyTranslationAdjustments,annualMinimumPensionLiabilities,trailingMinimumPensionLiabilities,annualUnrealizedGainLoss,trailingUnrealizedGainLoss,annualTreasuryStock,trailingTreasuryStock,annualRetainedEarnings,trailingRetainedEarnings,annualAdditionalPaidInCapital,trailingAdditionalPaidInCapital,annualCapitalStock,trailingCapitalStock,annualOtherCapitalStock,trailingOtherCapitalStock,annualCommonStock,trailingCommonStock,annualPreferredStock,trailingPreferredStock,annualTotalPartnershipCapital,trailingTotalPartnershipCapital,annualGeneralPartnershipCapital,trailingGeneralPartnershipCapital,annualLimitedPartnershipCapital,trailingLimitedPartnershipCapital,annualTotalLiabilitiesNetMinorityInterest,trailingTotalLiabilitiesNetMinorityInterest,annualTotalNonCurrentLiabilitiesNetMinorityInterest,trailingTotalNonCurrentLiabilitiesNetMinorityInterest,annualOtherNonCurrentLiabilities,trailingOtherNonCurrentLiabilities,annualLiabilitiesHeldforSaleNonCurrent,trailingLiabilitiesHeldforSaleNonCurrent,annualRestrictedCommonStock,trailingRestrictedCommonStock,annualPreferredSecuritiesOutsideStockEquity,trailingPreferredSecuritiesOutsideStockEquity,annualDerivativeProductLiabilities,trailingDerivativeProductLiabilities,annualEmployeeBenefits,trailingEmployeeBenefits,annualNonCurrentPensionAndOtherPostretirementBenefitPlans,trailingNonCurrentPensionAndOtherPostretirementBenefitPlans,annualNonCurrentAccruedExpenses,trailingNonCurrentAccruedExpenses,annualDuetoRelatedPartiesNonCurrent,trailingDuetoRelatedPartiesNonCurrent,annualTradeandOtherPayablesNonCurrent,trailingTradeandOtherPayablesNonCurrent,annualNonCurrentDeferredLiabilities,trailingNonCurrentDeferredLiabilities,annualNonCurrentDeferredRevenue,trailingNonCurrentDeferredRevenue,annualNonCurrentDeferredTaxesLiabilities,trailingNonCurrentDeferredTaxesLiabilities,annualLongTermDebtAndCapitalLeaseObligation,trailingLongTermDebtAndCapitalLeaseObligation,annualLongTermCapitalLeaseObligation,trailingLongTermCapitalLeaseObligation,annualLongTermDebt,trailingLongTermDebt,annualLongTermProvisions,trailingLongTermProvisions,annualCurrentLiabilities,trailingCurrentLiabilities,annualOtherCurrentLiabilities,trailingOtherCurrentLiabilities,annualCurrentDeferredLiabilities,trailingCurrentDeferredLiabilities,annualCurrentDeferredRevenue,trailingCurrentDeferredRevenue,annualCurrentDeferredTaxesLiabilities,trailingCurrentDeferredTaxesLiabilities,annualCurrentDebtAndCapitalLeaseObligation,trailingCurrentDebtAndCapitalLeaseObligation,annualCurrentCapitalLeaseObligation,trailingCurrentCapitalLeaseObligation,annualCurrentDebt,trailingCurrentDebt,annualOtherCurrentBorrowings,trailingOtherCurrentBorrowings,annualLineOfCredit,trailingLineOfCredit,annualCommercialPaper,trailingCommercialPaper,annualCurrentNotesPayable,trailingCurrentNotesPayable,annualPensionandOtherPostRetirementBenefitPlansCurrent,trailingPensionandOtherPostRetirementBenefitPlansCurrent,annualCurrentProvisions,trailingCurrentProvisions,annualPayablesAndAccruedExpenses,trailingPayablesAndAccruedExpenses,annualCurrentAccruedExpenses,trailingCurrentAccruedExpenses,annualInterestPayable,trailingInterestPayable,annualPayables,trailingPayables,annualOtherPayable,trailingOtherPayable,annualDuetoRelatedPartiesCurrent,trailingDuetoRelatedPartiesCurrent,annualDividendsPayable,trailingDividendsPayable,annualTotalTaxPayable,trailingTotalTaxPayable,annualIncomeTaxPayable,trailingIncomeTaxPayable,annualAccountsPayable,trailingAccountsPayable,annualTotalAssets,trailingTotalAssets,annualTotalNonCurrentAssets,trailingTotalNonCurrentAssets,annualOtherNonCurrentAssets,trailingOtherNonCurrentAssets,annualDefinedPensionBenefit,trailingDefinedPensionBenefit,annualNonCurrentPrepaidAssets,trailingNonCurrentPrepaidAssets,annualNonCurrentDeferredAssets,trailingNonCurrentDeferredAssets,annualNonCurrentDeferredTaxesAssets,trailingNonCurrentDeferredTaxesAssets,annualDuefromRelatedPartiesNonCurrent,trailingDuefromRelatedPartiesNonCurrent,annualNonCurrentNoteReceivables,trailingNonCurrentNoteReceivables,annualNonCurrentAccountsReceivable,trailingNonCurrentAccountsReceivable,annualFinancialAssets,trailingFinancialAssets,annualInvestmentsAndAdvances,trailingInvestmentsAndAdvances,annualOtherInvestments,trailingOtherInvestments,annualInvestmentinFinancialAssets,trailingInvestmentinFinancialAssets,annualHeldToMaturitySecurities,trailingHeldToMaturitySecurities,annualAvailableForSaleSecurities,trailingAvailableForSaleSecurities,annualFinancialAssetsDesignatedasFairValueThroughProfitorLossTotal,trailingFinancialAssetsDesignatedasFairValueThroughProfitorLossTotal,annualTradingSecurities,trailingTradingSecurities,annualLongTermEquityInvestment,trailingLongTermEquityInvestment,annualInvestmentsinJointVenturesatCost,trailingInvestmentsinJointVenturesatCost,annualInvestmentsInOtherVenturesUnderEquityMethod,trailingInvestmentsInOtherVenturesUnderEquityMethod,annualInvestmentsinAssociatesatCost,trailingInvestmentsinAssociatesatCost,annualInvestmentsinSubsidiariesatCost,trailingInvestmentsinSubsidiariesatCost,annualInvestmentProperties,trailingInvestmentProperties,annualGoodwillAndOtherIntangibleAssets,trailingGoodwillAndOtherIntangibleAssets,annualOtherIntangibleAssets,trailingOtherIntangibleAssets,annualGoodwill,trailingGoodwill,annualNetPPE,trailingNetPPE,annualAccumulatedDepreciation,trailingAccumulatedDepreciation,annualGrossPPE,trailingGrossPPE,annualLeases,trailingLeases,annualConstructionInProgress,trailingConstructionInProgress,annualOtherProperties,trailingOtherProperties,annualMachineryFurnitureEquipment,trailingMachineryFurnitureEquipment,annualBuildingsAndImprovements,trailingBuildingsAndImprovements,annualLandAndImprovements,trailingLandAndImprovements,annualProperties,trailingProperties,annualCurrentAssets,trailingCurrentAssets,annualOtherCurrentAssets,trailingOtherCurrentAssets,annualHedgingAssetsCurrent,trailingHedgingAssetsCurrent,annualAssetsHeldForSaleCurrent,trailingAssetsHeldForSaleCurrent,annualCurrentDeferredAssets,trailingCurrentDeferredAssets,annualCurrentDeferredTaxesAssets,trailingCurrentDeferredTaxesAssets,annualRestrictedCash,trailingRestrictedCash,annualPrepaidAssets,trailingPrepaidAssets,annualInventory,trailingInventory,annualInventoriesAdjustmentsAllowances,trailingInventoriesAdjustmentsAllowances,annualOtherInventories,trailingOtherInventories,annualFinishedGoods,trailingFinishedGoods,annualWorkInProcess,trailingWorkInProcess,annualRawMaterials,trailingRawMaterials,annualReceivables,trailingReceivables,annualReceivablesAdjustmentsAllowances,trailingReceivablesAdjustmentsAllowances,annualOtherReceivables,trailingOtherReceivables,annualDuefromRelatedPartiesCurrent,trailingDuefromRelatedPartiesCurrent,annualTaxesReceivable,trailingTaxesReceivable,annualAccruedInterestReceivable,trailingAccruedInterestReceivable,annualNotesReceivable,trailingNotesReceivable,annualLoansReceivable,trailingLoansReceivable,annualAccountsReceivable,trailingAccountsReceivable,annualAllowanceForDoubtfulAccountsReceivable,trailingAllowanceForDoubtfulAccountsReceivable,annualGrossAccountsReceivable,trailingGrossAccountsReceivable,annualCashCashEquivalentsAndShortTermInvestments,trailingCashCashEquivalentsAndShortTermInvestments,annualOtherShortTermInvestments,trailingOtherShortTermInvestments,annualCashAndCashEquivalents,trailingCashAndCashEquivalents,annualCashEquivalents,trailingCashEquivalents,annualCashFinancial,trailingCashFinancial&merge=false&period1=493590046&period2=1613490868
# https://query1.finance.yahoo.com/v8/finance/chart/MSFT?symbol=MSFT&period1=1550725200&period2=1613491890&useYfid=true&interval=1d&events=div
# https://query1.finance.yahoo.com/v10/finance/quoteSummary/MSFT?formatted=true&crumb=2M1BZy1YB7f&lang=en-US®ion=US&modules=incomeStatementHistory,cashflowStatementHistory,balanceSheetHistory,incomeStatementHistoryQuarterly,cashflowStatementHistoryQuarterly,balanceSheetHistoryQuarterly&corsDomain=finance.yahoo.com
The screenshot of the error is:
It refers to the line 51 of the above code. I have tried multiple times, and check some related questions/answers here as well but have not any satisfied answer. There is another similar question but it has not any proper answer.
Any help in this regard would be highly appreciated.
Thanks in anticipation!
A:
I have not managed to reproduce your dataframes, but generally this type of error is easily removed by doing df.tz_localize(None).
This will convert a tz-aware df to a tz-naive df.
so try applying this to the full_data dataframe of yours.
A:
all!
I just found that the issue was related to the full_data[ticker] in line 49. Once I checked its type and data inside, I found it as dataframe and as:
The issue was with the time under the index column Date. So, to remove those I used this line full_data[ticker] = full_data[ticker].tz_localize(None) of code under the line 49 full_data[ticker] = tckr. And then I checked the full_data[ticker] so got this:
The time under the Date are disappeared hence solving the issue. Thanks to @VasP whose suggestion helped me to crack this issue.
So, here is the working code now:
# -*- coding: utf-8 -*-
from yfinance import Ticker
import pandas as pd
from yahoofinancials import YahooFinancials
import requests
from tqdm import tqdm
import time
import pickle
# with open('tmp.pickle', 'rb') as f:
# statements, tickers_done = pickle.load(f)
# Download function
def _download_one(ticker, start=None, end=None,
auto_adjust=False, back_adjust=False,
actions=False, period="max", interval="1d",
prepost=False, proxy=None, rounding=False):
return Ticker(ticker).history(period=period, interval=interval,
start=start, end=end, prepost=prepost,
actions=actions, auto_adjust=auto_adjust,
back_adjust=back_adjust, proxy=proxy,
rounding=rounding, many=True)
# Modify project and reference index according to your needs
tickers_all = []
# for project in ["sp500", "nyse", "nasdaq"]:
for project in ["nasdaq"]:
print(project)
ref_index = ["^GSPC", "^IXIC"]
# Load tickers
companies = pd.read_csv(f"data/{project}/{project}.csv", sep=",")
# companies = companies.drop(companies.index[companies['Symbol'].index[companies['Symbol'].isnull()][0]]) # the row with Nan value
tickers = companies.Symbol.tolist()
tickers = [a for a in tickers if a not in tickers_all and "^" not in a and r"/" not in a]
tickers_all += tickers
# Download prices
full_data = {}
for ticker in tqdm(tickers + ref_index):
tckr = _download_one(ticker,
period="7y",
actions=True)
full_data[ticker] = tckr
full_data[ticker] = full_data[ticker].tz_localize(None) #Added now
ohlc = pd.concat(full_data.values(), axis=1,
keys=full_data.keys())
ohlc.columns = ohlc.columns.swaplevel(0, 1)
ohlc.sort_index(level=0, axis=1, inplace=True)
prices = ohlc["Adj Close"]
dividends = ohlc["Dividends"]
prices.to_csv(f"data/{project}/prices_daily.csv")
dividends.to_csv(f"data/{project}/dividends.csv")
statements = {}
tickers_done = []
for ticker in tqdm(tickers):
# Get statements
if ticker in tickers_done:
continue
yahoo_financials = YahooFinancials(ticker)
stmts_codes = ['income', 'cash', 'balance']
all_statement_data = yahoo_financials.get_financial_stmts('annual',
stmts_codes)
# build statements dictionnary
for a in all_statement_data.keys():
if a not in statements:
statements[a] = list()
for b in all_statement_data[a]:
try:
for result in all_statement_data[a][b]:
extracted_date = list(result)[0]
dataframe_row = list(result.values())[0]
dataframe_row['date'] = extracted_date
dataframe_row['symbol'] = b
statements[a].append(dataframe_row)
except Exception as e:
print("Error on " + ticker + " : " + a)
tickers_done.append(ticker)
with open('tmp.pickle', 'wb') as f:
pickle.dump([statements, tickers_done], f)
# save dataframes
for a in all_statement_data.keys():
df = pd.DataFrame(statements[a]).set_index('date')
df.to_csv(f"data/{project}/{a}.csv")
# Donwload shares
shares = []
tickers_done = []
for ticker in tqdm(tickers):
if ticker in tickers_done:
continue
d = requests.get(f"https://query1.finance.yahoo.com/ws/fundamentals-timeseries/v1/finance/timeseries/{ticker}?symbol={ticker}&padTimeSeries=true&type=annualPreferredSharesNumber,annualOrdinarySharesNumber&merge=false&period1=0&period2=2013490868")
if not d.ok:
time.sleep(300)
d = requests.get(f"https://query1.finance.yahoo.com/ws/fundamentals-timeseries/v1/finance/timeseries/{ticker}?symbol={ticker}&padTimeSeries=true&type=annualPreferredSharesNumber,annualOrdinarySharesNumber&merge=false&period1=0&period2=2013490868")
ctn = d.json()['timeseries']['result']
dct = dict()
for n in ctn:
type = n['meta']['type'][0]
dct[type] = dict()
if type in n:
for o in n[type]:
if o is not None:
dct[type][o['asOfDate']] = o['reportedValue']['raw']
df = pd.DataFrame.from_dict(dct)
df['symbol'] = ticker
shares.append(df)
tickers_done.append(ticker)
time.sleep(1)
# save dataframe
df = pd.concat(shares)
df['date'] = df.index
df.to_csv(f"data/{project}/shares.csv", index=False)
# https://query1.finance.yahoo.com/ws/fundamentals-timeseries/v1/finance/timeseries/MSFT?symbol=MSFT&padTimeSeries=true&type=annualTreasurySharesNumber,trailingTreasurySharesNumber,annualPreferredSharesNumber,trailingPreferredSharesNumber,annualOrdinarySharesNumber,trailingOrdinarySharesNumber,annualShareIssued,trailingShareIssued,annualNetDebt,trailingNetDebt,annualTotalDebt,trailingTotalDebt,annualTangibleBookValue,trailingTangibleBookValue,annualInvestedCapital,trailingInvestedCapital,annualWorkingCapital,trailingWorkingCapital,annualNetTangibleAssets,trailingNetTangibleAssets,annualCapitalLeaseObligations,trailingCapitalLeaseObligations,annualCommonStockEquity,trailingCommonStockEquity,annualPreferredStockEquity,trailingPreferredStockEquity,annualTotalCapitalization,trailingTotalCapitalization,annualTotalEquityGrossMinorityInterest,trailingTotalEquityGrossMinorityInterest,annualMinorityInterest,trailingMinorityInterest,annualStockholdersEquity,trailingStockholdersEquity,annualOtherEquityInterest,trailingOtherEquityInterest,annualGainsLossesNotAffectingRetainedEarnings,trailingGainsLossesNotAffectingRetainedEarnings,annualOtherEquityAdjustments,trailingOtherEquityAdjustments,annualFixedAssetsRevaluationReserve,trailingFixedAssetsRevaluationReserve,annualForeignCurrencyTranslationAdjustments,trailingForeignCurrencyTranslationAdjustments,annualMinimumPensionLiabilities,trailingMinimumPensionLiabilities,annualUnrealizedGainLoss,trailingUnrealizedGainLoss,annualTreasuryStock,trailingTreasuryStock,annualRetainedEarnings,trailingRetainedEarnings,annualAdditionalPaidInCapital,trailingAdditionalPaidInCapital,annualCapitalStock,trailingCapitalStock,annualOtherCapitalStock,trailingOtherCapitalStock,annualCommonStock,trailingCommonStock,annualPreferredStock,trailingPreferredStock,annualTotalPartnershipCapital,trailingTotalPartnershipCapital,annualGeneralPartnershipCapital,trailingGeneralPartnershipCapital,annualLimitedPartnershipCapital,trailingLimitedPartnershipCapital,annualTotalLiabilitiesNetMinorityInterest,trailingTotalLiabilitiesNetMinorityInterest,annualTotalNonCurrentLiabilitiesNetMinorityInterest,trailingTotalNonCurrentLiabilitiesNetMinorityInterest,annualOtherNonCurrentLiabilities,trailingOtherNonCurrentLiabilities,annualLiabilitiesHeldforSaleNonCurrent,trailingLiabilitiesHeldforSaleNonCurrent,annualRestrictedCommonStock,trailingRestrictedCommonStock,annualPreferredSecuritiesOutsideStockEquity,trailingPreferredSecuritiesOutsideStockEquity,annualDerivativeProductLiabilities,trailingDerivativeProductLiabilities,annualEmployeeBenefits,trailingEmployeeBenefits,annualNonCurrentPensionAndOtherPostretirementBenefitPlans,trailingNonCurrentPensionAndOtherPostretirementBenefitPlans,annualNonCurrentAccruedExpenses,trailingNonCurrentAccruedExpenses,annualDuetoRelatedPartiesNonCurrent,trailingDuetoRelatedPartiesNonCurrent,annualTradeandOtherPayablesNonCurrent,trailingTradeandOtherPayablesNonCurrent,annualNonCurrentDeferredLiabilities,trailingNonCurrentDeferredLiabilities,annualNonCurrentDeferredRevenue,trailingNonCurrentDeferredRevenue,annualNonCurrentDeferredTaxesLiabilities,trailingNonCurrentDeferredTaxesLiabilities,annualLongTermDebtAndCapitalLeaseObligation,trailingLongTermDebtAndCapitalLeaseObligation,annualLongTermCapitalLeaseObligation,trailingLongTermCapitalLeaseObligation,annualLongTermDebt,trailingLongTermDebt,annualLongTermProvisions,trailingLongTermProvisions,annualCurrentLiabilities,trailingCurrentLiabilities,annualOtherCurrentLiabilities,trailingOtherCurrentLiabilities,annualCurrentDeferredLiabilities,trailingCurrentDeferredLiabilities,annualCurrentDeferredRevenue,trailingCurrentDeferredRevenue,annualCurrentDeferredTaxesLiabilities,trailingCurrentDeferredTaxesLiabilities,annualCurrentDebtAndCapitalLeaseObligation,trailingCurrentDebtAndCapitalLeaseObligation,annualCurrentCapitalLeaseObligation,trailingCurrentCapitalLeaseObligation,annualCurrentDebt,trailingCurrentDebt,annualOtherCurrentBorrowings,trailingOtherCurrentBorrowings,annualLineOfCredit,trailingLineOfCredit,annualCommercialPaper,trailingCommercialPaper,annualCurrentNotesPayable,trailingCurrentNotesPayable,annualPensionandOtherPostRetirementBenefitPlansCurrent,trailingPensionandOtherPostRetirementBenefitPlansCurrent,annualCurrentProvisions,trailingCurrentProvisions,annualPayablesAndAccruedExpenses,trailingPayablesAndAccruedExpenses,annualCurrentAccruedExpenses,trailingCurrentAccruedExpenses,annualInterestPayable,trailingInterestPayable,annualPayables,trailingPayables,annualOtherPayable,trailingOtherPayable,annualDuetoRelatedPartiesCurrent,trailingDuetoRelatedPartiesCurrent,annualDividendsPayable,trailingDividendsPayable,annualTotalTaxPayable,trailingTotalTaxPayable,annualIncomeTaxPayable,trailingIncomeTaxPayable,annualAccountsPayable,trailingAccountsPayable,annualTotalAssets,trailingTotalAssets,annualTotalNonCurrentAssets,trailingTotalNonCurrentAssets,annualOtherNonCurrentAssets,trailingOtherNonCurrentAssets,annualDefinedPensionBenefit,trailingDefinedPensionBenefit,annualNonCurrentPrepaidAssets,trailingNonCurrentPrepaidAssets,annualNonCurrentDeferredAssets,trailingNonCurrentDeferredAssets,annualNonCurrentDeferredTaxesAssets,trailingNonCurrentDeferredTaxesAssets,annualDuefromRelatedPartiesNonCurrent,trailingDuefromRelatedPartiesNonCurrent,annualNonCurrentNoteReceivables,trailingNonCurrentNoteReceivables,annualNonCurrentAccountsReceivable,trailingNonCurrentAccountsReceivable,annualFinancialAssets,trailingFinancialAssets,annualInvestmentsAndAdvances,trailingInvestmentsAndAdvances,annualOtherInvestments,trailingOtherInvestments,annualInvestmentinFinancialAssets,trailingInvestmentinFinancialAssets,annualHeldToMaturitySecurities,trailingHeldToMaturitySecurities,annualAvailableForSaleSecurities,trailingAvailableForSaleSecurities,annualFinancialAssetsDesignatedasFairValueThroughProfitorLossTotal,trailingFinancialAssetsDesignatedasFairValueThroughProfitorLossTotal,annualTradingSecurities,trailingTradingSecurities,annualLongTermEquityInvestment,trailingLongTermEquityInvestment,annualInvestmentsinJointVenturesatCost,trailingInvestmentsinJointVenturesatCost,annualInvestmentsInOtherVenturesUnderEquityMethod,trailingInvestmentsInOtherVenturesUnderEquityMethod,annualInvestmentsinAssociatesatCost,trailingInvestmentsinAssociatesatCost,annualInvestmentsinSubsidiariesatCost,trailingInvestmentsinSubsidiariesatCost,annualInvestmentProperties,trailingInvestmentProperties,annualGoodwillAndOtherIntangibleAssets,trailingGoodwillAndOtherIntangibleAssets,annualOtherIntangibleAssets,trailingOtherIntangibleAssets,annualGoodwill,trailingGoodwill,annualNetPPE,trailingNetPPE,annualAccumulatedDepreciation,trailingAccumulatedDepreciation,annualGrossPPE,trailingGrossPPE,annualLeases,trailingLeases,annualConstructionInProgress,trailingConstructionInProgress,annualOtherProperties,trailingOtherProperties,annualMachineryFurnitureEquipment,trailingMachineryFurnitureEquipment,annualBuildingsAndImprovements,trailingBuildingsAndImprovements,annualLandAndImprovements,trailingLandAndImprovements,annualProperties,trailingProperties,annualCurrentAssets,trailingCurrentAssets,annualOtherCurrentAssets,trailingOtherCurrentAssets,annualHedgingAssetsCurrent,trailingHedgingAssetsCurrent,annualAssetsHeldForSaleCurrent,trailingAssetsHeldForSaleCurrent,annualCurrentDeferredAssets,trailingCurrentDeferredAssets,annualCurrentDeferredTaxesAssets,trailingCurrentDeferredTaxesAssets,annualRestrictedCash,trailingRestrictedCash,annualPrepaidAssets,trailingPrepaidAssets,annualInventory,trailingInventory,annualInventoriesAdjustmentsAllowances,trailingInventoriesAdjustmentsAllowances,annualOtherInventories,trailingOtherInventories,annualFinishedGoods,trailingFinishedGoods,annualWorkInProcess,trailingWorkInProcess,annualRawMaterials,trailingRawMaterials,annualReceivables,trailingReceivables,annualReceivablesAdjustmentsAllowances,trailingReceivablesAdjustmentsAllowances,annualOtherReceivables,trailingOtherReceivables,annualDuefromRelatedPartiesCurrent,trailingDuefromRelatedPartiesCurrent,annualTaxesReceivable,trailingTaxesReceivable,annualAccruedInterestReceivable,trailingAccruedInterestReceivable,annualNotesReceivable,trailingNotesReceivable,annualLoansReceivable,trailingLoansReceivable,annualAccountsReceivable,trailingAccountsReceivable,annualAllowanceForDoubtfulAccountsReceivable,trailingAllowanceForDoubtfulAccountsReceivable,annualGrossAccountsReceivable,trailingGrossAccountsReceivable,annualCashCashEquivalentsAndShortTermInvestments,trailingCashCashEquivalentsAndShortTermInvestments,annualOtherShortTermInvestments,trailingOtherShortTermInvestments,annualCashAndCashEquivalents,trailingCashAndCashEquivalents,annualCashEquivalents,trailingCashEquivalents,annualCashFinancial,trailingCashFinancial&merge=false&period1=493590046&period2=1613490868
# https://query1.finance.yahoo.com/v8/finance/chart/MSFT?symbol=MSFT&period1=1550725200&period2=1613491890&useYfid=true&interval=1d&events=div
# https://query1.finance.yahoo.com/v10/finance/quoteSummary/MSFT?formatted=true&crumb=2M1BZy1YB7f&lang=en-US®ion=US&modules=incomeStatementHistory,cashflowStatementHistory,balanceSheetHistory,incomeStatementHistoryQuarterly,cashflowStatementHistoryQuarterly,balanceSheetHistoryQuarterly&corsDomain=finance.yahoo.com
|
TypeError: Cannot join tz-naive with tz-aware DatetimeIndex
|
all!
I am trying to generate results of this repo
https://github.com/ArnaudBu/stock-returns-prediction
for stocks price prediction based on financial analysis. Running the very first step
1_get_data.py
I come across an error: TypeError: Cannot join tz-naive with tz-aware DatetimeIndex
The code is
# -*- coding: utf-8 -*-
from yfinance import Ticker
import pandas as pd
from yahoofinancials import YahooFinancials
import requests
from tqdm import tqdm
import time
import pickle
# with open('tmp.pickle', 'rb') as f:
# statements, tickers_done = pickle.load(f)
# Download function
def _download_one(ticker, start=None, end=None,
auto_adjust=False, back_adjust=False,
actions=False, period="max", interval="1d",
prepost=False, proxy=None, rounding=False):
return Ticker(ticker).history(period=period, interval=interval,
start=start, end=end, prepost=prepost,
actions=actions, auto_adjust=auto_adjust,
back_adjust=back_adjust, proxy=proxy,
rounding=rounding, many=True)
# Modify project and reference index according to your needs
tickers_all = []
# for project in ["sp500", "nyse", "nasdaq"]:
for project in ["nasdaq"]:
print(project)
ref_index = ["^GSPC", "^IXIC"]
# Load tickers
companies = pd.read_csv(f"data/{project}/{project}.csv", sep=",")
# companies = companies.drop(companies.index[companies['Symbol'].index[companies['Symbol'].isnull()][0]]) # the row with Nan value
tickers = companies.Symbol.tolist()
tickers = [a for a in tickers if a not in tickers_all and "^" not in a and r"/" not in a]
tickers_all += tickers
# Download prices
full_data = {}
for ticker in tqdm(tickers + ref_index):
tckr = _download_one(ticker,
period="7y",
actions=True)
full_data[ticker] = tckr
ohlc = pd.concat(full_data.values(), axis=1,
keys=full_data.keys())
ohlc.columns = ohlc.columns.swaplevel(0, 1)
ohlc.sort_index(level=0, axis=1, inplace=True)
prices = ohlc["Adj Close"]
dividends = ohlc["Dividends"]
prices.to_csv(f"data/{project}/prices_daily.csv")
dividends.to_csv(f"data/{project}/dividends.csv")
statements = {}
tickers_done = []
for ticker in tqdm(tickers):
# Get statements
if ticker in tickers_done:
continue
yahoo_financials = YahooFinancials(ticker)
stmts_codes = ['income', 'cash', 'balance']
all_statement_data = yahoo_financials.get_financial_stmts('annual',
stmts_codes)
# build statements dictionnary
for a in all_statement_data.keys():
if a not in statements:
statements[a] = list()
for b in all_statement_data[a]:
try:
for result in all_statement_data[a][b]:
extracted_date = list(result)[0]
dataframe_row = list(result.values())[0]
dataframe_row['date'] = extracted_date
dataframe_row['symbol'] = b
statements[a].append(dataframe_row)
except Exception as e:
print("Error on " + ticker + " : " + a)
tickers_done.append(ticker)
with open('tmp.pickle', 'wb') as f:
pickle.dump([statements, tickers_done], f)
# save dataframes
for a in all_statement_data.keys():
df = pd.DataFrame(statements[a]).set_index('date')
df.to_csv(f"data/{project}/{a}.csv")
# Donwload shares
shares = []
tickers_done = []
for ticker in tqdm(tickers):
if ticker in tickers_done:
continue
d = requests.get(f"https://query1.finance.yahoo.com/ws/fundamentals-timeseries/v1/finance/timeseries/{ticker}?symbol={ticker}&padTimeSeries=true&type=annualPreferredSharesNumber,annualOrdinarySharesNumber&merge=false&period1=0&period2=2013490868")
if not d.ok:
time.sleep(300)
d = requests.get(f"https://query1.finance.yahoo.com/ws/fundamentals-timeseries/v1/finance/timeseries/{ticker}?symbol={ticker}&padTimeSeries=true&type=annualPreferredSharesNumber,annualOrdinarySharesNumber&merge=false&period1=0&period2=2013490868")
ctn = d.json()['timeseries']['result']
dct = dict()
for n in ctn:
type = n['meta']['type'][0]
dct[type] = dict()
if type in n:
for o in n[type]:
if o is not None:
dct[type][o['asOfDate']] = o['reportedValue']['raw']
df = pd.DataFrame.from_dict(dct)
df['symbol'] = ticker
shares.append(df)
tickers_done.append(ticker)
time.sleep(1)
# save dataframe
df = pd.concat(shares)
df['date'] = df.index
df.to_csv(f"data/{project}/shares.csv", index=False)
# https://query1.finance.yahoo.com/ws/fundamentals-timeseries/v1/finance/timeseries/MSFT?symbol=MSFT&padTimeSeries=true&type=annualTreasurySharesNumber,trailingTreasurySharesNumber,annualPreferredSharesNumber,trailingPreferredSharesNumber,annualOrdinarySharesNumber,trailingOrdinarySharesNumber,annualShareIssued,trailingShareIssued,annualNetDebt,trailingNetDebt,annualTotalDebt,trailingTotalDebt,annualTangibleBookValue,trailingTangibleBookValue,annualInvestedCapital,trailingInvestedCapital,annualWorkingCapital,trailingWorkingCapital,annualNetTangibleAssets,trailingNetTangibleAssets,annualCapitalLeaseObligations,trailingCapitalLeaseObligations,annualCommonStockEquity,trailingCommonStockEquity,annualPreferredStockEquity,trailingPreferredStockEquity,annualTotalCapitalization,trailingTotalCapitalization,annualTotalEquityGrossMinorityInterest,trailingTotalEquityGrossMinorityInterest,annualMinorityInterest,trailingMinorityInterest,annualStockholdersEquity,trailingStockholdersEquity,annualOtherEquityInterest,trailingOtherEquityInterest,annualGainsLossesNotAffectingRetainedEarnings,trailingGainsLossesNotAffectingRetainedEarnings,annualOtherEquityAdjustments,trailingOtherEquityAdjustments,annualFixedAssetsRevaluationReserve,trailingFixedAssetsRevaluationReserve,annualForeignCurrencyTranslationAdjustments,trailingForeignCurrencyTranslationAdjustments,annualMinimumPensionLiabilities,trailingMinimumPensionLiabilities,annualUnrealizedGainLoss,trailingUnrealizedGainLoss,annualTreasuryStock,trailingTreasuryStock,annualRetainedEarnings,trailingRetainedEarnings,annualAdditionalPaidInCapital,trailingAdditionalPaidInCapital,annualCapitalStock,trailingCapitalStock,annualOtherCapitalStock,trailingOtherCapitalStock,annualCommonStock,trailingCommonStock,annualPreferredStock,trailingPreferredStock,annualTotalPartnershipCapital,trailingTotalPartnershipCapital,annualGeneralPartnershipCapital,trailingGeneralPartnershipCapital,annualLimitedPartnershipCapital,trailingLimitedPartnershipCapital,annualTotalLiabilitiesNetMinorityInterest,trailingTotalLiabilitiesNetMinorityInterest,annualTotalNonCurrentLiabilitiesNetMinorityInterest,trailingTotalNonCurrentLiabilitiesNetMinorityInterest,annualOtherNonCurrentLiabilities,trailingOtherNonCurrentLiabilities,annualLiabilitiesHeldforSaleNonCurrent,trailingLiabilitiesHeldforSaleNonCurrent,annualRestrictedCommonStock,trailingRestrictedCommonStock,annualPreferredSecuritiesOutsideStockEquity,trailingPreferredSecuritiesOutsideStockEquity,annualDerivativeProductLiabilities,trailingDerivativeProductLiabilities,annualEmployeeBenefits,trailingEmployeeBenefits,annualNonCurrentPensionAndOtherPostretirementBenefitPlans,trailingNonCurrentPensionAndOtherPostretirementBenefitPlans,annualNonCurrentAccruedExpenses,trailingNonCurrentAccruedExpenses,annualDuetoRelatedPartiesNonCurrent,trailingDuetoRelatedPartiesNonCurrent,annualTradeandOtherPayablesNonCurrent,trailingTradeandOtherPayablesNonCurrent,annualNonCurrentDeferredLiabilities,trailingNonCurrentDeferredLiabilities,annualNonCurrentDeferredRevenue,trailingNonCurrentDeferredRevenue,annualNonCurrentDeferredTaxesLiabilities,trailingNonCurrentDeferredTaxesLiabilities,annualLongTermDebtAndCapitalLeaseObligation,trailingLongTermDebtAndCapitalLeaseObligation,annualLongTermCapitalLeaseObligation,trailingLongTermCapitalLeaseObligation,annualLongTermDebt,trailingLongTermDebt,annualLongTermProvisions,trailingLongTermProvisions,annualCurrentLiabilities,trailingCurrentLiabilities,annualOtherCurrentLiabilities,trailingOtherCurrentLiabilities,annualCurrentDeferredLiabilities,trailingCurrentDeferredLiabilities,annualCurrentDeferredRevenue,trailingCurrentDeferredRevenue,annualCurrentDeferredTaxesLiabilities,trailingCurrentDeferredTaxesLiabilities,annualCurrentDebtAndCapitalLeaseObligation,trailingCurrentDebtAndCapitalLeaseObligation,annualCurrentCapitalLeaseObligation,trailingCurrentCapitalLeaseObligation,annualCurrentDebt,trailingCurrentDebt,annualOtherCurrentBorrowings,trailingOtherCurrentBorrowings,annualLineOfCredit,trailingLineOfCredit,annualCommercialPaper,trailingCommercialPaper,annualCurrentNotesPayable,trailingCurrentNotesPayable,annualPensionandOtherPostRetirementBenefitPlansCurrent,trailingPensionandOtherPostRetirementBenefitPlansCurrent,annualCurrentProvisions,trailingCurrentProvisions,annualPayablesAndAccruedExpenses,trailingPayablesAndAccruedExpenses,annualCurrentAccruedExpenses,trailingCurrentAccruedExpenses,annualInterestPayable,trailingInterestPayable,annualPayables,trailingPayables,annualOtherPayable,trailingOtherPayable,annualDuetoRelatedPartiesCurrent,trailingDuetoRelatedPartiesCurrent,annualDividendsPayable,trailingDividendsPayable,annualTotalTaxPayable,trailingTotalTaxPayable,annualIncomeTaxPayable,trailingIncomeTaxPayable,annualAccountsPayable,trailingAccountsPayable,annualTotalAssets,trailingTotalAssets,annualTotalNonCurrentAssets,trailingTotalNonCurrentAssets,annualOtherNonCurrentAssets,trailingOtherNonCurrentAssets,annualDefinedPensionBenefit,trailingDefinedPensionBenefit,annualNonCurrentPrepaidAssets,trailingNonCurrentPrepaidAssets,annualNonCurrentDeferredAssets,trailingNonCurrentDeferredAssets,annualNonCurrentDeferredTaxesAssets,trailingNonCurrentDeferredTaxesAssets,annualDuefromRelatedPartiesNonCurrent,trailingDuefromRelatedPartiesNonCurrent,annualNonCurrentNoteReceivables,trailingNonCurrentNoteReceivables,annualNonCurrentAccountsReceivable,trailingNonCurrentAccountsReceivable,annualFinancialAssets,trailingFinancialAssets,annualInvestmentsAndAdvances,trailingInvestmentsAndAdvances,annualOtherInvestments,trailingOtherInvestments,annualInvestmentinFinancialAssets,trailingInvestmentinFinancialAssets,annualHeldToMaturitySecurities,trailingHeldToMaturitySecurities,annualAvailableForSaleSecurities,trailingAvailableForSaleSecurities,annualFinancialAssetsDesignatedasFairValueThroughProfitorLossTotal,trailingFinancialAssetsDesignatedasFairValueThroughProfitorLossTotal,annualTradingSecurities,trailingTradingSecurities,annualLongTermEquityInvestment,trailingLongTermEquityInvestment,annualInvestmentsinJointVenturesatCost,trailingInvestmentsinJointVenturesatCost,annualInvestmentsInOtherVenturesUnderEquityMethod,trailingInvestmentsInOtherVenturesUnderEquityMethod,annualInvestmentsinAssociatesatCost,trailingInvestmentsinAssociatesatCost,annualInvestmentsinSubsidiariesatCost,trailingInvestmentsinSubsidiariesatCost,annualInvestmentProperties,trailingInvestmentProperties,annualGoodwillAndOtherIntangibleAssets,trailingGoodwillAndOtherIntangibleAssets,annualOtherIntangibleAssets,trailingOtherIntangibleAssets,annualGoodwill,trailingGoodwill,annualNetPPE,trailingNetPPE,annualAccumulatedDepreciation,trailingAccumulatedDepreciation,annualGrossPPE,trailingGrossPPE,annualLeases,trailingLeases,annualConstructionInProgress,trailingConstructionInProgress,annualOtherProperties,trailingOtherProperties,annualMachineryFurnitureEquipment,trailingMachineryFurnitureEquipment,annualBuildingsAndImprovements,trailingBuildingsAndImprovements,annualLandAndImprovements,trailingLandAndImprovements,annualProperties,trailingProperties,annualCurrentAssets,trailingCurrentAssets,annualOtherCurrentAssets,trailingOtherCurrentAssets,annualHedgingAssetsCurrent,trailingHedgingAssetsCurrent,annualAssetsHeldForSaleCurrent,trailingAssetsHeldForSaleCurrent,annualCurrentDeferredAssets,trailingCurrentDeferredAssets,annualCurrentDeferredTaxesAssets,trailingCurrentDeferredTaxesAssets,annualRestrictedCash,trailingRestrictedCash,annualPrepaidAssets,trailingPrepaidAssets,annualInventory,trailingInventory,annualInventoriesAdjustmentsAllowances,trailingInventoriesAdjustmentsAllowances,annualOtherInventories,trailingOtherInventories,annualFinishedGoods,trailingFinishedGoods,annualWorkInProcess,trailingWorkInProcess,annualRawMaterials,trailingRawMaterials,annualReceivables,trailingReceivables,annualReceivablesAdjustmentsAllowances,trailingReceivablesAdjustmentsAllowances,annualOtherReceivables,trailingOtherReceivables,annualDuefromRelatedPartiesCurrent,trailingDuefromRelatedPartiesCurrent,annualTaxesReceivable,trailingTaxesReceivable,annualAccruedInterestReceivable,trailingAccruedInterestReceivable,annualNotesReceivable,trailingNotesReceivable,annualLoansReceivable,trailingLoansReceivable,annualAccountsReceivable,trailingAccountsReceivable,annualAllowanceForDoubtfulAccountsReceivable,trailingAllowanceForDoubtfulAccountsReceivable,annualGrossAccountsReceivable,trailingGrossAccountsReceivable,annualCashCashEquivalentsAndShortTermInvestments,trailingCashCashEquivalentsAndShortTermInvestments,annualOtherShortTermInvestments,trailingOtherShortTermInvestments,annualCashAndCashEquivalents,trailingCashAndCashEquivalents,annualCashEquivalents,trailingCashEquivalents,annualCashFinancial,trailingCashFinancial&merge=false&period1=493590046&period2=1613490868
# https://query1.finance.yahoo.com/v8/finance/chart/MSFT?symbol=MSFT&period1=1550725200&period2=1613491890&useYfid=true&interval=1d&events=div
# https://query1.finance.yahoo.com/v10/finance/quoteSummary/MSFT?formatted=true&crumb=2M1BZy1YB7f&lang=en-US®ion=US&modules=incomeStatementHistory,cashflowStatementHistory,balanceSheetHistory,incomeStatementHistoryQuarterly,cashflowStatementHistoryQuarterly,balanceSheetHistoryQuarterly&corsDomain=finance.yahoo.com
The screenshot of the error is:
It refers to the line 51 of the above code. I have tried multiple times, and check some related questions/answers here as well but have not any satisfied answer. There is another similar question but it has not any proper answer.
Any help in this regard would be highly appreciated.
Thanks in anticipation!
|
[
"I have not managed to reproduce your dataframes, but generally this type of error is easily removed by doing df.tz_localize(None).\nThis will convert a tz-aware df to a tz-naive df.\nso try applying this to the full_data dataframe of yours.\n",
"all!\nI just found that the issue was related to the full_data[ticker] in line 49. Once I checked its type and data inside, I found it as dataframe and as:\n\nThe issue was with the time under the index column Date. So, to remove those I used this line full_data[ticker] = full_data[ticker].tz_localize(None) of code under the line 49 full_data[ticker] = tckr. And then I checked the full_data[ticker] so got this:\n\nThe time under the Date are disappeared hence solving the issue. Thanks to @VasP whose suggestion helped me to crack this issue.\nSo, here is the working code now:\n# -*- coding: utf-8 -*-\n\nfrom yfinance import Ticker\nimport pandas as pd\nfrom yahoofinancials import YahooFinancials\nimport requests\nfrom tqdm import tqdm\nimport time\nimport pickle\n\n# with open('tmp.pickle', 'rb') as f:\n# statements, tickers_done = pickle.load(f)\n\n\n# Download function\ndef _download_one(ticker, start=None, end=None,\n auto_adjust=False, back_adjust=False,\n actions=False, period=\"max\", interval=\"1d\",\n prepost=False, proxy=None, rounding=False):\n\n return Ticker(ticker).history(period=period, interval=interval,\n start=start, end=end, prepost=prepost,\n actions=actions, auto_adjust=auto_adjust,\n back_adjust=back_adjust, proxy=proxy,\n rounding=rounding, many=True)\n\n\n# Modify project and reference index according to your needs\ntickers_all = []\n# for project in [\"sp500\", \"nyse\", \"nasdaq\"]:\nfor project in [\"nasdaq\"]:\n print(project)\n ref_index = [\"^GSPC\", \"^IXIC\"]\n\n # Load tickers\n companies = pd.read_csv(f\"data/{project}/{project}.csv\", sep=\",\")\n # companies = companies.drop(companies.index[companies['Symbol'].index[companies['Symbol'].isnull()][0]]) # the row with Nan value\n tickers = companies.Symbol.tolist()\n tickers = [a for a in tickers if a not in tickers_all and \"^\" not in a and r\"/\" not in a]\n tickers_all += tickers\n\n # Download prices\n full_data = {}\n for ticker in tqdm(tickers + ref_index):\n tckr = _download_one(ticker,\n period=\"7y\",\n actions=True)\n full_data[ticker] = tckr\n full_data[ticker] = full_data[ticker].tz_localize(None) #Added now\n ohlc = pd.concat(full_data.values(), axis=1,\n keys=full_data.keys())\n ohlc.columns = ohlc.columns.swaplevel(0, 1)\n ohlc.sort_index(level=0, axis=1, inplace=True)\n prices = ohlc[\"Adj Close\"]\n dividends = ohlc[\"Dividends\"]\n prices.to_csv(f\"data/{project}/prices_daily.csv\")\n dividends.to_csv(f\"data/{project}/dividends.csv\")\n\n statements = {}\n tickers_done = []\n for ticker in tqdm(tickers):\n # Get statements\n if ticker in tickers_done:\n continue\n yahoo_financials = YahooFinancials(ticker)\n stmts_codes = ['income', 'cash', 'balance']\n all_statement_data = yahoo_financials.get_financial_stmts('annual',\n stmts_codes)\n # build statements dictionnary\n for a in all_statement_data.keys():\n if a not in statements:\n statements[a] = list()\n for b in all_statement_data[a]:\n try:\n for result in all_statement_data[a][b]:\n extracted_date = list(result)[0]\n dataframe_row = list(result.values())[0]\n dataframe_row['date'] = extracted_date\n dataframe_row['symbol'] = b\n statements[a].append(dataframe_row)\n except Exception as e:\n print(\"Error on \" + ticker + \" : \" + a)\n tickers_done.append(ticker)\n with open('tmp.pickle', 'wb') as f:\n pickle.dump([statements, tickers_done], f)\n\n # save dataframes\n for a in all_statement_data.keys():\n df = pd.DataFrame(statements[a]).set_index('date')\n df.to_csv(f\"data/{project}/{a}.csv\")\n\n # Donwload shares\n shares = []\n tickers_done = []\n for ticker in tqdm(tickers):\n if ticker in tickers_done:\n continue\n d = requests.get(f\"https://query1.finance.yahoo.com/ws/fundamentals-timeseries/v1/finance/timeseries/{ticker}?symbol={ticker}&padTimeSeries=true&type=annualPreferredSharesNumber,annualOrdinarySharesNumber&merge=false&period1=0&period2=2013490868\")\n if not d.ok:\n time.sleep(300)\n d = requests.get(f\"https://query1.finance.yahoo.com/ws/fundamentals-timeseries/v1/finance/timeseries/{ticker}?symbol={ticker}&padTimeSeries=true&type=annualPreferredSharesNumber,annualOrdinarySharesNumber&merge=false&period1=0&period2=2013490868\")\n ctn = d.json()['timeseries']['result']\n dct = dict()\n for n in ctn:\n type = n['meta']['type'][0]\n dct[type] = dict()\n if type in n:\n for o in n[type]:\n if o is not None:\n dct[type][o['asOfDate']] = o['reportedValue']['raw']\n df = pd.DataFrame.from_dict(dct)\n df['symbol'] = ticker\n shares.append(df)\n tickers_done.append(ticker)\n time.sleep(1)\n\n # save dataframe\n df = pd.concat(shares)\n df['date'] = df.index\n df.to_csv(f\"data/{project}/shares.csv\", index=False)\n\n # https://query1.finance.yahoo.com/ws/fundamentals-timeseries/v1/finance/timeseries/MSFT?symbol=MSFT&padTimeSeries=true&type=annualTreasurySharesNumber,trailingTreasurySharesNumber,annualPreferredSharesNumber,trailingPreferredSharesNumber,annualOrdinarySharesNumber,trailingOrdinarySharesNumber,annualShareIssued,trailingShareIssued,annualNetDebt,trailingNetDebt,annualTotalDebt,trailingTotalDebt,annualTangibleBookValue,trailingTangibleBookValue,annualInvestedCapital,trailingInvestedCapital,annualWorkingCapital,trailingWorkingCapital,annualNetTangibleAssets,trailingNetTangibleAssets,annualCapitalLeaseObligations,trailingCapitalLeaseObligations,annualCommonStockEquity,trailingCommonStockEquity,annualPreferredStockEquity,trailingPreferredStockEquity,annualTotalCapitalization,trailingTotalCapitalization,annualTotalEquityGrossMinorityInterest,trailingTotalEquityGrossMinorityInterest,annualMinorityInterest,trailingMinorityInterest,annualStockholdersEquity,trailingStockholdersEquity,annualOtherEquityInterest,trailingOtherEquityInterest,annualGainsLossesNotAffectingRetainedEarnings,trailingGainsLossesNotAffectingRetainedEarnings,annualOtherEquityAdjustments,trailingOtherEquityAdjustments,annualFixedAssetsRevaluationReserve,trailingFixedAssetsRevaluationReserve,annualForeignCurrencyTranslationAdjustments,trailingForeignCurrencyTranslationAdjustments,annualMinimumPensionLiabilities,trailingMinimumPensionLiabilities,annualUnrealizedGainLoss,trailingUnrealizedGainLoss,annualTreasuryStock,trailingTreasuryStock,annualRetainedEarnings,trailingRetainedEarnings,annualAdditionalPaidInCapital,trailingAdditionalPaidInCapital,annualCapitalStock,trailingCapitalStock,annualOtherCapitalStock,trailingOtherCapitalStock,annualCommonStock,trailingCommonStock,annualPreferredStock,trailingPreferredStock,annualTotalPartnershipCapital,trailingTotalPartnershipCapital,annualGeneralPartnershipCapital,trailingGeneralPartnershipCapital,annualLimitedPartnershipCapital,trailingLimitedPartnershipCapital,annualTotalLiabilitiesNetMinorityInterest,trailingTotalLiabilitiesNetMinorityInterest,annualTotalNonCurrentLiabilitiesNetMinorityInterest,trailingTotalNonCurrentLiabilitiesNetMinorityInterest,annualOtherNonCurrentLiabilities,trailingOtherNonCurrentLiabilities,annualLiabilitiesHeldforSaleNonCurrent,trailingLiabilitiesHeldforSaleNonCurrent,annualRestrictedCommonStock,trailingRestrictedCommonStock,annualPreferredSecuritiesOutsideStockEquity,trailingPreferredSecuritiesOutsideStockEquity,annualDerivativeProductLiabilities,trailingDerivativeProductLiabilities,annualEmployeeBenefits,trailingEmployeeBenefits,annualNonCurrentPensionAndOtherPostretirementBenefitPlans,trailingNonCurrentPensionAndOtherPostretirementBenefitPlans,annualNonCurrentAccruedExpenses,trailingNonCurrentAccruedExpenses,annualDuetoRelatedPartiesNonCurrent,trailingDuetoRelatedPartiesNonCurrent,annualTradeandOtherPayablesNonCurrent,trailingTradeandOtherPayablesNonCurrent,annualNonCurrentDeferredLiabilities,trailingNonCurrentDeferredLiabilities,annualNonCurrentDeferredRevenue,trailingNonCurrentDeferredRevenue,annualNonCurrentDeferredTaxesLiabilities,trailingNonCurrentDeferredTaxesLiabilities,annualLongTermDebtAndCapitalLeaseObligation,trailingLongTermDebtAndCapitalLeaseObligation,annualLongTermCapitalLeaseObligation,trailingLongTermCapitalLeaseObligation,annualLongTermDebt,trailingLongTermDebt,annualLongTermProvisions,trailingLongTermProvisions,annualCurrentLiabilities,trailingCurrentLiabilities,annualOtherCurrentLiabilities,trailingOtherCurrentLiabilities,annualCurrentDeferredLiabilities,trailingCurrentDeferredLiabilities,annualCurrentDeferredRevenue,trailingCurrentDeferredRevenue,annualCurrentDeferredTaxesLiabilities,trailingCurrentDeferredTaxesLiabilities,annualCurrentDebtAndCapitalLeaseObligation,trailingCurrentDebtAndCapitalLeaseObligation,annualCurrentCapitalLeaseObligation,trailingCurrentCapitalLeaseObligation,annualCurrentDebt,trailingCurrentDebt,annualOtherCurrentBorrowings,trailingOtherCurrentBorrowings,annualLineOfCredit,trailingLineOfCredit,annualCommercialPaper,trailingCommercialPaper,annualCurrentNotesPayable,trailingCurrentNotesPayable,annualPensionandOtherPostRetirementBenefitPlansCurrent,trailingPensionandOtherPostRetirementBenefitPlansCurrent,annualCurrentProvisions,trailingCurrentProvisions,annualPayablesAndAccruedExpenses,trailingPayablesAndAccruedExpenses,annualCurrentAccruedExpenses,trailingCurrentAccruedExpenses,annualInterestPayable,trailingInterestPayable,annualPayables,trailingPayables,annualOtherPayable,trailingOtherPayable,annualDuetoRelatedPartiesCurrent,trailingDuetoRelatedPartiesCurrent,annualDividendsPayable,trailingDividendsPayable,annualTotalTaxPayable,trailingTotalTaxPayable,annualIncomeTaxPayable,trailingIncomeTaxPayable,annualAccountsPayable,trailingAccountsPayable,annualTotalAssets,trailingTotalAssets,annualTotalNonCurrentAssets,trailingTotalNonCurrentAssets,annualOtherNonCurrentAssets,trailingOtherNonCurrentAssets,annualDefinedPensionBenefit,trailingDefinedPensionBenefit,annualNonCurrentPrepaidAssets,trailingNonCurrentPrepaidAssets,annualNonCurrentDeferredAssets,trailingNonCurrentDeferredAssets,annualNonCurrentDeferredTaxesAssets,trailingNonCurrentDeferredTaxesAssets,annualDuefromRelatedPartiesNonCurrent,trailingDuefromRelatedPartiesNonCurrent,annualNonCurrentNoteReceivables,trailingNonCurrentNoteReceivables,annualNonCurrentAccountsReceivable,trailingNonCurrentAccountsReceivable,annualFinancialAssets,trailingFinancialAssets,annualInvestmentsAndAdvances,trailingInvestmentsAndAdvances,annualOtherInvestments,trailingOtherInvestments,annualInvestmentinFinancialAssets,trailingInvestmentinFinancialAssets,annualHeldToMaturitySecurities,trailingHeldToMaturitySecurities,annualAvailableForSaleSecurities,trailingAvailableForSaleSecurities,annualFinancialAssetsDesignatedasFairValueThroughProfitorLossTotal,trailingFinancialAssetsDesignatedasFairValueThroughProfitorLossTotal,annualTradingSecurities,trailingTradingSecurities,annualLongTermEquityInvestment,trailingLongTermEquityInvestment,annualInvestmentsinJointVenturesatCost,trailingInvestmentsinJointVenturesatCost,annualInvestmentsInOtherVenturesUnderEquityMethod,trailingInvestmentsInOtherVenturesUnderEquityMethod,annualInvestmentsinAssociatesatCost,trailingInvestmentsinAssociatesatCost,annualInvestmentsinSubsidiariesatCost,trailingInvestmentsinSubsidiariesatCost,annualInvestmentProperties,trailingInvestmentProperties,annualGoodwillAndOtherIntangibleAssets,trailingGoodwillAndOtherIntangibleAssets,annualOtherIntangibleAssets,trailingOtherIntangibleAssets,annualGoodwill,trailingGoodwill,annualNetPPE,trailingNetPPE,annualAccumulatedDepreciation,trailingAccumulatedDepreciation,annualGrossPPE,trailingGrossPPE,annualLeases,trailingLeases,annualConstructionInProgress,trailingConstructionInProgress,annualOtherProperties,trailingOtherProperties,annualMachineryFurnitureEquipment,trailingMachineryFurnitureEquipment,annualBuildingsAndImprovements,trailingBuildingsAndImprovements,annualLandAndImprovements,trailingLandAndImprovements,annualProperties,trailingProperties,annualCurrentAssets,trailingCurrentAssets,annualOtherCurrentAssets,trailingOtherCurrentAssets,annualHedgingAssetsCurrent,trailingHedgingAssetsCurrent,annualAssetsHeldForSaleCurrent,trailingAssetsHeldForSaleCurrent,annualCurrentDeferredAssets,trailingCurrentDeferredAssets,annualCurrentDeferredTaxesAssets,trailingCurrentDeferredTaxesAssets,annualRestrictedCash,trailingRestrictedCash,annualPrepaidAssets,trailingPrepaidAssets,annualInventory,trailingInventory,annualInventoriesAdjustmentsAllowances,trailingInventoriesAdjustmentsAllowances,annualOtherInventories,trailingOtherInventories,annualFinishedGoods,trailingFinishedGoods,annualWorkInProcess,trailingWorkInProcess,annualRawMaterials,trailingRawMaterials,annualReceivables,trailingReceivables,annualReceivablesAdjustmentsAllowances,trailingReceivablesAdjustmentsAllowances,annualOtherReceivables,trailingOtherReceivables,annualDuefromRelatedPartiesCurrent,trailingDuefromRelatedPartiesCurrent,annualTaxesReceivable,trailingTaxesReceivable,annualAccruedInterestReceivable,trailingAccruedInterestReceivable,annualNotesReceivable,trailingNotesReceivable,annualLoansReceivable,trailingLoansReceivable,annualAccountsReceivable,trailingAccountsReceivable,annualAllowanceForDoubtfulAccountsReceivable,trailingAllowanceForDoubtfulAccountsReceivable,annualGrossAccountsReceivable,trailingGrossAccountsReceivable,annualCashCashEquivalentsAndShortTermInvestments,trailingCashCashEquivalentsAndShortTermInvestments,annualOtherShortTermInvestments,trailingOtherShortTermInvestments,annualCashAndCashEquivalents,trailingCashAndCashEquivalents,annualCashEquivalents,trailingCashEquivalents,annualCashFinancial,trailingCashFinancial&merge=false&period1=493590046&period2=1613490868\n # https://query1.finance.yahoo.com/v8/finance/chart/MSFT?symbol=MSFT&period1=1550725200&period2=1613491890&useYfid=true&interval=1d&events=div\n # https://query1.finance.yahoo.com/v10/finance/quoteSummary/MSFT?formatted=true&crumb=2M1BZy1YB7f&lang=en-US®ion=US&modules=incomeStatementHistory,cashflowStatementHistory,balanceSheetHistory,incomeStatementHistoryQuarterly,cashflowStatementHistoryQuarterly,balanceSheetHistoryQuarterly&corsDomain=finance.yahoo.com\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"analysis",
"datetimeindex",
"finance",
"python",
"stock"
] |
stackoverflow_0074565844_analysis_datetimeindex_finance_python_stock.txt
|
Q:
Split string by list of indexes
I need a function that splits the string by indexes specified in indexes. Wrong indexes must be ignored.
My code:
def split_by_index(s: str, indexes: List[int]) -> List[str]:
parts = [s[i:j] for i,j in zip(indexes, indexes[1:]+[None])]
return parts
My strings:
split_by_index("pythoniscool,isn'tit?", [6, 8, 12, 13, 18])
split_by_index("no luck", [42])
Output:
['is', 'cool', ',', "isn't", 'it?']
['']
Expected output:
["python", "is", "cool", ",", "isn't", "it?"]
["no luck"]
Where is my mistake?
A:
You need to start from the 0th index, while you are starting from 6:8 in your first example and 42:None in the second:
def split_by_index(s: str, indexes: List[int]) -> List[str]:
parts = [s[i:j] for i,j in zip([0] + indexes, indexes + [None])]
return parts
A:
the only appending zero to your list would have solved as mentioned in my comment, but for ignoring if the index is bigger you could add the same condition inside for loop
def split_by_index(s: str, indexes):
indexes = [0] + indexes + [None]
parts = [s[i:j] for i,j in zip(indexes, indexes[1:]) if j and j < len(s)]
return parts
A:
The only way I found that works for both cases:
def split_by_index(s: str, indexes: List[int]) -> List[str]:
parts = [s[i:j] for i,j in zip([0] + indexes, indexes + [None])]
if '' in parts:
parts.pop()
return parts
|
Split string by list of indexes
|
I need a function that splits the string by indexes specified in indexes. Wrong indexes must be ignored.
My code:
def split_by_index(s: str, indexes: List[int]) -> List[str]:
parts = [s[i:j] for i,j in zip(indexes, indexes[1:]+[None])]
return parts
My strings:
split_by_index("pythoniscool,isn'tit?", [6, 8, 12, 13, 18])
split_by_index("no luck", [42])
Output:
['is', 'cool', ',', "isn't", 'it?']
['']
Expected output:
["python", "is", "cool", ",", "isn't", "it?"]
["no luck"]
Where is my mistake?
|
[
"You need to start from the 0th index, while you are starting from 6:8 in your first example and 42:None in the second:\ndef split_by_index(s: str, indexes: List[int]) -> List[str]:\n parts = [s[i:j] for i,j in zip([0] + indexes, indexes + [None])]\n return parts\n\n",
"the only appending zero to your list would have solved as mentioned in my comment, but for ignoring if the index is bigger you could add the same condition inside for loop\ndef split_by_index(s: str, indexes):\n indexes = [0] + indexes + [None]\n parts = [s[i:j] for i,j in zip(indexes, indexes[1:]) if j and j < len(s)]\n return parts\n\n",
"The only way I found that works for both cases:\ndef split_by_index(s: str, indexes: List[int]) -> List[str]:\n parts = [s[i:j] for i,j in zip([0] + indexes, indexes + [None])]\n if '' in parts:\n parts.pop()\n return parts\n\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"indexing",
"python",
"split",
"string"
] |
stackoverflow_0074571584_indexing_python_split_string.txt
|
Q:
Direct assignment to the forward side of a many-to-many set is prohibited. Use coolbox_id.set() instead. helpme
I am getting this error when i use many to many field help me plsssssss
views.py
def add_ship(request):
if request.method=='POST':
m_namedriver = request.POST.get('m_namedriver')
driver_id = Driver.objects.get(driver_id=m_namedriver)
m_licensepl = request.POST.get('m_licensepl')
car_id = Car.objects.get(car_id=m_licensepl)
m_weightcoolbox = request.POST.get('m_weightcoolbox')
coolbox_id = Coolbox.objects.get(coolbox_id=m_weightcoolbox)
ship_date = request.POST.get('ship_date')
ship_time = request.POST.get('ship_time')
original = request.POST.get('original')
destination = request.POST.get('destination')
if shipping.objects.count() != 0:
ship_id_max = shipping.objects.aggregate(Max('shipping_id'))['ship_id__max']
next_ship_id = ship_id_max[0:2] + str(int(ship_id_max[2:6])+1)
else:
next_ship_id = "SP1000"
new_shipping = shipping.objects.create(
shipping_id = next_ship_id,
driver_id = driver_id,
car_id = car_id,
coolbox_id = coolbox_id,
ship_date = ship_date,
ship_time = ship_time,
original = original,
destination = destination,
)
new_shipping.save()
new_shipping.coolbox_id.add(coolbox_id)
return render(request,'add_ship.html',{'message1':"Add shipping successful."})
driver_ship = Driver.objects.all()
car_ship = Car.objects.all()
coolbox_ship = Coolbox.objects.all()
return render(request,'add_ship.html',{'driver_ship':driver_ship,'car_ship':car_ship,'coolbox_ship':coolbox_ship})
I've been stuck here for 3 days now. At first I used it as a CharField so I could add it, but when I added another ID it couldn't add it. It says there is a problem in this part ship_id_max = shipping.objects.aggregate(Max('shipping_id'))['ship_id__max']
models.py
class Coolbox(models.Model):
coolbox_id = models.CharField(max_length=40,primary_key=True)
medicine_name = models.ForeignKey(Medicine, on_delete=models.CASCADE, related_name="medicinename")
weight = models.FloatField(blank=True, null=True)
coolboxtemp_max = models.FloatField(blank=True, null=True)
coolboxtemp_min = models.FloatField(blank=True, null=True)
dimension = models.CharField(max_length=40)
d_measurement = models.CharField(max_length=40)
t_measurement = models.CharField(max_length=40)
total = models.FloatField(blank=True, null=True)
status = models.CharField(max_length=20, choices=STATUS, blank=True)
def __str__(self):
return f"{self.medicine_name}"
class shipping(models.Model):
shipping_id = models.CharField(max_length=15,primary_key=True)
driver_id = models.ForeignKey(Driver, on_delete=models.CASCADE, related_name="driverfk")
car_id = models.ForeignKey(Car, on_delete=models.CASCADE, related_name="carfk")
coolbox_id = models.ManyToManyField(Coolbox, related_name="coolboxfk")
ship_date = models.DateField(blank=True,null=True)
ship_time = models.TimeField(blank=True,null=True)
original = models.CharField(max_length=200)
destination = models.CharField(max_length=200)
def __str__(self):
return f"{self.shipping_id}: {self.driver_id}"
enter image description here
enter image description here
HTML
<div class="col-md-6 mb-4">
<div class="form-outline multip_select_box">
<label class="form-label" for="Coolboxs">Coolboxs ID</label>
<br>
<select name="m_weightcoolbox" id="m_weightcoolbox" class="multi_select form-control" multiple data-selected-text-format="count > 3" >
{% for m_weightcoolbox in coolbox_ship %}
<option value="{{ m_weightcoolbox.coolbox_id }}">{{ m_weightcoolbox.coolbox_id }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
enter code here
Help me plsssssssssss
A:
You need to pass a List of objects of not a single object at save
you can do like this ...
def add_ship(request):
if request.method=='POST':
m_namedriver = request.POST.get('m_namedriver')
driver_id = Driver.objects.get(driver_id=m_namedriver)
m_licensepl = request.POST.get('m_licensepl')
car_id = Car.objects.get(car_id=m_licensepl)
m_weightcoolbox = request.POST.getlist('m_weightcoolbox')
print(m_weightcoolbox)
coolb_id = [i for i in Coolbox.objects.filter(coolbox_id__in=m_weightcoolbox)]
ship_date = request.POST.get('ship_date')
ship_time = request.POST.get('ship_time')
original = request.POST.get('original')
destination = request.POST.get('destination')
if shipping.objects.count() != 0:
ship_id_max = shipping.objects.aggregate(Max('shipping_id'))["shipping_id__max"]
next_ship_id = ship_id_max[0:2] + str(int(ship_id_max[2:6])+1)
else:
next_ship_id = "SP1000"
new_shipping = shipping.objects.create(
shipping_id = next_ship_id,
driver_id = driver_id,
car_id = car_id,
ship_date = ship_date,
ship_time = ship_time,
original = original,
destination = destination,
)
new_shipping.coolbox_id.set(coolb_id)
return redirect("add_ship")
return render(request,'add_ship.html',{'message1':"Add shipping successful."})
driver_ship = Driver.objects.all()
car_ship = Car.objects.all()
coolbox_ship = Coolbox.objects.all()
return render(request,'add_ship.html',{'driver_ship':driver_ship,'car_ship':car_ship,'coolbox_ship':coolbox_ship})
CODE
https://drive.google.com/file/d/18v_BgTLSmMLhfNCDojhYlTeqkfUsASqt/view?usp=share_link
OUTPUT
after downloading Animatoin.gif file open it in Chrome Browser it's the full video of working with your project
https://drive.google.com/file/d/1klxwCUb47UI2NimCnSvrqkpc2SB0691S/view?usp=share_link
A:
def add_ship(request):
if request.method=='POST':
m_namedriver = request.POST.get('m_namedriver')
driver_id = Driver.objects.get(driver_id=m_namedriver)
m_licensepl = request.POST.get('m_licensepl')
car_id = Car.objects.get(car_id=m_licensepl)
m_weightcoolbox = request.POST.get('m_weightcoolbox')
coolbox_id = Coolbox.objects.get(coolbox_id=m_weightcoolbox)
ship_date = request.POST.get('ship_date')
ship_time = request.POST.get('ship_time')
original = request.POST.get('original')
destination = request.POST.get('destination')
if shipping.objects.count() != 0:
ship_id_max = shipping.objects.aggregate(Max('shipping_id'))['ship_id__max']
next_ship_id = ship_id_max[0:2] + str(int(ship_id_max[2:6])+1)
else:
next_ship_id = "SP1000"
new_shipping = shipping.objects.create(
shipping_id = next_ship_id,
driver_id = driver_id,
car_id = car_id,
coolbox_id = coolbox_id,
ship_date = ship_date,
ship_time = ship_time,
original = original,
destination = destination,
)
new_shipping.save()
new_shipping.shipping.add(coolbox_id)
return render(request,'add_ship.html',{'message1':"Add shipping successful."})
driver_ship = Driver.objects.all()
car_ship = Car.objects.all()
coolbox_ship = Coolbox.objects.all()
return render(request,'add_ship.html',{'driver_ship':driver_ship,'car_ship':car_ship,'coolbox_ship':coolbox_ship})
|
Direct assignment to the forward side of a many-to-many set is prohibited. Use coolbox_id.set() instead. helpme
|
I am getting this error when i use many to many field help me plsssssss
views.py
def add_ship(request):
if request.method=='POST':
m_namedriver = request.POST.get('m_namedriver')
driver_id = Driver.objects.get(driver_id=m_namedriver)
m_licensepl = request.POST.get('m_licensepl')
car_id = Car.objects.get(car_id=m_licensepl)
m_weightcoolbox = request.POST.get('m_weightcoolbox')
coolbox_id = Coolbox.objects.get(coolbox_id=m_weightcoolbox)
ship_date = request.POST.get('ship_date')
ship_time = request.POST.get('ship_time')
original = request.POST.get('original')
destination = request.POST.get('destination')
if shipping.objects.count() != 0:
ship_id_max = shipping.objects.aggregate(Max('shipping_id'))['ship_id__max']
next_ship_id = ship_id_max[0:2] + str(int(ship_id_max[2:6])+1)
else:
next_ship_id = "SP1000"
new_shipping = shipping.objects.create(
shipping_id = next_ship_id,
driver_id = driver_id,
car_id = car_id,
coolbox_id = coolbox_id,
ship_date = ship_date,
ship_time = ship_time,
original = original,
destination = destination,
)
new_shipping.save()
new_shipping.coolbox_id.add(coolbox_id)
return render(request,'add_ship.html',{'message1':"Add shipping successful."})
driver_ship = Driver.objects.all()
car_ship = Car.objects.all()
coolbox_ship = Coolbox.objects.all()
return render(request,'add_ship.html',{'driver_ship':driver_ship,'car_ship':car_ship,'coolbox_ship':coolbox_ship})
I've been stuck here for 3 days now. At first I used it as a CharField so I could add it, but when I added another ID it couldn't add it. It says there is a problem in this part ship_id_max = shipping.objects.aggregate(Max('shipping_id'))['ship_id__max']
models.py
class Coolbox(models.Model):
coolbox_id = models.CharField(max_length=40,primary_key=True)
medicine_name = models.ForeignKey(Medicine, on_delete=models.CASCADE, related_name="medicinename")
weight = models.FloatField(blank=True, null=True)
coolboxtemp_max = models.FloatField(blank=True, null=True)
coolboxtemp_min = models.FloatField(blank=True, null=True)
dimension = models.CharField(max_length=40)
d_measurement = models.CharField(max_length=40)
t_measurement = models.CharField(max_length=40)
total = models.FloatField(blank=True, null=True)
status = models.CharField(max_length=20, choices=STATUS, blank=True)
def __str__(self):
return f"{self.medicine_name}"
class shipping(models.Model):
shipping_id = models.CharField(max_length=15,primary_key=True)
driver_id = models.ForeignKey(Driver, on_delete=models.CASCADE, related_name="driverfk")
car_id = models.ForeignKey(Car, on_delete=models.CASCADE, related_name="carfk")
coolbox_id = models.ManyToManyField(Coolbox, related_name="coolboxfk")
ship_date = models.DateField(blank=True,null=True)
ship_time = models.TimeField(blank=True,null=True)
original = models.CharField(max_length=200)
destination = models.CharField(max_length=200)
def __str__(self):
return f"{self.shipping_id}: {self.driver_id}"
enter image description here
enter image description here
HTML
<div class="col-md-6 mb-4">
<div class="form-outline multip_select_box">
<label class="form-label" for="Coolboxs">Coolboxs ID</label>
<br>
<select name="m_weightcoolbox" id="m_weightcoolbox" class="multi_select form-control" multiple data-selected-text-format="count > 3" >
{% for m_weightcoolbox in coolbox_ship %}
<option value="{{ m_weightcoolbox.coolbox_id }}">{{ m_weightcoolbox.coolbox_id }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
enter code here
Help me plsssssssssss
|
[
"You need to pass a List of objects of not a single object at save\nyou can do like this ...\ndef add_ship(request):\n if request.method=='POST':\n \n m_namedriver = request.POST.get('m_namedriver')\n driver_id = Driver.objects.get(driver_id=m_namedriver)\n\n m_licensepl = request.POST.get('m_licensepl')\n car_id = Car.objects.get(car_id=m_licensepl)\n\n m_weightcoolbox = request.POST.getlist('m_weightcoolbox')\n print(m_weightcoolbox)\n coolb_id = [i for i in Coolbox.objects.filter(coolbox_id__in=m_weightcoolbox)]\n ship_date = request.POST.get('ship_date')\n ship_time = request.POST.get('ship_time')\n original = request.POST.get('original')\n destination = request.POST.get('destination')\n\n if shipping.objects.count() != 0:\n ship_id_max = shipping.objects.aggregate(Max('shipping_id'))[\"shipping_id__max\"]\n next_ship_id = ship_id_max[0:2] + str(int(ship_id_max[2:6])+1)\n else:\n next_ship_id = \"SP1000\"\n\n new_shipping = shipping.objects.create(\n shipping_id = next_ship_id,\n driver_id = driver_id,\n car_id = car_id,\n ship_date = ship_date,\n ship_time = ship_time,\n original = original,\n destination = destination,\n )\n new_shipping.coolbox_id.set(coolb_id)\n return redirect(\"add_ship\")\n\n return render(request,'add_ship.html',{'message1':\"Add shipping successful.\"})\n driver_ship = Driver.objects.all()\n car_ship = Car.objects.all()\n coolbox_ship = Coolbox.objects.all()\n return render(request,'add_ship.html',{'driver_ship':driver_ship,'car_ship':car_ship,'coolbox_ship':coolbox_ship})\n\nCODE\nhttps://drive.google.com/file/d/18v_BgTLSmMLhfNCDojhYlTeqkfUsASqt/view?usp=share_link\nOUTPUT\nafter downloading Animatoin.gif file open it in Chrome Browser it's the full video of working with your project\nhttps://drive.google.com/file/d/1klxwCUb47UI2NimCnSvrqkpc2SB0691S/view?usp=share_link\n",
"def add_ship(request):\n\nif request.method=='POST':\n \n m_namedriver = request.POST.get('m_namedriver')\n driver_id = Driver.objects.get(driver_id=m_namedriver)\n\n m_licensepl = request.POST.get('m_licensepl')\n car_id = Car.objects.get(car_id=m_licensepl)\n\n m_weightcoolbox = request.POST.get('m_weightcoolbox')\n coolbox_id = Coolbox.objects.get(coolbox_id=m_weightcoolbox)\n\n ship_date = request.POST.get('ship_date')\n ship_time = request.POST.get('ship_time')\n original = request.POST.get('original')\n destination = request.POST.get('destination')\n\n if shipping.objects.count() != 0:\n ship_id_max = shipping.objects.aggregate(Max('shipping_id'))['ship_id__max']\n next_ship_id = ship_id_max[0:2] + str(int(ship_id_max[2:6])+1)\n else:\n next_ship_id = \"SP1000\"\n\n new_shipping = shipping.objects.create(\n shipping_id = next_ship_id,\n driver_id = driver_id,\n car_id = car_id,\n coolbox_id = coolbox_id,\n ship_date = ship_date,\n ship_time = ship_time,\n original = original,\n destination = destination,\n )\n\n new_shipping.save()\n new_shipping.shipping.add(coolbox_id)\n\n return render(request,'add_ship.html',{'message1':\"Add shipping successful.\"})\ndriver_ship = Driver.objects.all()\ncar_ship = Car.objects.all()\ncoolbox_ship = Coolbox.objects.all()\nreturn render(request,'add_ship.html',{'driver_ship':driver_ship,'car_ship':car_ship,'coolbox_ship':coolbox_ship})\n\n"
] |
[
1,
0
] |
[
"<div class=\"col-md-6 mb-4\">\n <div class=\"form-outline multip_select_box\">\n <label class=\"form-label\" for=\"Coolboxs\">Coolboxs ID</label>\n <br>\n <select name=\"m_weightcoolbox\" id=\"m_weightcoolbox\" class=\"multi_select form-control\" multiple data-selected-text-format=\"count > 3\" >\n {% for m_weightcoolbox in coolbox_ship %}\n \n <option value=\"{{ m_weightcoolbox.coolbox_id }}\">{{ m_weightcoolbox.coolbox_id }}</option>\n {% endfor %}\n \n </select>\n \n \n\n \n \n </div>\n \n </div>\n </div> \n\n"
] |
[
-1
] |
[
"django_models",
"django_views",
"python"
] |
stackoverflow_0074570113_django_models_django_views_python.txt
|
Q:
Pyspark lambda operation to create key pairs
I already have code which maps to this
['vita', 'oscura', 'smarrita', 'dura', 'forte', 'paura', 'morte', 'trovai', 'scorte', 'v’intrai']
I want this
[('vita','oscura',1),('oscura','smarrita',1),('smarrita','dura',1), ('dura','forte',1) etc
I thought that I could do this via a lambda function, where for every line, i ask for the first row, first item, then I ask for first row second column, which fails bc of an out of index error, any points on how I could go about this?
this is my code so far
def lower_clean_str(x):
punc='!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
lowercased_str = x.lower()
for ch in punc:
lowercased_str = lowercased_str.replace(ch, '')
return lowercased_str
clean_dcr=dcr.map(lower_clean_str)
print(clean_dcr.take(10))
#we split on whitespaces as in ex1, notice how this time we take [-1] to grab only the first word
clean_dcr=clean_dcr.map(lambda line: line.split()[-1])
print(clean_dcr.take(10))
#this gives an error
#clean_dcr=clean_dcr.map((lambda line:line[0][0],line[0][1])),1)
#print(clean_dcr.take(3))
A:
For Python 3.10 and above one can use pairwise
Sample code snippet can be,
import itertools
input_list = ['vita', 'oscura', 'smarrita', 'dura', 'forte', 'paura', 'morte', 'trovai', 'scorte', 'v’intrai']
output = [element + (1, ) for element in itertools.pairwise(input_list)]
For python versions below 3.10 one can use reference implementation of pairwise which is also mentioned in the link
|
Pyspark lambda operation to create key pairs
|
I already have code which maps to this
['vita', 'oscura', 'smarrita', 'dura', 'forte', 'paura', 'morte', 'trovai', 'scorte', 'v’intrai']
I want this
[('vita','oscura',1),('oscura','smarrita',1),('smarrita','dura',1), ('dura','forte',1) etc
I thought that I could do this via a lambda function, where for every line, i ask for the first row, first item, then I ask for first row second column, which fails bc of an out of index error, any points on how I could go about this?
this is my code so far
def lower_clean_str(x):
punc='!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
lowercased_str = x.lower()
for ch in punc:
lowercased_str = lowercased_str.replace(ch, '')
return lowercased_str
clean_dcr=dcr.map(lower_clean_str)
print(clean_dcr.take(10))
#we split on whitespaces as in ex1, notice how this time we take [-1] to grab only the first word
clean_dcr=clean_dcr.map(lambda line: line.split()[-1])
print(clean_dcr.take(10))
#this gives an error
#clean_dcr=clean_dcr.map((lambda line:line[0][0],line[0][1])),1)
#print(clean_dcr.take(3))
|
[
"For Python 3.10 and above one can use pairwise\nSample code snippet can be,\nimport itertools\n\ninput_list = ['vita', 'oscura', 'smarrita', 'dura', 'forte', 'paura', 'morte', 'trovai', 'scorte', 'v’intrai']\n\noutput = [element + (1, ) for element in itertools.pairwise(input_list)]\n\nFor python versions below 3.10 one can use reference implementation of pairwise which is also mentioned in the link\n"
] |
[
1
] |
[] |
[] |
[
"lambda",
"map_function",
"python"
] |
stackoverflow_0074571753_lambda_map_function_python.txt
|
Q:
Pyfirmata throws error after creating arduino object
I'm trying to start an arduino project but every time I try running it it throws an error. I think I might have gotten some of the setup wrong?
I've uploaded the Standard Firmata Sketch to the Arduino Mega and installed pyFirmata. I can't really think of what else I could've done wrong.
Note that I'd already tried in another computer and, while it didn't really work, the board was initialized and it didn't throw any error like this
This is my python code
import pyfirmata as pf
board = pf.ArduinoMega('COM5')
And this is the eror thrown
Traceback (most recent call last):
File "C:\Users\stiky\Desktop\Code\Python Codes\Arduino\test.py", line 3, in <module>
board = pf.ArduinoMega('COM5')
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\stiky\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyfirmata\__init__.py", line 32, in __init__
super(ArduinoMega, self).__init__(*args, **kwargs)
File "C:\Users\stiky\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyfirmata\pyfirmata.py", line 101, in __init__
self.setup_layout(layout)
File "C:\Users\stiky\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyfirmata\pyfirmata.py", line 157, in setup_layout
self._set_default_handlers()
File "C:\Users\stiky\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyfirmata\pyfirmata.py", line 161, in _set_default_handlers
self.add_cmd_handler(ANALOG_MESSAGE, self._handle_analog_message)
File "C:\Users\stiky\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyfirmata\pyfirmata.py", line 185, in add_cmd_handler
len_args = len(inspect.getargspec(func)[0])
^^^^^^^^^^^^^^^^^^
AttributeError: module 'inspect' has no attribute 'getargspec'. Did you mean: 'getargs'?
What am I doing wrong?
A:
This is probably a compatibility issue between PyFirmata and your Python version.
getargspec is deprecated since Python 3.11.
An up-to-date PyFirmata version should have replaced this by getfullargspec.
https://github.com/tino/pyFirmata/commit/1f6b116b80172e70c7866d595120413078ae1222
Also the PyFirmata documentations says
It runs on Python 2.7, 3.6 and 3.7.
So I would not necessarily expect 3.11 to run without problems.
|
Pyfirmata throws error after creating arduino object
|
I'm trying to start an arduino project but every time I try running it it throws an error. I think I might have gotten some of the setup wrong?
I've uploaded the Standard Firmata Sketch to the Arduino Mega and installed pyFirmata. I can't really think of what else I could've done wrong.
Note that I'd already tried in another computer and, while it didn't really work, the board was initialized and it didn't throw any error like this
This is my python code
import pyfirmata as pf
board = pf.ArduinoMega('COM5')
And this is the eror thrown
Traceback (most recent call last):
File "C:\Users\stiky\Desktop\Code\Python Codes\Arduino\test.py", line 3, in <module>
board = pf.ArduinoMega('COM5')
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\stiky\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyfirmata\__init__.py", line 32, in __init__
super(ArduinoMega, self).__init__(*args, **kwargs)
File "C:\Users\stiky\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyfirmata\pyfirmata.py", line 101, in __init__
self.setup_layout(layout)
File "C:\Users\stiky\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyfirmata\pyfirmata.py", line 157, in setup_layout
self._set_default_handlers()
File "C:\Users\stiky\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyfirmata\pyfirmata.py", line 161, in _set_default_handlers
self.add_cmd_handler(ANALOG_MESSAGE, self._handle_analog_message)
File "C:\Users\stiky\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyfirmata\pyfirmata.py", line 185, in add_cmd_handler
len_args = len(inspect.getargspec(func)[0])
^^^^^^^^^^^^^^^^^^
AttributeError: module 'inspect' has no attribute 'getargspec'. Did you mean: 'getargs'?
What am I doing wrong?
|
[
"This is probably a compatibility issue between PyFirmata and your Python version.\ngetargspec is deprecated since Python 3.11.\nAn up-to-date PyFirmata version should have replaced this by getfullargspec.\nhttps://github.com/tino/pyFirmata/commit/1f6b116b80172e70c7866d595120413078ae1222\nAlso the PyFirmata documentations says\n\nIt runs on Python 2.7, 3.6 and 3.7.\n\nSo I would not necessarily expect 3.11 to run without problems.\n"
] |
[
0
] |
[] |
[] |
[
"arduino",
"pyfirmata",
"python",
"python_module"
] |
stackoverflow_0074572015_arduino_pyfirmata_python_python_module.txt
|
Q:
how can i make a conditional sort for storting a list of tuples?
I have been trying to sort this list in a way that it should first sort based on the second item of the tuples but if two tuples have the same second item it should sort based on the first item alphabetically
patient_list: list[tuple] = [("Johnson", 9), ("Smith", 2), ("Perry", 4), ("Allison", 8), ("Bradley", 1), ("Tucker", 9)]
def sort(patient_list: list[tuple]) -> list[tuple]:
"""
"""
patient_list = sorted(patient_list, key=lambda y: y[1])
print(patient_list)
sort(patient_list)
i tried this first but it doesnt work:
patient_list: list[tuple] = [("Johnson", 9), ("Smith", 2), ("Perry", 4), ("Allison", 8), ("Bradley", 1), ("Tucker", 9)]
def sort(patient_list: list[tuple]) -> list[tuple]:
"""
"""
patient_list = sorted(patient_list, key=lambda t: t[0])
patient_list = sorted(patient_list, key=lambda y: y[1])
print(patient_list)
sort(patient_list)
A:
You need to phrase the problem statement as the function that you pass as key=.
patient_list.sort(key=lambda t: (t[1],t[0]))
This works because tuples sort the way you would expect. Since you want the data sorted in-place in patient_list, use .sort() instead of sorted().
|
how can i make a conditional sort for storting a list of tuples?
|
I have been trying to sort this list in a way that it should first sort based on the second item of the tuples but if two tuples have the same second item it should sort based on the first item alphabetically
patient_list: list[tuple] = [("Johnson", 9), ("Smith", 2), ("Perry", 4), ("Allison", 8), ("Bradley", 1), ("Tucker", 9)]
def sort(patient_list: list[tuple]) -> list[tuple]:
"""
"""
patient_list = sorted(patient_list, key=lambda y: y[1])
print(patient_list)
sort(patient_list)
i tried this first but it doesnt work:
patient_list: list[tuple] = [("Johnson", 9), ("Smith", 2), ("Perry", 4), ("Allison", 8), ("Bradley", 1), ("Tucker", 9)]
def sort(patient_list: list[tuple]) -> list[tuple]:
"""
"""
patient_list = sorted(patient_list, key=lambda t: t[0])
patient_list = sorted(patient_list, key=lambda y: y[1])
print(patient_list)
sort(patient_list)
|
[
"You need to phrase the problem statement as the function that you pass as key=.\npatient_list.sort(key=lambda t: (t[1],t[0]))\n\nThis works because tuples sort the way you would expect. Since you want the data sorted in-place in patient_list, use .sort() instead of sorted().\n"
] |
[
0
] |
[] |
[] |
[
"conditional_statements",
"lambda",
"python",
"sorting"
] |
stackoverflow_0074572081_conditional_statements_lambda_python_sorting.txt
|
Q:
TensorFlow: Couldn't understand the error mentioned below
My code attempts to take different files as input and predict their language. This is the error I am getting every time I run the main file. At first, I thought it was a problem with the output path but so far it doesn't seem like that's the problem as I have gone through all the code files I have written and checked all the paths. And now I am unable to infer what this error actually means. Please help.
2022-11-25 16:53:52.060639: W tensorflow/core/common_runtime/forward_type_inference.cc:332] Type inference failed. This indicates an invalid graph that escaped type checking. Error message: INVALID_ARGUMENT: expected compatible input types, but input 1:
type_id: TFT_OPTIONAL
args {
type_id: TFT_PRODUCT
args {
type_id: TFT_TENSOR
args {
type_id: TFT_INT64
}
}
}
is neither a subtype nor a supertype of the combined inputs preceding it:
type_id: TFT_OPTIONAL
args {
type_id: TFT_PRODUCT
args {
type_id: TFT_TENSOR
args {
type_id: TFT_INT32
}
}
}
while inferring type of node 'dnn/zero_fraction/cond/output/_18'
2022-11-25 16:53:54.402348: W tensorflow/core/framework/op_kernel.cc:1780] OP_REQUIRES failed at save_restore_v2_ops.cc:112 : NOT_FOUND: Failed to create a NewWriteableFile: C:/Users/vs889/Desktop/project/outputs\model.ckpt-0_temp\part-00000-of-00001.data-00000-of-00001.tempstate6886965226105612622 : The system cannot find the path specified.
; No such process
Traceback (most recent call last):
File "C:\Users\vs889\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\python\client\session.py", line 1378, in _do_call
return fn(*args)
File "C:\Users\vs889\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\python\client\session.py", line 1361, in _run_fn
return self._call_tf_sessionrun(options, feed_dict, fetch_list,
File "C:\Users\vs889\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\python\client\session.py", line 1454, in _call_tf_sessionrun
return tf_session.TF_SessionRun_wrapper(self._session, options, feed_dict,
tensorflow.python.framework.errors_impl.NotFoundError: Failed to create a NewWriteableFile: C:/Users/vs889/Desktop/project/outputs\model.ckpt-0_temp\part-00000-of-00001.data-00000-of-00001.tempstate6886965226105612622 : The system cannot find the path specified.
; No such process
[[{{node save/SaveV2}}]]
A:
Maybe your way of naming files and paths makes windows unable to recognize the file location. You can test by running on linux. You should agree to use "\" on Windows and avoid the "-" sign.
|
TensorFlow: Couldn't understand the error mentioned below
|
My code attempts to take different files as input and predict their language. This is the error I am getting every time I run the main file. At first, I thought it was a problem with the output path but so far it doesn't seem like that's the problem as I have gone through all the code files I have written and checked all the paths. And now I am unable to infer what this error actually means. Please help.
2022-11-25 16:53:52.060639: W tensorflow/core/common_runtime/forward_type_inference.cc:332] Type inference failed. This indicates an invalid graph that escaped type checking. Error message: INVALID_ARGUMENT: expected compatible input types, but input 1:
type_id: TFT_OPTIONAL
args {
type_id: TFT_PRODUCT
args {
type_id: TFT_TENSOR
args {
type_id: TFT_INT64
}
}
}
is neither a subtype nor a supertype of the combined inputs preceding it:
type_id: TFT_OPTIONAL
args {
type_id: TFT_PRODUCT
args {
type_id: TFT_TENSOR
args {
type_id: TFT_INT32
}
}
}
while inferring type of node 'dnn/zero_fraction/cond/output/_18'
2022-11-25 16:53:54.402348: W tensorflow/core/framework/op_kernel.cc:1780] OP_REQUIRES failed at save_restore_v2_ops.cc:112 : NOT_FOUND: Failed to create a NewWriteableFile: C:/Users/vs889/Desktop/project/outputs\model.ckpt-0_temp\part-00000-of-00001.data-00000-of-00001.tempstate6886965226105612622 : The system cannot find the path specified.
; No such process
Traceback (most recent call last):
File "C:\Users\vs889\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\python\client\session.py", line 1378, in _do_call
return fn(*args)
File "C:\Users\vs889\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\python\client\session.py", line 1361, in _run_fn
return self._call_tf_sessionrun(options, feed_dict, fetch_list,
File "C:\Users\vs889\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\python\client\session.py", line 1454, in _call_tf_sessionrun
return tf_session.TF_SessionRun_wrapper(self._session, options, feed_dict,
tensorflow.python.framework.errors_impl.NotFoundError: Failed to create a NewWriteableFile: C:/Users/vs889/Desktop/project/outputs\model.ckpt-0_temp\part-00000-of-00001.data-00000-of-00001.tempstate6886965226105612622 : The system cannot find the path specified.
; No such process
[[{{node save/SaveV2}}]]
|
[
"Maybe your way of naming files and paths makes windows unable to recognize the file location. You can test by running on linux. You should agree to use \"\\\" on Windows and avoid the \"-\" sign.\n"
] |
[
0
] |
[] |
[] |
[
"deep_learning",
"machine_learning",
"python",
"python_3.x",
"tensorflow"
] |
stackoverflow_0074572198_deep_learning_machine_learning_python_python_3.x_tensorflow.txt
|
Q:
Python dataframe find closest date for each ID
I have a dataframe like this:
data = {'SalePrice':[10,10,10,20,20,3,3,1,4,8,8],'HandoverDateA':['2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-03-30','2022-03-30'],'ID': ['Tom', 'Tom','Tom','Joseph','Joseph','Ben','Ben','Eden','Tim','Adam','Adam'], 'Tranche': ['Red', 'Red', 'Red', 'Red','Red','Blue','Blue','Red','Red','Red','Red'],'Totals':[100,100,100,50,50,90,90,70,60,70,70],'Sent':['2022-01-18','2022-02-19','2022-03-14','2022-03-14','2022-04-22','2022-03-03','2022-02-07','2022-01-04','2022-01-10','2022-01-15','2022-03-12'],'Amount':[20,10,14,34,15,60,25,10,10,40,20],'Opened':['2021-12-29','2021-12-29','2021-12-29','2022-12-29','2022-12-29','2021-12-19','2021-12-19','2021-12-29','2021-12-29','2021-12-29','2021-12-29']}
I need to find the sent date which is closest to the HandoverDate. I've seen plenty of examples that work when you give one date to search but here the date I want to be closest to can change for every ID. I have tried to adapt the following:
def nearest(items, pivot):
return min([i for i in items if i <= pivot], key=lambda x: abs(x - pivot))
And also tried to write a loop where I make a dataframe for each ID and use max on the date column then stick them together, but it's incredibly slow!
Thanks for any suggestions :)
A:
IIUC, you can use:
data[['HandoverDateA', 'Sent']] = data[['HandoverDateA', 'Sent']].apply(pd.to_datetime)
out = data.loc[data['HandoverDateA']
.sub(data['Sent']).abs()
.groupby(data['ID']).idxmin()]
Output:
SalePrice HandoverDateA ID Tranche Totals Sent Amount Opened
10 8 2022-03-30 Adam Red 70 2022-03-12 20 2021-12-29
5 3 2022-04-30 Ben Blue 90 2022-03-03 60 2021-12-19
7 1 2022-04-30 Eden Red 70 2022-01-04 10 2021-12-29
4 20 2022-04-30 Joseph Red 50 2022-04-22 15 2022-12-29
8 4 2022-04-30 Tim Red 60 2022-01-10 10 2021-12-29
2 10 2022-04-30 Tom Red 100 2022-03-14 14 2021-12-29
A:
Considering that the goal is to find the sent date which is closest to the HandoverDate, one approach would be as follows.
First of all, create the dataframe df from data with pandas.DataFrame
import pandas as pd
df = pd.DataFrame(data)
Then, make sure that the columns HandoverDateA and Sent are of datetime using pandas.to_datetime
df['HandoverDateA'] = pd.to_datetime(df['HandoverDateA'])
df['Sent'] = pd.to_datetime(df['Sent'])
Then, in order to make it more convenient, create a column, diff, to store the absolute value of the difference between the columns HandoverDateA and Sent
df['diff'] = (df['HandoverDateA'] - df['Sent']).dt.days.abs()
With that column, one can simply sort by that column as follows
df = df.sort_values(by=['diff'])
[Out]:
SalePrice HandoverDateA ID ... Amount Opened diff
4 20 2022-04-30 Joseph ... 15 2022-12-29 8
10 8 2022-03-30 Adam ... 20 2021-12-29 18
2 10 2022-04-30 Tom ... 14 2021-12-29 47
5 3 2022-04-30 Ben ... 60 2021-12-19 58
8 4 2022-04-30 Tim ... 10 2021-12-29 110
7 1 2022-04-30 Eden ... 10 2021-12-29 116
and the first row is the one where Sent is closest to HandOverDateA.
With the column diff, one option to get the one where diff is minimum is with pandas.DataFrame.query as follows
df = df.query('diff == diff.min()')
[Out]:
SalePrice HandoverDateA ID Tranche ... Sent Amount Opened diff
4 20 2022-04-30 Joseph Red ... 2022-04-22 15 2022-12-29 8
Notes:
For more information on sorting dataframes by columns, read my answer here.
|
Python dataframe find closest date for each ID
|
I have a dataframe like this:
data = {'SalePrice':[10,10,10,20,20,3,3,1,4,8,8],'HandoverDateA':['2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-03-30','2022-03-30'],'ID': ['Tom', 'Tom','Tom','Joseph','Joseph','Ben','Ben','Eden','Tim','Adam','Adam'], 'Tranche': ['Red', 'Red', 'Red', 'Red','Red','Blue','Blue','Red','Red','Red','Red'],'Totals':[100,100,100,50,50,90,90,70,60,70,70],'Sent':['2022-01-18','2022-02-19','2022-03-14','2022-03-14','2022-04-22','2022-03-03','2022-02-07','2022-01-04','2022-01-10','2022-01-15','2022-03-12'],'Amount':[20,10,14,34,15,60,25,10,10,40,20],'Opened':['2021-12-29','2021-12-29','2021-12-29','2022-12-29','2022-12-29','2021-12-19','2021-12-19','2021-12-29','2021-12-29','2021-12-29','2021-12-29']}
I need to find the sent date which is closest to the HandoverDate. I've seen plenty of examples that work when you give one date to search but here the date I want to be closest to can change for every ID. I have tried to adapt the following:
def nearest(items, pivot):
return min([i for i in items if i <= pivot], key=lambda x: abs(x - pivot))
And also tried to write a loop where I make a dataframe for each ID and use max on the date column then stick them together, but it's incredibly slow!
Thanks for any suggestions :)
|
[
"IIUC, you can use:\ndata[['HandoverDateA', 'Sent']] = data[['HandoverDateA', 'Sent']].apply(pd.to_datetime)\n\nout = data.loc[data['HandoverDateA']\n .sub(data['Sent']).abs()\n .groupby(data['ID']).idxmin()]\n\nOutput:\n SalePrice HandoverDateA ID Tranche Totals Sent Amount Opened\n10 8 2022-03-30 Adam Red 70 2022-03-12 20 2021-12-29\n5 3 2022-04-30 Ben Blue 90 2022-03-03 60 2021-12-19\n7 1 2022-04-30 Eden Red 70 2022-01-04 10 2021-12-29\n4 20 2022-04-30 Joseph Red 50 2022-04-22 15 2022-12-29\n8 4 2022-04-30 Tim Red 60 2022-01-10 10 2021-12-29\n2 10 2022-04-30 Tom Red 100 2022-03-14 14 2021-12-29\n\n",
"Considering that the goal is to find the sent date which is closest to the HandoverDate, one approach would be as follows.\nFirst of all, create the dataframe df from data with pandas.DataFrame\nimport pandas as pd\n\ndf = pd.DataFrame(data)\n\nThen, make sure that the columns HandoverDateA and Sent are of datetime using pandas.to_datetime\ndf['HandoverDateA'] = pd.to_datetime(df['HandoverDateA'])\ndf['Sent'] = pd.to_datetime(df['Sent'])\n\nThen, in order to make it more convenient, create a column, diff, to store the absolute value of the difference between the columns HandoverDateA and Sent\ndf['diff'] = (df['HandoverDateA'] - df['Sent']).dt.days.abs()\n\nWith that column, one can simply sort by that column as follows\ndf = df.sort_values(by=['diff'])\n\n[Out]:\n\n SalePrice HandoverDateA ID ... Amount Opened diff\n4 20 2022-04-30 Joseph ... 15 2022-12-29 8\n10 8 2022-03-30 Adam ... 20 2021-12-29 18\n2 10 2022-04-30 Tom ... 14 2021-12-29 47\n5 3 2022-04-30 Ben ... 60 2021-12-19 58\n8 4 2022-04-30 Tim ... 10 2021-12-29 110\n7 1 2022-04-30 Eden ... 10 2021-12-29 116\n\nand the first row is the one where Sent is closest to HandOverDateA.\nWith the column diff, one option to get the one where diff is minimum is with pandas.DataFrame.query as follows\ndf = df.query('diff == diff.min()')\n\n[Out]:\n\n SalePrice HandoverDateA ID Tranche ... Sent Amount Opened diff\n4 20 2022-04-30 Joseph Red ... 2022-04-22 15 2022-12-29 8\n\n\nNotes:\n\nFor more information on sorting dataframes by columns, read my answer here.\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"dataframe",
"datetime",
"pandas",
"python"
] |
stackoverflow_0074571603_dataframe_datetime_pandas_python.txt
|
Q:
How to tail and use grep for all the log files inside a folder and subfolders using subprocess?
I am using flask and I am trying to tail and get the lines containing Error and or Warning in all the log files inside the folder and subfolders using subprocess. I show the outcome on the webapp using Jinja in my html file in a div. If I use "**/*.log" to select all log files in the folder and subfolders the div is empty and I do not see any lines. If I use the exact path of a logfile it does show the correct lines of the certain log. Am I doing something wrong?
@ app.route("/")
def index():
# get stream name in card
naam = os.path.basename('../TESTCLIENT.log')
naamUitkomst = os.path.splitext(naam)[0]
#gets log lines containing Error and or Warning
out = subprocess.run(['tail', '-n', '10', '|', 'egrep', '-w', 'Error|Warning', "**/*.log"], capture_output=True)
return render_template('index.html', value=naamUitkomst, result=out.stdout.decode())
<div class="card">
<div class="card-header" id="headingThree">
<h2 class="mb-0">
<button id="btnColor" class="btn btn-link collapsed" type="button" data-toggle="collapse"
data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
{{ value }}
</button>
</h2>
</div>
<div id="collapseThree" class="collapse" aria-labelledby="headingThree" data- parent="#accordionExample">
<div id="test" class="card-body>
{{ result }}
</div>
</div>
</div>
I tried using the direct path to a single logfile in the command. If I do so it does work for the single file but the moment I use **/*.log to select all the logfiles the webapp shows nothing. I have tried different python modules to excecute Unix commands in python but subprocess is the only one that sort of works for me.
A:
It doesn't work because without shell=True, the run command passes the **/*.log argument literally without expanding the arguments.
But better drop all the underlying commands, pipes and processes. Why not just code it in python? My attempt (not tested)
import glob,re
# list of matching lines
out = []
# match your pattern
for logfile in glob.glob("**/*.log",recursive=True):
# read the last 10 lines of each logfile
with open(logfile) as f:
for line in f.readlines()[-10:]:
# extract errors using regex and "word only" mode
m = re.search(r"\b(Error|Warning)\b",line)
if m:
out.append(line)
# full result as text buffer
out = "".join(out)
|
How to tail and use grep for all the log files inside a folder and subfolders using subprocess?
|
I am using flask and I am trying to tail and get the lines containing Error and or Warning in all the log files inside the folder and subfolders using subprocess. I show the outcome on the webapp using Jinja in my html file in a div. If I use "**/*.log" to select all log files in the folder and subfolders the div is empty and I do not see any lines. If I use the exact path of a logfile it does show the correct lines of the certain log. Am I doing something wrong?
@ app.route("/")
def index():
# get stream name in card
naam = os.path.basename('../TESTCLIENT.log')
naamUitkomst = os.path.splitext(naam)[0]
#gets log lines containing Error and or Warning
out = subprocess.run(['tail', '-n', '10', '|', 'egrep', '-w', 'Error|Warning', "**/*.log"], capture_output=True)
return render_template('index.html', value=naamUitkomst, result=out.stdout.decode())
<div class="card">
<div class="card-header" id="headingThree">
<h2 class="mb-0">
<button id="btnColor" class="btn btn-link collapsed" type="button" data-toggle="collapse"
data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
{{ value }}
</button>
</h2>
</div>
<div id="collapseThree" class="collapse" aria-labelledby="headingThree" data- parent="#accordionExample">
<div id="test" class="card-body>
{{ result }}
</div>
</div>
</div>
I tried using the direct path to a single logfile in the command. If I do so it does work for the single file but the moment I use **/*.log to select all the logfiles the webapp shows nothing. I have tried different python modules to excecute Unix commands in python but subprocess is the only one that sort of works for me.
|
[
"It doesn't work because without shell=True, the run command passes the **/*.log argument literally without expanding the arguments.\nBut better drop all the underlying commands, pipes and processes. Why not just code it in python? My attempt (not tested)\nimport glob,re\n\n# list of matching lines\nout = []\n# match your pattern\nfor logfile in glob.glob(\"**/*.log\",recursive=True):\n # read the last 10 lines of each logfile\n with open(logfile) as f:\n for line in f.readlines()[-10:]:\n # extract errors using regex and \"word only\" mode\n m = re.search(r\"\\b(Error|Warning)\\b\",line)\n if m:\n out.append(line)\n\n# full result as text buffer\nout = \"\".join(out)\n\n"
] |
[
0
] |
[] |
[] |
[
"flask",
"grep",
"python",
"subprocess",
"tail"
] |
stackoverflow_0074572211_flask_grep_python_subprocess_tail.txt
|
Q:
Pandas: Merge two dataframes with timedelta
I am attempting to perform an inner merge of two large dataframes having columns 'ID' and 'Date'. A sample of each is shown below:
df1
ID Date
0 RHD78 2022-08-05
1 RHD78 2022-08-06
2 RHD78 2022-08-09
3 RHD78 2022-08-11
4 RHD78 2022-08-12
5 RHD78 2022-08-14
6 RHD78 2022-08-15
7 RHD78 2022-08-19
8 BDW56 2022-03-15
9 BDW56 2022-03-16
10 BDW56 2022-03-17
11 BDW56 2022-03-22
12 BDW56 2022-03-23
13 BDW56 2022-03-27
14 BDW56 2022-03-29
15 BDW56 2022-03-30
df2
ID Date
0 RHD78 2022-08-12
1 BDW56 2022-03-23
If I use the code df_result = pd.merge(df1, df2, how = 'inner', on='Date') then I get the two intersecting datapoints. However I am struggling to introduce a timedelta such that the resulting dataframe also includes data 4 days before and after the intersecting dates like so:
df_desired
ID Date
0 RHD78 8/9/2022
1 RHD78 8/11/2022
2 RHD78 8/12/2022
3 RHD78 8/14/2022
4 RHD78 8/15/2022
5 BDW56 3/22/2022
6 BDW56 3/23/2022
7 BDW56 3/27/2022
I tried to look into using merge_asof() function but my understanding is that it gets only the values that are closest to the date and not within a particular date range. I am learning pandas and python so I would appreciate if someone can help me solve this issue and provide simplified explanation of merge_asof().
A:
Using df as your first dataframe and df2 as the second, i followed the same procedure as in this answer, which was to cross merge them together and then filter after the merge has occurred. A cross merge is just a blanket merge, which combines each row pair from each dataframe together. This might not be applicable if your two dataframes are immensely large.
merge = df2.merge(df,how='cross')
merge['timedelta'] = pd.to_datetime(merge['Date_x']) - \
pd.to_datetime(merge['Date_y'])
merge_filt = merge.loc[merge['timedelta'].apply(lambda x: x.days).abs()<=4]
print(merge_filt)
Out[43]:
ID_x Date_x ID_y Date_y timedelta
2 RHD78 2022-08-12 RHD78 2022-08-09 3 days
3 RHD78 2022-08-12 RHD78 2022-08-11 1 days
4 RHD78 2022-08-12 RHD78 2022-08-12 0 days
5 RHD78 2022-08-12 RHD78 2022-08-14 -2 days
6 RHD78 2022-08-12 RHD78 2022-08-15 -3 days
27 BDW56 2022-03-23 BDW56 2022-03-22 1 days
28 BDW56 2022-03-23 BDW56 2022-03-23 0 days
29 BDW56 2022-03-23 BDW56 2022-03-27 -4 days
A:
suppose your Date column is datetime object, then we could do something like this:
d = pd.to_timedelta(4,'days')
df2['Date'] = df2['Date'].map(lambda x: pd.date_range(x-d,x+d))
df1.merge(df2.set_index('ID').explode('Date').reset_index())
>>>
'''
ID Date
0 RHD78 2022-08-09
1 RHD78 2022-08-11
2 RHD78 2022-08-12
3 RHD78 2022-08-14
4 RHD78 2022-08-15
5 BDW56 2022-03-22
6 BDW56 2022-03-23
7 BDW56 2022-03-27
A:
For this use case, you can avoid a cartesian join, or map - an efficient approach is to do an inner merge and filter after:
df2 = df2.assign(start = df2.Date -pd.Timedelta(days=4),
end = df2.Date + pd.Timedelta(days=4))
(df
.merge(df2.drop(columns='Date'), on='ID')
.loc[lambda d: d.Date.between(d.start, d.end, inclusive='both'), df.columns])
ID Date
2 RHD78 2022-08-09
3 RHD78 2022-08-11
4 RHD78 2022-08-12
5 RHD78 2022-08-14
6 RHD78 2022-08-15
11 BDW56 2022-03-22
12 BDW56 2022-03-23
13 BDW56 2022-03-27
|
Pandas: Merge two dataframes with timedelta
|
I am attempting to perform an inner merge of two large dataframes having columns 'ID' and 'Date'. A sample of each is shown below:
df1
ID Date
0 RHD78 2022-08-05
1 RHD78 2022-08-06
2 RHD78 2022-08-09
3 RHD78 2022-08-11
4 RHD78 2022-08-12
5 RHD78 2022-08-14
6 RHD78 2022-08-15
7 RHD78 2022-08-19
8 BDW56 2022-03-15
9 BDW56 2022-03-16
10 BDW56 2022-03-17
11 BDW56 2022-03-22
12 BDW56 2022-03-23
13 BDW56 2022-03-27
14 BDW56 2022-03-29
15 BDW56 2022-03-30
df2
ID Date
0 RHD78 2022-08-12
1 BDW56 2022-03-23
If I use the code df_result = pd.merge(df1, df2, how = 'inner', on='Date') then I get the two intersecting datapoints. However I am struggling to introduce a timedelta such that the resulting dataframe also includes data 4 days before and after the intersecting dates like so:
df_desired
ID Date
0 RHD78 8/9/2022
1 RHD78 8/11/2022
2 RHD78 8/12/2022
3 RHD78 8/14/2022
4 RHD78 8/15/2022
5 BDW56 3/22/2022
6 BDW56 3/23/2022
7 BDW56 3/27/2022
I tried to look into using merge_asof() function but my understanding is that it gets only the values that are closest to the date and not within a particular date range. I am learning pandas and python so I would appreciate if someone can help me solve this issue and provide simplified explanation of merge_asof().
|
[
"Using df as your first dataframe and df2 as the second, i followed the same procedure as in this answer, which was to cross merge them together and then filter after the merge has occurred. A cross merge is just a blanket merge, which combines each row pair from each dataframe together. This might not be applicable if your two dataframes are immensely large.\nmerge = df2.merge(df,how='cross')\nmerge['timedelta'] = pd.to_datetime(merge['Date_x']) - \\\n pd.to_datetime(merge['Date_y'])\nmerge_filt = merge.loc[merge['timedelta'].apply(lambda x: x.days).abs()<=4]\n\n\nprint(merge_filt)\nOut[43]: \n ID_x Date_x ID_y Date_y timedelta\n2 RHD78 2022-08-12 RHD78 2022-08-09 3 days\n3 RHD78 2022-08-12 RHD78 2022-08-11 1 days\n4 RHD78 2022-08-12 RHD78 2022-08-12 0 days\n5 RHD78 2022-08-12 RHD78 2022-08-14 -2 days\n6 RHD78 2022-08-12 RHD78 2022-08-15 -3 days\n27 BDW56 2022-03-23 BDW56 2022-03-22 1 days\n28 BDW56 2022-03-23 BDW56 2022-03-23 0 days\n29 BDW56 2022-03-23 BDW56 2022-03-27 -4 days\n\n",
"suppose your Date column is datetime object, then we could do something like this:\nd = pd.to_timedelta(4,'days')\ndf2['Date'] = df2['Date'].map(lambda x: pd.date_range(x-d,x+d))\ndf1.merge(df2.set_index('ID').explode('Date').reset_index())\n\n>>>\n'''\n ID Date\n0 RHD78 2022-08-09\n1 RHD78 2022-08-11\n2 RHD78 2022-08-12\n3 RHD78 2022-08-14\n4 RHD78 2022-08-15\n5 BDW56 2022-03-22\n6 BDW56 2022-03-23\n7 BDW56 2022-03-27\n\n",
"For this use case, you can avoid a cartesian join, or map - an efficient approach is to do an inner merge and filter after:\ndf2 = df2.assign(start = df2.Date -pd.Timedelta(days=4), \n end = df2.Date + pd.Timedelta(days=4))\n(df\n.merge(df2.drop(columns='Date'), on='ID')\n.loc[lambda d: d.Date.between(d.start, d.end, inclusive='both'), df.columns])\n\n ID Date\n2 RHD78 2022-08-09\n3 RHD78 2022-08-11\n4 RHD78 2022-08-12\n5 RHD78 2022-08-14\n6 RHD78 2022-08-15\n11 BDW56 2022-03-22\n12 BDW56 2022-03-23\n13 BDW56 2022-03-27\n\n"
] |
[
2,
2,
1
] |
[] |
[] |
[
"dataframe",
"merge",
"pandas",
"python",
"python_3.x"
] |
stackoverflow_0074567688_dataframe_merge_pandas_python_python_3.x.txt
|
Q:
sqlalchemy can't read null dates from sqlite3 (0000-00-00): ValueError: year is out of range
When I try to query a database containing dates such as 0000-00-00 00:00:00 with sqlachemy, I get ValueError: year is out of range.
Here's the db dump:
Here's the stacktrace:
File "/home/rob/.virtualenvs/calif/lib/python3.5/site-packages/sqlalchemy/engine/result.py" in items
163. return [(key, self[key]) for key in self.keys()]
File "/home/rob/.virtualenvs/calif/lib/python3.5/site-packages/sqlalchemy/engine/result.py" in <listcomp>
163. return [(key, self[key]) for key in self.keys()]
File "/home/rob/.virtualenvs/calif/lib/python3.5/site-packages/sqlalchemy/engine/result.py" in __getitem__
90. return processor(self._row[index])
File "/home/rob/.virtualenvs/calif/lib/python3.5/site-packages/sqlalchemy/processors.py" in process
48. return type_(*list(map(int, m.groups(0))))
Exception Type: ValueError at /
Exception Value: year is out of range
Is this normal ? Can sqlalchemy read dates like that ? Is this a python limitation ? Is there a workaround to keep the date as-is (not converting to None) ?
A:
Got the answer via inklesspen on IRC: Python datetime representation has minimum year and it's 1
A:
I was able to bypass the problem by using sqlalchemy.text
from sqlalchemy import text
with engine.connect() as conn:
result = conn.execute(text("select * from table"))
....
|
sqlalchemy can't read null dates from sqlite3 (0000-00-00): ValueError: year is out of range
|
When I try to query a database containing dates such as 0000-00-00 00:00:00 with sqlachemy, I get ValueError: year is out of range.
Here's the db dump:
Here's the stacktrace:
File "/home/rob/.virtualenvs/calif/lib/python3.5/site-packages/sqlalchemy/engine/result.py" in items
163. return [(key, self[key]) for key in self.keys()]
File "/home/rob/.virtualenvs/calif/lib/python3.5/site-packages/sqlalchemy/engine/result.py" in <listcomp>
163. return [(key, self[key]) for key in self.keys()]
File "/home/rob/.virtualenvs/calif/lib/python3.5/site-packages/sqlalchemy/engine/result.py" in __getitem__
90. return processor(self._row[index])
File "/home/rob/.virtualenvs/calif/lib/python3.5/site-packages/sqlalchemy/processors.py" in process
48. return type_(*list(map(int, m.groups(0))))
Exception Type: ValueError at /
Exception Value: year is out of range
Is this normal ? Can sqlalchemy read dates like that ? Is this a python limitation ? Is there a workaround to keep the date as-is (not converting to None) ?
|
[
"Got the answer via inklesspen on IRC: Python datetime representation has minimum year and it's 1\n",
"I was able to bypass the problem by using sqlalchemy.text\nfrom sqlalchemy import text\n\nwith engine.connect() as conn:\n result = conn.execute(text(\"select * from table\"))\n ....\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"python",
"sqlalchemy"
] |
stackoverflow_0040118266_python_sqlalchemy.txt
|
Q:
BME280 on Raspberry Pi using Python 3 - Odd first reading
I have 2 x Pimoroni BME280 and they both produce the same initial reading of 21.95*C 698.09hPa 76.34% humidity.
Using this simple code
import time
from smbus2 import SMBus
from bme280 import BME280
bus = SMBus(1)
bme280 = BME280(i2c_dev=bus)
while True:
temperature = bme280.get_temperature()
pressure = bme280.get_pressure()
humidity = bme280.get_humidity()
print('{:05.2f}*C {:05.2f}hPa {:05.2f}%'.format(temperature, pressure, humidity))
time.sleep(1)
and I always get as the first line of output as...
21.95*C 698.09hPa 76.34%
followed by the correct data for example...
18.70*C 993.54hPa 55.88%
18.70*C 993.53hPa 56.12%
18.71*C 993.54hPa 56.06%
18.71*C 993.54hPa 55.95%
Does anybody know why this is?
Currently I have the same thing on both of my BME280 so presume it's some sort of initialization thing on the first reading which must be discarded. If I run my program the only solution I can see it to ask twice what thr readings are and discard the first reading..
Thanks for reading and helping...
A:
I would presume that this is caused due to an initial transient value being outputted by the sensor as a result of initialising your sensor.
It would be interesting to see how an Arduino would handle the initialisation process
vis-à-vis said transient value with your sensor.
As you said, if your continuous readings are 'correct', I would try to perhaps delay the output process or omit the first reading in some way or another.
|
BME280 on Raspberry Pi using Python 3 - Odd first reading
|
I have 2 x Pimoroni BME280 and they both produce the same initial reading of 21.95*C 698.09hPa 76.34% humidity.
Using this simple code
import time
from smbus2 import SMBus
from bme280 import BME280
bus = SMBus(1)
bme280 = BME280(i2c_dev=bus)
while True:
temperature = bme280.get_temperature()
pressure = bme280.get_pressure()
humidity = bme280.get_humidity()
print('{:05.2f}*C {:05.2f}hPa {:05.2f}%'.format(temperature, pressure, humidity))
time.sleep(1)
and I always get as the first line of output as...
21.95*C 698.09hPa 76.34%
followed by the correct data for example...
18.70*C 993.54hPa 55.88%
18.70*C 993.53hPa 56.12%
18.71*C 993.54hPa 56.06%
18.71*C 993.54hPa 55.95%
Does anybody know why this is?
Currently I have the same thing on both of my BME280 so presume it's some sort of initialization thing on the first reading which must be discarded. If I run my program the only solution I can see it to ask twice what thr readings are and discard the first reading..
Thanks for reading and helping...
|
[
"I would presume that this is caused due to an initial transient value being outputted by the sensor as a result of initialising your sensor.\nIt would be interesting to see how an Arduino would handle the initialisation process\nvis-à-vis said transient value with your sensor.\nAs you said, if your continuous readings are 'correct', I would try to perhaps delay the output process or omit the first reading in some way or another.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"raspberry_pi"
] |
stackoverflow_0074566028_python_raspberry_pi.txt
|
Q:
How to count number of points inside a circle
I got this plot and I want to divide this plot into many different circles and need how many points in each circle.
I am trying to plot radius of the circle with how many number of points inside the circle.
A:
Intuition:- Finding the distance between two points. (i.e sqrt((x2-x1)**2+(y2-y1)**2)) [Euclidean Formula]
If Distance>Radius than point is outside the circle
If Distance=Radius than point is on the circle
If Distance<Radius than point is inside the circle
Code:-
import math
# Lets say the circle points are x=2 y=3
x,y=2,3
# Radius of a Circle radius=4
radius=4
# Given points to check -:
lis=[(-1,1),(4,3),(5,4),(9,10),(1,2),(2,7)]
res=[]
for x1,y1 in lis: # x1,y1 points to check is it inside or not
if math.sqrt((x1-x)**2+(y1-y)**2)<radius: #Note use "<=radius" if you want point which is on the circle also
res.append((x1,y1))
print(res) #The points which are inside in the circle
Output:-
[(-1, 1), (4, 3), (5, 4), (1, 2)]
|
How to count number of points inside a circle
|
I got this plot and I want to divide this plot into many different circles and need how many points in each circle.
I am trying to plot radius of the circle with how many number of points inside the circle.
|
[
"Intuition:- Finding the distance between two points. (i.e sqrt((x2-x1)**2+(y2-y1)**2)) [Euclidean Formula]\n\n\nIf Distance>Radius than point is outside the circle\nIf Distance=Radius than point is on the circle\nIf Distance<Radius than point is inside the circle\n\n\nCode:-\nimport math\n# Lets say the circle points are x=2 y=3\nx,y=2,3\n# Radius of a Circle radius=4\nradius=4\n# Given points to check -:\nlis=[(-1,1),(4,3),(5,4),(9,10),(1,2),(2,7)]\nres=[]\nfor x1,y1 in lis: # x1,y1 points to check is it inside or not\n if math.sqrt((x1-x)**2+(y1-y)**2)<radius: #Note use \"<=radius\" if you want point which is on the circle also\n res.append((x1,y1))\nprint(res) #The points which are inside in the circle\n\nOutput:-\n[(-1, 1), (4, 3), (5, 4), (1, 2)]\n\n"
] |
[
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074569052_python.txt
|
Q:
Plotly How to create a line animation with column name in x axis and column data in y axis?
I have a data frame as shown below.
Device_ID Die_Version Temp(deg) sup(V) freq sensitivity THD_94 THD_100 THD_105 THD_110 THD_112 THD_114 THD_115 THD_116 THD_118 THD_120
TTM_041 0x16 -40 1.8 0.8 -25.041 0.009 0.01 0.071 0.206 0.143 0.099 0.1 0.296 4.243 11.888
TTM_041 0x16 -40 1.8 2.4 -25.041 0.009 0.01 0.075 0.206 0.143 0.1 0.101 0.245 4.495 11.728
TTM_041 0x16 -40 1.98 0.8 -25.04 0.009 0.01 0.076 0.207 0.143 0.1 0.102 0.313 4.484 11.844
I need to plot the graph in such a way that column names (THD_94 THD_100 THD_105 THD_110 THD_112 THD_114 THD_115 THD_116 THD_118 THD_120) needs to come in the X axis and its values need to come in the Y axis.
I tried with below code, but it is not working as expected.
fig = px.line(df_MM_SPEC, x=px.Constant('col'), y=['THD_94', 'THD_100'], animation_frame='Device_ID')
# fig.update_layout(barmode='group')
fig.show()
A:
reshaped_df = df[[col for col in df.columns if 'THD' in col]].T.stack().reset_index()
gives us some reshaped data that looks like this:
level_0 level_1 0
0 THD_94 0 0.009
1 THD_94 1 0.009
2 THD_94 2 0.009
3 THD_100 0 0.010
4 THD_100 1 0.010
5 THD_100 2 0.010
6 THD_105 0 0.071
7 THD_105 1 0.075
8 THD_105 2 0.076
9 THD_110 0 0.206
10 THD_110 1 0.206
11 THD_110 2 0.207
12 THD_112 0 0.143
13 THD_112 1 0.143
14 THD_112 2 0.143
15 THD_114 0 0.099
16 THD_114 1 0.100
17 THD_114 2 0.100
18 THD_115 0 0.100
19 THD_115 1 0.101
20 THD_115 2 0.102
21 THD_116 0 0.296
22 THD_116 1 0.245
23 THD_116 2 0.313
24 THD_118 0 4.243
25 THD_118 1 4.495
26 THD_118 2 4.484
27 THD_120 0 11.888
28 THD_120 1 11.728
29 THD_120 2 11.844
It might be wise to rename your columns to something more logical, but I'll leave that to the reader. With the reshaped data, it's pretty trivial to animate:
px.line(reshaped_df, x='level_0', y=0, animation_frame='level_1')
|
Plotly How to create a line animation with column name in x axis and column data in y axis?
|
I have a data frame as shown below.
Device_ID Die_Version Temp(deg) sup(V) freq sensitivity THD_94 THD_100 THD_105 THD_110 THD_112 THD_114 THD_115 THD_116 THD_118 THD_120
TTM_041 0x16 -40 1.8 0.8 -25.041 0.009 0.01 0.071 0.206 0.143 0.099 0.1 0.296 4.243 11.888
TTM_041 0x16 -40 1.8 2.4 -25.041 0.009 0.01 0.075 0.206 0.143 0.1 0.101 0.245 4.495 11.728
TTM_041 0x16 -40 1.98 0.8 -25.04 0.009 0.01 0.076 0.207 0.143 0.1 0.102 0.313 4.484 11.844
I need to plot the graph in such a way that column names (THD_94 THD_100 THD_105 THD_110 THD_112 THD_114 THD_115 THD_116 THD_118 THD_120) needs to come in the X axis and its values need to come in the Y axis.
I tried with below code, but it is not working as expected.
fig = px.line(df_MM_SPEC, x=px.Constant('col'), y=['THD_94', 'THD_100'], animation_frame='Device_ID')
# fig.update_layout(barmode='group')
fig.show()
|
[
"reshaped_df = df[[col for col in df.columns if 'THD' in col]].T.stack().reset_index()\n\ngives us some reshaped data that looks like this:\n level_0 level_1 0\n0 THD_94 0 0.009\n1 THD_94 1 0.009\n2 THD_94 2 0.009\n3 THD_100 0 0.010\n4 THD_100 1 0.010\n5 THD_100 2 0.010\n6 THD_105 0 0.071\n7 THD_105 1 0.075\n8 THD_105 2 0.076\n9 THD_110 0 0.206\n10 THD_110 1 0.206\n11 THD_110 2 0.207\n12 THD_112 0 0.143\n13 THD_112 1 0.143\n14 THD_112 2 0.143\n15 THD_114 0 0.099\n16 THD_114 1 0.100\n17 THD_114 2 0.100\n18 THD_115 0 0.100\n19 THD_115 1 0.101\n20 THD_115 2 0.102\n21 THD_116 0 0.296\n22 THD_116 1 0.245\n23 THD_116 2 0.313\n24 THD_118 0 4.243\n25 THD_118 1 4.495\n26 THD_118 2 4.484\n27 THD_120 0 11.888\n28 THD_120 1 11.728\n29 THD_120 2 11.844\n\nIt might be wise to rename your columns to something more logical, but I'll leave that to the reader. With the reshaped data, it's pretty trivial to animate:\npx.line(reshaped_df, x='level_0', y=0, animation_frame='level_1')\n\n\n"
] |
[
2
] |
[] |
[] |
[
"pandas",
"plot",
"plotly",
"plotly_dash",
"python"
] |
stackoverflow_0074570406_pandas_plot_plotly_plotly_dash_python.txt
|
Q:
Local variable value is not used in recursion
Here is my snippet:
core = client.CoreV1Api()
apps = client.AppsV1Api()
def get_pod_parent(resource, tmp):
if resource.metadata.owner_references:
parrent = eval(f"apps.read_namespaced_{re.sub(r'(?<!^)(?=[A-Z])', '_', resource.metadata.owner_references[0].kind).lower()}")(
resource.metadata.owner_references[0].name,
resource.metadata.namespace
)
get_pod_parent(parrent, tmp)
else:
#print(resource) it prints the resource which I need to take
tmp = resource #Local variable 'tmp' value is not used
pod = core.read_namespaced_pod('test_name', 'test_namespace')
last_parrent = None
test = get_pod_parent(pod, last_parrent)
print(last_parrent) # It prints None
Why does it print None? I can't understand! I need to store the resource when it gets into the else. The resource is there, but I cant store it somehow. Is there someone who can explain what is going on and how can I take the needed resource outside of the function?
A:
Python uses pass by value in this case therefore when you pass the variable last_parrent it passes the value of the variable and any modification won't effect last_parrent. What you probably want to do is write
return resource
Then when you call the function at the bottom will contain the value of resource when the function has run so if you print(test) you'll get what you need.
HOWEVER if you want the function to keep running after you have assigned it look it generators (using yield instead of return)
A:
@chrslg You are right! I forgot that we are passing the values of arguments, not their references. So that is why I change the things a little bit in order to take the needed data.
def get_pod_parent(resource, store):
if resource.metadata.owner_references:
parrent = eval(
f"apps.read_namespaced_{re.sub(r'(?<!^)(?=[A-Z])', '_', resource.metadata.owner_references[0].kind).lower()}")(
resource.metadata.owner_references[0].name,
resource.metadata.namespace
)
get_pod_parent(parrent, store)
else:
store.update({'name': resource.metadata.name, 'namespace': resource.metadata.name})
pod = core.read_namespaced_pod('test_name', 'test_namespace')
store = {}
get_pod_parent(pod, store)
print(store)
So now the data which I need is there stored in store var. Thank you
|
Local variable value is not used in recursion
|
Here is my snippet:
core = client.CoreV1Api()
apps = client.AppsV1Api()
def get_pod_parent(resource, tmp):
if resource.metadata.owner_references:
parrent = eval(f"apps.read_namespaced_{re.sub(r'(?<!^)(?=[A-Z])', '_', resource.metadata.owner_references[0].kind).lower()}")(
resource.metadata.owner_references[0].name,
resource.metadata.namespace
)
get_pod_parent(parrent, tmp)
else:
#print(resource) it prints the resource which I need to take
tmp = resource #Local variable 'tmp' value is not used
pod = core.read_namespaced_pod('test_name', 'test_namespace')
last_parrent = None
test = get_pod_parent(pod, last_parrent)
print(last_parrent) # It prints None
Why does it print None? I can't understand! I need to store the resource when it gets into the else. The resource is there, but I cant store it somehow. Is there someone who can explain what is going on and how can I take the needed resource outside of the function?
|
[
"Python uses pass by value in this case therefore when you pass the variable last_parrent it passes the value of the variable and any modification won't effect last_parrent. What you probably want to do is write\nreturn resource\n\nThen when you call the function at the bottom will contain the value of resource when the function has run so if you print(test) you'll get what you need.\nHOWEVER if you want the function to keep running after you have assigned it look it generators (using yield instead of return)\n",
"@chrslg You are right! I forgot that we are passing the values of arguments, not their references. So that is why I change the things a little bit in order to take the needed data.\ndef get_pod_parent(resource, store):\nif resource.metadata.owner_references:\n parrent = eval(\n f\"apps.read_namespaced_{re.sub(r'(?<!^)(?=[A-Z])', '_', resource.metadata.owner_references[0].kind).lower()}\")(\n resource.metadata.owner_references[0].name,\n resource.metadata.namespace\n\n )\n get_pod_parent(parrent, store)\nelse:\n store.update({'name': resource.metadata.name, 'namespace': resource.metadata.name})\npod = core.read_namespaced_pod('test_name', 'test_namespace')\nstore = {}\nget_pod_parent(pod, store)\nprint(store) \n\nSo now the data which I need is there stored in store var. Thank you\n"
] |
[
1,
0
] |
[] |
[] |
[
"arguments",
"parameter_passing",
"python"
] |
stackoverflow_0074571792_arguments_parameter_passing_python.txt
|
Q:
Scrapy images do not download
The scraper runs and finds the urls of the images, but it won't download the images for some reason.
It prints the information of the Items in the terminal, but nothing gets recorded.
I have tried all the combinations of settings I could find on SO, but I have been unlucky so far. This scraper used to work it might be linked to the updates on the recent version of scrapy
I run the command scrapy runspider /path/to/myspider.py
Versions:
scrapy==2.7.1
python==3.10.8
settings.py
BOT_NAME = "my_bot"
SPIDER_MODULES = ["my_bot.spiders"]
NEWSPIDER_MODULE = "my_bot.spiders"
# Crawl responsibly by identifying yourself (and your website) on the user-agent
# USER_AGENT = 'ooshot_marketplace (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
# Configure maximum concurrent requests performed by Scrapy (default: 16)
# CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
# CONCURRENT_REQUESTS_PER_DOMAIN = 16
# CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
COOKIES_ENABLED = True
# Disable Telnet Console (enabled by default)
# TELNETCONSOLE_ENABLED = False
# Override the default request headers:
# DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
# }
# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
SPIDER_MIDDLEWARES = {
"my_bot.middlewares.OoshotMarketplaceSpiderMiddleware": 543,
}
# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
"my_bot.middlewares.OoshotMarketplaceDownloaderMiddleware": 543,
}
# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
# EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
# }
# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# ITEM_PIPELINES = {
# 'my_bot.pipelines.MyPipeline': 300,
# }
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
# AUTOTHROTTLE_ENABLED = True
# The initial download delay
# AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
# AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
# AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
# AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
# HTTPCACHE_ENABLED = True
# HTTPCACHE_EXPIRATION_SECS = 0
# HTTPCACHE_DIR = 'httpcache'
# HTTPCACHE_IGNORE_HTTP_CODES = []
# HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
# Set settings whose default value is deprecated to a future-proof value
REQUEST_FINGERPRINTER_IMPLEMENTATION = "2.7"
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
# DUPEFILTER_DEBUG = True
# ITEM_PIPELINES = {"scrapy.pipelines.images.ImagesPipeline": 1}
ITEM_PIPELINES = {"crawler.pipelines.SessionImagesPipeline": 1}
IMAGES_STORE = "images"
IMAGES_URLS_FIELD = "image_urls" # copy verbatim
IMAGES_RESULT_FIELD = "images" # copy verbatim
my_spider.py
import os
import scrapy
import sys
class ImageItem(scrapy.Item):
# ... other item fields ...
image_urls = scrapy.Field()
photographer_name = scrapy.Field()
category_name = scrapy.Field()
class MySpider(scrapy.Spider):
name = "myspider"
start_urls = ["http://my-url/"]
http_user = "my-user"
http_pass = "my-passwd"
def parse(self, response):
photographers_urls = response.css(".search-result-name a::attr(href)").extract()
for photographer_url in photographers_urls:
yield scrapy.Request(
response.urljoin(photographer_url), callback=self.parse_photographer
)
photographers_pages_urls = response.css(".pagination a::attr(href)").extract()
for photographer_page_url in photographers_pages_urls:
yield scrapy.Request(
response.urljoin(photographer_page_url), callback=self.parse
)
def parse_photographer(self, response):
photographer_name = os.path.basename(response.url)
categories_urls = response.css(
".profile-header-categories a::attr(href)"
).extract()
for category_url in categories_urls:
yield scrapy.Request(
response.urljoin(category_url),
callback=self.parse_category,
meta={"photographer_name": photographer_name},
)
def parse_category(self, response):
category_name = os.path.basename(response.url)
photos_urls = response.css(".grid-col a::attr(href)").extract()
for photo_url in photos_urls:
yield scrapy.Request(
response.urljoin(photo_url),
callback=self.save_photo,
meta={
"photographer_name": response.meta["photographer_name"],
"category_name": category_name,
},
)
def save_photo(self, response):
image_url = response.css(".js-photo-details-photo::attr(src)").extract_first()
image_item = ImageItem()
image_item["image_urls"] = [response.urljoin(image_url)]
image_item["photographer_name"] = response.meta["photographer_name"]
image_item["category_name"] = response.meta["category_name"]
yield image_item
pipeline.py
import scrapy
import os
from scrapy.pipelines.images import ImagesPipeline, ImageException
class SessionImagesPipeline(ImagesPipeline):
# # Photographers function
def item_completed(self, results, item, info):
# iterate over the local file paths of all downloaded images
for result in [x for ok, x in results if ok]:
path = result["path"]
# here we create the session-path where the files should be in the end
# you'll have to change this path creation depending on your needs
# settings = get_project_settings()
storage = "/my/path/images"
category_path = os.path.join(storage, item["category_name"])
if not os.path.isdir(category_path):
os.mkdir(category_path)
photographer_path = os.path.join(category_path, item["photographer_name"])
if not os.path.isdir(photographer_path):
os.mkdir(photographer_path)
target_path = os.path.join(photographer_path, os.path.basename(path))
path = os.path.join(storage, path)
# try to move the file and raise exception if not possible
if not os.rename(path, target_path):
raise ImageException("Could not move image to target folder")
# here we'll write out the result with the new path,
# if there is a result field on the item (just like the original code does)
if self.IMAGES_RESULT_FIELD in item.fields:
result["path"] = target_path
item[self.IMAGES_RESULT_FIELD].append(result)
return item
A:
You are missing the images result field in your image item.
class ImageItem(scrapy.Item):
# ... other item fields ...
image_urls = scrapy.Field()
photographer_name = scrapy.Field()
category_name = scrapy.Field()
images = scrapy.Field() # <----- add this
|
Scrapy images do not download
|
The scraper runs and finds the urls of the images, but it won't download the images for some reason.
It prints the information of the Items in the terminal, but nothing gets recorded.
I have tried all the combinations of settings I could find on SO, but I have been unlucky so far. This scraper used to work it might be linked to the updates on the recent version of scrapy
I run the command scrapy runspider /path/to/myspider.py
Versions:
scrapy==2.7.1
python==3.10.8
settings.py
BOT_NAME = "my_bot"
SPIDER_MODULES = ["my_bot.spiders"]
NEWSPIDER_MODULE = "my_bot.spiders"
# Crawl responsibly by identifying yourself (and your website) on the user-agent
# USER_AGENT = 'ooshot_marketplace (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
# Configure maximum concurrent requests performed by Scrapy (default: 16)
# CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
# CONCURRENT_REQUESTS_PER_DOMAIN = 16
# CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
COOKIES_ENABLED = True
# Disable Telnet Console (enabled by default)
# TELNETCONSOLE_ENABLED = False
# Override the default request headers:
# DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
# }
# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
SPIDER_MIDDLEWARES = {
"my_bot.middlewares.OoshotMarketplaceSpiderMiddleware": 543,
}
# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
"my_bot.middlewares.OoshotMarketplaceDownloaderMiddleware": 543,
}
# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
# EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
# }
# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# ITEM_PIPELINES = {
# 'my_bot.pipelines.MyPipeline': 300,
# }
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
# AUTOTHROTTLE_ENABLED = True
# The initial download delay
# AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
# AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
# AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
# AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
# HTTPCACHE_ENABLED = True
# HTTPCACHE_EXPIRATION_SECS = 0
# HTTPCACHE_DIR = 'httpcache'
# HTTPCACHE_IGNORE_HTTP_CODES = []
# HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
# Set settings whose default value is deprecated to a future-proof value
REQUEST_FINGERPRINTER_IMPLEMENTATION = "2.7"
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
# DUPEFILTER_DEBUG = True
# ITEM_PIPELINES = {"scrapy.pipelines.images.ImagesPipeline": 1}
ITEM_PIPELINES = {"crawler.pipelines.SessionImagesPipeline": 1}
IMAGES_STORE = "images"
IMAGES_URLS_FIELD = "image_urls" # copy verbatim
IMAGES_RESULT_FIELD = "images" # copy verbatim
my_spider.py
import os
import scrapy
import sys
class ImageItem(scrapy.Item):
# ... other item fields ...
image_urls = scrapy.Field()
photographer_name = scrapy.Field()
category_name = scrapy.Field()
class MySpider(scrapy.Spider):
name = "myspider"
start_urls = ["http://my-url/"]
http_user = "my-user"
http_pass = "my-passwd"
def parse(self, response):
photographers_urls = response.css(".search-result-name a::attr(href)").extract()
for photographer_url in photographers_urls:
yield scrapy.Request(
response.urljoin(photographer_url), callback=self.parse_photographer
)
photographers_pages_urls = response.css(".pagination a::attr(href)").extract()
for photographer_page_url in photographers_pages_urls:
yield scrapy.Request(
response.urljoin(photographer_page_url), callback=self.parse
)
def parse_photographer(self, response):
photographer_name = os.path.basename(response.url)
categories_urls = response.css(
".profile-header-categories a::attr(href)"
).extract()
for category_url in categories_urls:
yield scrapy.Request(
response.urljoin(category_url),
callback=self.parse_category,
meta={"photographer_name": photographer_name},
)
def parse_category(self, response):
category_name = os.path.basename(response.url)
photos_urls = response.css(".grid-col a::attr(href)").extract()
for photo_url in photos_urls:
yield scrapy.Request(
response.urljoin(photo_url),
callback=self.save_photo,
meta={
"photographer_name": response.meta["photographer_name"],
"category_name": category_name,
},
)
def save_photo(self, response):
image_url = response.css(".js-photo-details-photo::attr(src)").extract_first()
image_item = ImageItem()
image_item["image_urls"] = [response.urljoin(image_url)]
image_item["photographer_name"] = response.meta["photographer_name"]
image_item["category_name"] = response.meta["category_name"]
yield image_item
pipeline.py
import scrapy
import os
from scrapy.pipelines.images import ImagesPipeline, ImageException
class SessionImagesPipeline(ImagesPipeline):
# # Photographers function
def item_completed(self, results, item, info):
# iterate over the local file paths of all downloaded images
for result in [x for ok, x in results if ok]:
path = result["path"]
# here we create the session-path where the files should be in the end
# you'll have to change this path creation depending on your needs
# settings = get_project_settings()
storage = "/my/path/images"
category_path = os.path.join(storage, item["category_name"])
if not os.path.isdir(category_path):
os.mkdir(category_path)
photographer_path = os.path.join(category_path, item["photographer_name"])
if not os.path.isdir(photographer_path):
os.mkdir(photographer_path)
target_path = os.path.join(photographer_path, os.path.basename(path))
path = os.path.join(storage, path)
# try to move the file and raise exception if not possible
if not os.rename(path, target_path):
raise ImageException("Could not move image to target folder")
# here we'll write out the result with the new path,
# if there is a result field on the item (just like the original code does)
if self.IMAGES_RESULT_FIELD in item.fields:
result["path"] = target_path
item[self.IMAGES_RESULT_FIELD].append(result)
return item
|
[
"You are missing the images result field in your image item.\nclass ImageItem(scrapy.Item):\n\n # ... other item fields ...\n image_urls = scrapy.Field()\n photographer_name = scrapy.Field()\n category_name = scrapy.Field()\n images = scrapy.Field() # <----- add this\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"python_3.x",
"scrapy",
"web_scraping"
] |
stackoverflow_0074567077_python_python_3.x_scrapy_web_scraping.txt
|
Q:
How to add in react-native script in python?
Also i have got a new project, where nedded make a voice recognition (speech-to-text) , but i have't find a worked library in react-native. How can i connect scripts in python to react native project?
I only find how to make autorizathion in python, but by me it was maked in JS
A:
If your python app is going to be running on a separate machine to the react-native app (so it is running on a server). I would write a small server implementation ontop of the python app using something like flask which sends back a JSON then you can follow the tutorial here: https://reactnative.dev/docs/network Which talks about making http requests and parsing the response. So in a REST api manner
If you are talking about client side python running in tandem with react-native on a mobile device. That would be pretty difficult to accomplish as in production the react compile is compiling into native code by handling JavaScript/JSX and not python. Someone may have an answer on this last part
A:
You can embed Python into React-Native, but it's really tricky. I suggest you go with the other answer using Server-Client Architecture.
However if you really have no other choice.
Then you can create a Turbo Module in C++
Use a python interpreter in C++ to call and use python libraries/scripts use this embedding tutorial
Finally call this native module in your react-native application to make use of the python scripts.
|
How to add in react-native script in python?
|
Also i have got a new project, where nedded make a voice recognition (speech-to-text) , but i have't find a worked library in react-native. How can i connect scripts in python to react native project?
I only find how to make autorizathion in python, but by me it was maked in JS
|
[
"If your python app is going to be running on a separate machine to the react-native app (so it is running on a server). I would write a small server implementation ontop of the python app using something like flask which sends back a JSON then you can follow the tutorial here: https://reactnative.dev/docs/network Which talks about making http requests and parsing the response. So in a REST api manner\nIf you are talking about client side python running in tandem with react-native on a mobile device. That would be pretty difficult to accomplish as in production the react compile is compiling into native code by handling JavaScript/JSX and not python. Someone may have an answer on this last part\n",
"You can embed Python into React-Native, but it's really tricky. I suggest you go with the other answer using Server-Client Architecture.\nHowever if you really have no other choice.\n\nThen you can create a Turbo Module in C++\nUse a python interpreter in C++ to call and use python libraries/scripts use this embedding tutorial\nFinally call this native module in your react-native application to make use of the python scripts.\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"javascript",
"python",
"react_native"
] |
stackoverflow_0074571737_javascript_python_react_native.txt
|
Q:
tabula error 'list' object has no attribute 'to_excel'
I tried to convert PDF file that contains the data table to excel file.
Here is my cord.
import tabula
# Read PDF File
df = tabula.read_pdf("files/Seniority List 2018 19.pdf", pages = 1)
# Convert into Excel File
df.to_excel('files/excel.xlsx')
but error occurred.
AttributeError Traceback (most recent call last)
Input In [5], in <cell line: 9>()
6 df = tabula.read_pdf("files/Seniority List 2018 19.pdf", pages = 1)
8 # # Convert into Excel File
----> 9 df.to_excel('files/excel.xlsx')
AttributeError: 'list' object has no attribute 'to_excel'
PDF is from here
https://www.docdroid.net/jTWmB15/seniority-list-2018-19-pdf
How can I use 'to_excel'??
I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you
A:
df[0].to_excel('files/excel.xlsx')
tabula returns a list of possible table
A:
instead of using df = tabula.read_pdf('file.pdf', pages = '1')
Use df = tabula.read_pdf('file.pdf', pages = '1')[0]
|
tabula error 'list' object has no attribute 'to_excel'
|
I tried to convert PDF file that contains the data table to excel file.
Here is my cord.
import tabula
# Read PDF File
df = tabula.read_pdf("files/Seniority List 2018 19.pdf", pages = 1)
# Convert into Excel File
df.to_excel('files/excel.xlsx')
but error occurred.
AttributeError Traceback (most recent call last)
Input In [5], in <cell line: 9>()
6 df = tabula.read_pdf("files/Seniority List 2018 19.pdf", pages = 1)
8 # # Convert into Excel File
----> 9 df.to_excel('files/excel.xlsx')
AttributeError: 'list' object has no attribute 'to_excel'
PDF is from here
https://www.docdroid.net/jTWmB15/seniority-list-2018-19-pdf
How can I use 'to_excel'??
I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you
|
[
"df[0].to_excel('files/excel.xlsx')\n\ntabula returns a list of possible table\n",
"instead of using df = tabula.read_pdf('file.pdf', pages = '1')\nUse df = tabula.read_pdf('file.pdf', pages = '1')[0]\n"
] |
[
0,
0
] |
[] |
[] |
[
"python",
"tabula"
] |
stackoverflow_0074572159_python_tabula.txt
|
Q:
Set environment variable in PyCharm to None value
During debug sessions in PyCharm I need to set some environment variables to None value.
There is good explanation on how to set Run/Debug configuration environment variables in PyCharm How to set environment variables in PyCharm?, but they set each variable to specific value.
It is possible to delete environment variable from Run/Debug configuration setting it to None, but I would prefer to keep the variable's name inside PyCharm configuration settings for further use.
So how I set it to python None?
A:
You can't. Environment variables behave as Windows determines, and Windows doesn't provide an equivalent of Python's None. If you do SET MYVAR= at a console prompt, Windows will delete the variable. There is little that PyCharm can do to change that.
But there is nothing to stop you having an environment variable called #MYVAR that is set to the old value of MYVAR.
A:
I found the solution. I just have to create different run/debug configurations with different environment variables.
|
Set environment variable in PyCharm to None value
|
During debug sessions in PyCharm I need to set some environment variables to None value.
There is good explanation on how to set Run/Debug configuration environment variables in PyCharm How to set environment variables in PyCharm?, but they set each variable to specific value.
It is possible to delete environment variable from Run/Debug configuration setting it to None, but I would prefer to keep the variable's name inside PyCharm configuration settings for further use.
So how I set it to python None?
|
[
"You can't. Environment variables behave as Windows determines, and Windows doesn't provide an equivalent of Python's None. If you do SET MYVAR= at a console prompt, Windows will delete the variable. There is little that PyCharm can do to change that.\nBut there is nothing to stop you having an environment variable called #MYVAR that is set to the old value of MYVAR.\n",
"I found the solution. I just have to create different run/debug configurations with different environment variables.\n"
] |
[
1,
0
] |
[] |
[] |
[
"pycharm",
"python"
] |
stackoverflow_0074570140_pycharm_python.txt
|
Q:
Mark all the columns after the first occurrence of an event as NaN in pandas
I want to mark all the columns after the first occurrence of an event(ONE-OFF) as NaN in pandas dataframe
Note: There can be multiple rows in this df and ONE-OFF can appear at any column or may not appear at all
input_df = pd.DataFrame(
{
1: {'15': 'Normal'},
2: {'15': 'Normal'},
3: {'15': 'Normal'},
4: {'15': 'ONE-OFF'},
5: {'15': 'Normal'},
6: {'15': 'Normal'},
}
)
All columns for this row should be NaN after first occurrence of ONE-OFF
output_df = pd.DataFrame(
{
1: {'15': 'Normal'},
2: {'15': 'Normal'},
3: {'15': 'Normal'},
4: {'15': 'ONE-OFF'},
5: {'15': np.nan},
6: {'15': np.nan},
}
)
Please suggest
Thanks
A:
Compare values and use DataFrame.shift with DataFrame.cummax for mask and replace NaNs by DataFrame.mask for replace values after first matched value per rows separately:
print (input_df)
1 2 3 4 5 6
0 Normal Normal Normal ONE-OFF Normal Normal
1 ONE-OFF Normal Normal Normal Normal Normal
2 Normal Normal Normal ONE-OFF Normal Normal
3 Normal ONE-OFF Normal Normal Normal Normal
4 Normal Normal Normal Normal Normal ONE-OFF
df = input_df.mask(input_df.shift(axis=1).eq('ONE-OFF').cummax(axis=1))
print (df)
1 2 3 4 5 6
0 Normal Normal Normal ONE-OFF NaN NaN
1 ONE-OFF NaN NaN NaN NaN NaN
2 Normal Normal Normal ONE-OFF NaN NaN
3 Normal ONE-OFF NaN NaN NaN NaN
4 Normal Normal Normal Normal Normal ONE-OFF
If need set all columns by first occurncy in any column use DataFrame.loc with DataFrame.any for mask:
m = input_df.shift(axis=1).eq('ONE-OFF').cummax(axis=1).any()
input_df.loc[:, m] = np.nan
print (input_df)
1 2 3 4 5 6
0 Normal NaN NaN NaN NaN NaN
1 ONE-OFF NaN NaN NaN NaN NaN
2 Normal NaN NaN NaN NaN NaN
3 Normal NaN NaN NaN NaN NaN
4 Normal NaN NaN NaN NaN NaN
|
Mark all the columns after the first occurrence of an event as NaN in pandas
|
I want to mark all the columns after the first occurrence of an event(ONE-OFF) as NaN in pandas dataframe
Note: There can be multiple rows in this df and ONE-OFF can appear at any column or may not appear at all
input_df = pd.DataFrame(
{
1: {'15': 'Normal'},
2: {'15': 'Normal'},
3: {'15': 'Normal'},
4: {'15': 'ONE-OFF'},
5: {'15': 'Normal'},
6: {'15': 'Normal'},
}
)
All columns for this row should be NaN after first occurrence of ONE-OFF
output_df = pd.DataFrame(
{
1: {'15': 'Normal'},
2: {'15': 'Normal'},
3: {'15': 'Normal'},
4: {'15': 'ONE-OFF'},
5: {'15': np.nan},
6: {'15': np.nan},
}
)
Please suggest
Thanks
|
[
"Compare values and use DataFrame.shift with DataFrame.cummax for mask and replace NaNs by DataFrame.mask for replace values after first matched value per rows separately:\nprint (input_df)\n 1 2 3 4 5 6\n0 Normal Normal Normal ONE-OFF Normal Normal\n1 ONE-OFF Normal Normal Normal Normal Normal\n2 Normal Normal Normal ONE-OFF Normal Normal\n3 Normal ONE-OFF Normal Normal Normal Normal\n4 Normal Normal Normal Normal Normal ONE-OFF\n\ndf = input_df.mask(input_df.shift(axis=1).eq('ONE-OFF').cummax(axis=1))\nprint (df)\n 1 2 3 4 5 6\n0 Normal Normal Normal ONE-OFF NaN NaN\n1 ONE-OFF NaN NaN NaN NaN NaN\n2 Normal Normal Normal ONE-OFF NaN NaN\n3 Normal ONE-OFF NaN NaN NaN NaN\n4 Normal Normal Normal Normal Normal ONE-OFF\n\nIf need set all columns by first occurncy in any column use DataFrame.loc with DataFrame.any for mask:\nm = input_df.shift(axis=1).eq('ONE-OFF').cummax(axis=1).any()\n\ninput_df.loc[:, m] = np.nan\nprint (input_df)\n 1 2 3 4 5 6\n0 Normal NaN NaN NaN NaN NaN\n1 ONE-OFF NaN NaN NaN NaN NaN\n2 Normal NaN NaN NaN NaN NaN\n3 Normal NaN NaN NaN NaN NaN\n4 Normal NaN NaN NaN NaN NaN\n\n"
] |
[
0
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074572495_pandas_python.txt
|
Q:
remove prefix in all column names
I would like to remove the prefix from all column names in a dataframe.
I tried creating a udf and calling it in a for loop
def remove_prefix(str, prefix):
if str.startswith(blabla):
return str[len(prefix):]
return str
for x in df.columns:
x.remove_prefix()
A:
Use Series.str.replace with regex ^ for match start of string:
df = pd.DataFrame(columns=['pre_A', 'pre_B', 'pre_predmet'])
df.columns = df.columns.str.replace('^pre_', '')
print (df)
Empty DataFrame
Columns: [A, B, predmet]
Index: []
Another solution is use list comprehension with re.sub:
import re
df.columns = [re.sub('^pre_',"", x) for x in df.columns]
A:
You can use str.lstrip to strip the prefix from the column names, this way you avoid looping and checking which do contain the prefix:
# Example dataframe
df = pd.DataFrame(columns=['pre_A', 'pre_B', 'C'])
df.columns = df.columns.str.lstrip('pre_')
Resulting in:
print(df.columns)
# Index(['A', 'B', 'C'], dtype='object')
Note: This will also remove an occurence of pre_ preceded by another, i.e. all the left side successive occurrences.
A:
Use replace in list-comprehension:
df.columns = [i.replace(prefix,"") for i in df.columns]
A:
Your can read file without headers, using header=None:
pandas.read_csv(filepath_or_buffer=filename, header=None, sep=',')
A:
Use the rename method, which accepts a function to apply to column names
def remove_prefix(prefix):
return lambda x: x[len(prefix):]
frame = pd.DataFrame(dict(x_a=[1,2,3], x_b=[4,5,6]))
frame = frame.rename(remove_prefix('x_'), axis='columns')
A:
Remove it using standard pandas API:
df.columns = df.columns.str.removeprefix("prefix_")
|
remove prefix in all column names
|
I would like to remove the prefix from all column names in a dataframe.
I tried creating a udf and calling it in a for loop
def remove_prefix(str, prefix):
if str.startswith(blabla):
return str[len(prefix):]
return str
for x in df.columns:
x.remove_prefix()
|
[
"Use Series.str.replace with regex ^ for match start of string:\ndf = pd.DataFrame(columns=['pre_A', 'pre_B', 'pre_predmet'])\ndf.columns = df.columns.str.replace('^pre_', '')\nprint (df)\nEmpty DataFrame\nColumns: [A, B, predmet]\nIndex: []\n\nAnother solution is use list comprehension with re.sub:\nimport re\n\ndf.columns = [re.sub('^pre_',\"\", x) for x in df.columns]\n\n",
"You can use str.lstrip to strip the prefix from the column names, this way you avoid looping and checking which do contain the prefix:\n# Example dataframe\ndf = pd.DataFrame(columns=['pre_A', 'pre_B', 'C'])\ndf.columns = df.columns.str.lstrip('pre_')\n\nResulting in:\nprint(df.columns)\n# Index(['A', 'B', 'C'], dtype='object')\n\nNote: This will also remove an occurence of pre_ preceded by another, i.e. all the left side successive occurrences.\n",
"Use replace in list-comprehension:\ndf.columns = [i.replace(prefix,\"\") for i in df.columns]\n\n",
"Your can read file without headers, using header=None: \npandas.read_csv(filepath_or_buffer=filename, header=None, sep=',') \n\n",
"Use the rename method, which accepts a function to apply to column names\n\ndef remove_prefix(prefix):\n return lambda x: x[len(prefix):]\n\nframe = pd.DataFrame(dict(x_a=[1,2,3], x_b=[4,5,6])) \nframe = frame.rename(remove_prefix('x_'), axis='columns')\n\n",
"Remove it using standard pandas API:\ndf.columns = df.columns.str.removeprefix(\"prefix_\")\n\n"
] |
[
12,
4,
3,
0,
0,
0
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0055830212_pandas_python.txt
|
Q:
yield + generator in python in class
I am very new in Python and I wanna create a generator object that yields two lists for Fibonacci sequence. First list of number and second list of fibonacci.
The function define in the class. Before it I define fibonacci function as below:
def fib(self, _n,) -> int:
if _n == 0:
return 0
if _n == 1:
return 1
return self.fib(_n-1) + self.fib(_n-2)
I need to define def fib_seq(self, _n): function with yield and use gen() together.
I did it:
def fib_seq(self, _n):
"""
- input: n=4
- output: generator object that produces:
([0, 1, 2, 3, 4],
[0, 1, 1, 2, 3])
"""
for i in range(_n):
nlist = gen(i)
flist = gen(self.fib(i))
yield ([nlist], [flist])
but I got below error in test part:
Traceback (most recent call last):
File --- line 161, in <module> # this part is in test section
n, fib = next(gen) # trigger generator
^^^^^^^^^
File ---, line 53, in fib_seq # this part is my code
nlist = gen(i)
^^^^^^
TypeError: 'generator' object is not callable
A:
I'm not sure what the gen function you are using is, but you don't need to use it. You could do (removing self in this example to have standalone functions):
def fib(_n):
if _n == 0:
return 0
if _n == 1:
return 1
return fib(_n-1) + fib(_n-2)
def fib_seq(n):
for i in range(n + 1):
nlist = list(range(i + 1))
flist = [fib(j) for j in range(i + 1)]
yield (nlist, flist)
# as fib_seq yields a generator you have to use it in, e.g., a for loop
for k in fib_seq(4):
print(k)
([0, 1, 2, 3, 4], [0, 1, 1, 2, 3])
Note that the for loop in fib_seq is a bit superfluous as it stands. You could move the yield to within the loop, e.g.,
def fib_seq(n):
for i in range(n + 1):
nlist = list(range(i + 1))
flist = [fib(j) for j in range(i + 1)]
yield (nlist, flist)
which would give:
for k in fib_seq(4):
print(k)
([0], [0])
([0, 1], [0, 1])
([0, 1, 2], [0, 1, 1])
([0, 1, 2, 3], [0, 1, 1, 2])
([0, 1, 2, 3, 4], [0, 1, 1, 2, 3])
or, if you only want one output, have:
def fib_seq(n):
nlist = list(range(n + 1))
flist = [fib(j) for j in range(n + 1)]
yield (nlist, flist)
which would give:
for k in fib_seq(4):
print(k)
([0, 1, 2, 3, 4], [0, 1, 1, 2, 3])
|
yield + generator in python in class
|
I am very new in Python and I wanna create a generator object that yields two lists for Fibonacci sequence. First list of number and second list of fibonacci.
The function define in the class. Before it I define fibonacci function as below:
def fib(self, _n,) -> int:
if _n == 0:
return 0
if _n == 1:
return 1
return self.fib(_n-1) + self.fib(_n-2)
I need to define def fib_seq(self, _n): function with yield and use gen() together.
I did it:
def fib_seq(self, _n):
"""
- input: n=4
- output: generator object that produces:
([0, 1, 2, 3, 4],
[0, 1, 1, 2, 3])
"""
for i in range(_n):
nlist = gen(i)
flist = gen(self.fib(i))
yield ([nlist], [flist])
but I got below error in test part:
Traceback (most recent call last):
File --- line 161, in <module> # this part is in test section
n, fib = next(gen) # trigger generator
^^^^^^^^^
File ---, line 53, in fib_seq # this part is my code
nlist = gen(i)
^^^^^^
TypeError: 'generator' object is not callable
|
[
"I'm not sure what the gen function you are using is, but you don't need to use it. You could do (removing self in this example to have standalone functions):\ndef fib(_n):\n if _n == 0:\n return 0\n if _n == 1:\n return 1\n return fib(_n-1) + fib(_n-2)\n\ndef fib_seq(n):\n for i in range(n + 1):\n nlist = list(range(i + 1))\n flist = [fib(j) for j in range(i + 1)]\n yield (nlist, flist)\n\n# as fib_seq yields a generator you have to use it in, e.g., a for loop\nfor k in fib_seq(4):\n print(k)\n\n([0, 1, 2, 3, 4], [0, 1, 1, 2, 3])\n\nNote that the for loop in fib_seq is a bit superfluous as it stands. You could move the yield to within the loop, e.g.,\ndef fib_seq(n):\n for i in range(n + 1):\n nlist = list(range(i + 1))\n flist = [fib(j) for j in range(i + 1)]\n yield (nlist, flist)\n\nwhich would give:\nfor k in fib_seq(4):\n print(k)\n\n([0], [0])\n([0, 1], [0, 1])\n([0, 1, 2], [0, 1, 1])\n([0, 1, 2, 3], [0, 1, 1, 2])\n([0, 1, 2, 3, 4], [0, 1, 1, 2, 3])\n\nor, if you only want one output, have:\ndef fib_seq(n):\n nlist = list(range(n + 1))\n flist = [fib(j) for j in range(n + 1)]\n yield (nlist, flist)\n\nwhich would give:\nfor k in fib_seq(4):\n print(k)\n\n([0, 1, 2, 3, 4], [0, 1, 1, 2, 3])\n\n"
] |
[
1
] |
[] |
[] |
[
"generator",
"python",
"yield"
] |
stackoverflow_0074572200_generator_python_yield.txt
|
Q:
How to think about a schedule-building script (general thought process)
I ran into this issue that's been bugging me.
I'm trying to write a Python script to build a stock take schedule.
I managed to propose dates based on deadlines and I also managed to move the proposed dates to the nearest "legal" date in case the original proposed date fell on weekend, planned annual code freeze, etc...
I've got couple more conditions and I'm struggling to implement those.
I tried a combination of while loops with ifs, but it got me nowhere in my case.
I'm a self-taught Pythoner who's been mostly using Pandas for analysis until now, that's why I'm probably struggling with this.
**
I'm not looking for a free code service**, but I'd be over the moon if someone could give me a nudge how to think about this issue in the first place.
Ideally the dates the algorithm comes with will be:
Before given deadline for each location
No more than n counts happening on the same date
and I could possibly swap the last one around manually, but:
No location from the same area to be on the same date
Area
Location
Deadline
Proposed
A
A1
14 Apr
01 Apr
B
B3
14 Apr
01 Apr
A
A2
14 Apr
03 Apr
Any little nudge in the right direction or a half line of pseudocode would be a great help.
Massive thanks to anyone who hasn't gone into Picard-style facepalm yet after reading this.
A:
I think you need to start with pseudocode.
Something like this:
For entry in your data.
Propose an initial date (eg: deadline -1)
Check if another location from the same area happens that day
Yes? Decrement 1 to the proposed day and check again
No? Check the next condition
Check that if more than n counts happen on this date
Yes? Decrement 1 to the proposed day and check again both conditions
No? Set the date for that entry.
How you do the checkings will depend how you decide to store your data. I'd suggest probably dictionaries, but maybe you might need to crete your own classes and data structures.
Of course this is a simple algorithm that might not be able to fit all dates, but is something you can start with. Then if you see it's not enough you can try adding some things, like sorting your entries, so the most restrictive ones are set first and the more flexible ones are set last.
Ideally it should be implemented as a tree where you explore branches and can backtrack once stuck, so you would eventually find a path that leads to all entries having a solution. Trees however can grow too much to be computable, so you would need some heuristics to explore some branches first. But this can get too complex, so maybe for your problem a simpler algorithm like the one I proposed will work good enough
|
How to think about a schedule-building script (general thought process)
|
I ran into this issue that's been bugging me.
I'm trying to write a Python script to build a stock take schedule.
I managed to propose dates based on deadlines and I also managed to move the proposed dates to the nearest "legal" date in case the original proposed date fell on weekend, planned annual code freeze, etc...
I've got couple more conditions and I'm struggling to implement those.
I tried a combination of while loops with ifs, but it got me nowhere in my case.
I'm a self-taught Pythoner who's been mostly using Pandas for analysis until now, that's why I'm probably struggling with this.
**
I'm not looking for a free code service**, but I'd be over the moon if someone could give me a nudge how to think about this issue in the first place.
Ideally the dates the algorithm comes with will be:
Before given deadline for each location
No more than n counts happening on the same date
and I could possibly swap the last one around manually, but:
No location from the same area to be on the same date
Area
Location
Deadline
Proposed
A
A1
14 Apr
01 Apr
B
B3
14 Apr
01 Apr
A
A2
14 Apr
03 Apr
Any little nudge in the right direction or a half line of pseudocode would be a great help.
Massive thanks to anyone who hasn't gone into Picard-style facepalm yet after reading this.
|
[
"I think you need to start with pseudocode.\nSomething like this:\nFor entry in your data.\n Propose an initial date (eg: deadline -1)\n Check if another location from the same area happens that day\n Yes? Decrement 1 to the proposed day and check again\n No? Check the next condition\n Check that if more than n counts happen on this date\n Yes? Decrement 1 to the proposed day and check again both conditions\n No? Set the date for that entry.\n\nHow you do the checkings will depend how you decide to store your data. I'd suggest probably dictionaries, but maybe you might need to crete your own classes and data structures.\nOf course this is a simple algorithm that might not be able to fit all dates, but is something you can start with. Then if you see it's not enough you can try adding some things, like sorting your entries, so the most restrictive ones are set first and the more flexible ones are set last.\nIdeally it should be implemented as a tree where you explore branches and can backtrack once stuck, so you would eventually find a path that leads to all entries having a solution. Trees however can grow too much to be computable, so you would need some heuristics to explore some branches first. But this can get too complex, so maybe for your problem a simpler algorithm like the one I proposed will work good enough\n"
] |
[
0
] |
[] |
[] |
[
"python",
"schedule"
] |
stackoverflow_0074572469_python_schedule.txt
|
Q:
Pass certificate to requests.post from s3 bucket in AWS lambda
I am calling the api and want to send certificate along with it like this:
response = requests.post(url,cert=('pem_cert.pem', 'key_cert.key'), headers=headers, data=payload)
print(response)
Now, both pem_cert.pem and key_cert.key files are present in the local directory so it's work well, but now I want to store those certificate to S3 bucket and use it here, how can I do it?
I tried to place S3 URI but it can't find it, permission is there
I read the file from S3 bucket and passed the content directly but it's not worked.
Please help me with this.
Also I have tried to copy those file locally using:
S3_BUCKET = 'test-bucket'
object_key = "certificates/transport.key"
key_content = s3_client.get_object(Bucket=S3_BUCKET, Key=object_key)["Body"].read()
key_cert = tempfile.NamedTemporaryFile(suffix='.key')
key_cert.write(key_content)
and then passing it to the request as:
response = requests.post(url,cert=(pem_cert.name, key_cert.name), headers=headers, data=payload)
and I get max retry error:
"errorMessage": "HTTPSConnectionPool(host='abc.com', port=443): Max retries exceeded with url:
A:
To read your pem and cert file from an S3 bucket you can copy them into lambda temp storage /tmp and use it from there like it was a file on your local hard disk.
When you copy from S3 to /tmp just make sure you copy as binary file and not as a string as it won't work.
import json
import requests
import boto3
def lambda_handler(event, context):
s3 = boto3.client('s3')
#GET CERT FROM BUCKET
bucket = 'MyBucketWithCerts'
pem_key = 'MyCert.pem'
key_key = 'MyPrivateKey.key'
#Get the key and cert object
pem_response= s3.get_object(Bucket=bucket, Key=pem_key)
key_response= s3.get_object(Bucket=bucket, Key=key_key)
PemContent = pem_response['Body'].read()
KeyContent = key_response['Body'].read()
#This is the path you'll use in lambda's temp storage
Pemfile_path = '/tmp/MyCert.pem'
Keyfile_path = '/tmp/MyPrivateKey.key'
#Now create the files in lambda's tmp folder
with open(Pemfile_path, "wb") as Pembinary_file:
Pembinary_file.write(PemContent)
with open(Keyfile_path, "wb") as Keybinary_file:
Keybinary_file.write(KeyContent)
#IMPORTANT, copy them as bytes not as string
# This won't work
# tmpPemFile = open(Pemfile_path, "a")
# tmpPemFile.write(PemContent)
# tmpPemFile.close()
#Now you can do your request referencing your temp lambda files
x = requests.post('MyURL', data=your_data, headers=your_headers,cert=(Pemfile_path,Keyfile_path))
print("RESPONSE -> " + json.dumps(x.text))
|
Pass certificate to requests.post from s3 bucket in AWS lambda
|
I am calling the api and want to send certificate along with it like this:
response = requests.post(url,cert=('pem_cert.pem', 'key_cert.key'), headers=headers, data=payload)
print(response)
Now, both pem_cert.pem and key_cert.key files are present in the local directory so it's work well, but now I want to store those certificate to S3 bucket and use it here, how can I do it?
I tried to place S3 URI but it can't find it, permission is there
I read the file from S3 bucket and passed the content directly but it's not worked.
Please help me with this.
Also I have tried to copy those file locally using:
S3_BUCKET = 'test-bucket'
object_key = "certificates/transport.key"
key_content = s3_client.get_object(Bucket=S3_BUCKET, Key=object_key)["Body"].read()
key_cert = tempfile.NamedTemporaryFile(suffix='.key')
key_cert.write(key_content)
and then passing it to the request as:
response = requests.post(url,cert=(pem_cert.name, key_cert.name), headers=headers, data=payload)
and I get max retry error:
"errorMessage": "HTTPSConnectionPool(host='abc.com', port=443): Max retries exceeded with url:
|
[
"To read your pem and cert file from an S3 bucket you can copy them into lambda temp storage /tmp and use it from there like it was a file on your local hard disk.\nWhen you copy from S3 to /tmp just make sure you copy as binary file and not as a string as it won't work.\nimport json\nimport requests\nimport boto3 \n\n\ndef lambda_handler(event, context):\n \n s3 = boto3.client('s3')\n\n #GET CERT FROM BUCKET\n bucket = 'MyBucketWithCerts'\n pem_key = 'MyCert.pem'\n key_key = 'MyPrivateKey.key'\n\n #Get the key and cert object\n pem_response= s3.get_object(Bucket=bucket, Key=pem_key)\n key_response= s3.get_object(Bucket=bucket, Key=key_key)\n\n PemContent = pem_response['Body'].read()\n KeyContent = key_response['Body'].read()\n \n #This is the path you'll use in lambda's temp storage\n Pemfile_path = '/tmp/MyCert.pem'\n Keyfile_path = '/tmp/MyPrivateKey.key'\n\n #Now create the files in lambda's tmp folder\n with open(Pemfile_path, \"wb\") as Pembinary_file:\n Pembinary_file.write(PemContent) \n\n with open(Keyfile_path, \"wb\") as Keybinary_file:\n Keybinary_file.write(KeyContent) \n\n #IMPORTANT, copy them as bytes not as string\n # This won't work\n\n # tmpPemFile = open(Pemfile_path, \"a\")\n # tmpPemFile.write(PemContent)\n # tmpPemFile.close()\n\n #Now you can do your request referencing your temp lambda files\n x = requests.post('MyURL', data=your_data, headers=your_headers,cert=(Pemfile_path,Keyfile_path))\n print(\"RESPONSE -> \" + json.dumps(x.text))\n \n\n"
] |
[
0
] |
[] |
[] |
[
"amazon_s3",
"amazon_web_services",
"python"
] |
stackoverflow_0073403727_amazon_s3_amazon_web_services_python.txt
|
Q:
Delete specific route cache in Flask-Caching
I am trying to delete a flask cache on a specific route if there is an error or if a variable is empty, but i don't understand how to do it.
I have found this, but i don't think it is helpful in my case:
Delete specific cache in Flask-Cache or Flask-Caching
This is my code:
@nsaudio.route('/repeat/<string:text>/<string:chatid>/<string:voice>')
class AudioRepeatClass(Resource):
@cache.cached(timeout=120, query_string=True)
def get (self, text: str, chatid: str, voice: str):
try:
tts_out = utils.get_tts(text, voice=voice, timeout=120)
if tts_out is not None:
return send_file(tts_out, attachment_filename='audio.wav', mimetype='audio/x-wav')
else:
resp = make_response("TTS Generation Error!", 500)
return resp
except Exception as e:
return make_response(str(e), 500)
I need to clear the cache when tts_out is None and when there is an Exception
I need the client to call the utils.get_tts method if the precedent request was in error
How to do that?
A:
For Anyone having this proplem, I have just found the solution.
@nsaudio.route('/repeat/<string:text>/<string:chatid>/<string:voice>')
class AudioRepeatClass(Resource):
@cache.cached(timeout=120, query_string=True)
def get (self, text: str, chatid: str, voice: str):
try:
tts_out = utils.get_tts(text, voice=voice, timeout=120)
if tts_out is not None:
return send_file(tts_out, attachment_filename='audio.wav', mimetype='audio/x-wav')
else:
@after_this_request
def clear_cache(response):
cache.delete_memoized(AudioRepeatClass.get, self, str, str, str)
return make_response("TTS Generation Error!", 500)
except Exception as e:
@after_this_request
def clear_cache(response):
cache.delete_memoized(AudioRepeatClass.get, self, str, str, str)
return make_response(str(e), 500)
|
Delete specific route cache in Flask-Caching
|
I am trying to delete a flask cache on a specific route if there is an error or if a variable is empty, but i don't understand how to do it.
I have found this, but i don't think it is helpful in my case:
Delete specific cache in Flask-Cache or Flask-Caching
This is my code:
@nsaudio.route('/repeat/<string:text>/<string:chatid>/<string:voice>')
class AudioRepeatClass(Resource):
@cache.cached(timeout=120, query_string=True)
def get (self, text: str, chatid: str, voice: str):
try:
tts_out = utils.get_tts(text, voice=voice, timeout=120)
if tts_out is not None:
return send_file(tts_out, attachment_filename='audio.wav', mimetype='audio/x-wav')
else:
resp = make_response("TTS Generation Error!", 500)
return resp
except Exception as e:
return make_response(str(e), 500)
I need to clear the cache when tts_out is None and when there is an Exception
I need the client to call the utils.get_tts method if the precedent request was in error
How to do that?
|
[
"For Anyone having this proplem, I have just found the solution.\n@nsaudio.route('/repeat/<string:text>/<string:chatid>/<string:voice>')\nclass AudioRepeatClass(Resource):\n @cache.cached(timeout=120, query_string=True)\n def get (self, text: str, chatid: str, voice: str):\n try:\n tts_out = utils.get_tts(text, voice=voice, timeout=120)\n if tts_out is not None:\n return send_file(tts_out, attachment_filename='audio.wav', mimetype='audio/x-wav')\n else:\n @after_this_request\n def clear_cache(response):\n cache.delete_memoized(AudioRepeatClass.get, self, str, str, str)\n return make_response(\"TTS Generation Error!\", 500)\n except Exception as e:\n @after_this_request\n def clear_cache(response):\n cache.delete_memoized(AudioRepeatClass.get, self, str, str, str)\n return make_response(str(e), 500)\n\n"
] |
[
0
] |
[] |
[] |
[
"flask",
"flask_caching",
"python"
] |
stackoverflow_0074572207_flask_flask_caching_python.txt
|
Q:
Nested regex in pandas python
I am working on the cosmetic ingredient data and trying to solve a regex problem where I want to replace "," with "-".
For example,
x = ['6,7- dihydro-1,1,2,3,3-pentamethyl-4(5h)-indanone',
'steareth-10, polyacrylamide c1,14 isoparaffin, laureth-7, propylene glycol, hydrolyzed soy protein, aloe barbadensis, 1,2-hexanediol']
Here, I only wish to substitute , between the chemical formula to be replaced with - and not the word separator.
For example, expected outout like
6-7- dihydro-1-1-2-3-3-pentamethyl-4(5h)-indanone
steareth-10, polyacrylamide c1-14 isoparaffin, laureth-7, propylene glycol, hydrolyzed soy protein, aloe barbadensis, 1-2-hexanediol
I have tried creating generic regex and even though I am able to match the data, I am unable to replace.
x.str.contains(r'(\d,\d,\d,\d,\d,\d,\d,\d,\d,\d)|(\d,\d,\d,\d,\d,\d,\d,\d)|(\d,\d,\d,\d,\d,\d,\d)|(\d,\d,\d,\d,\d,\d)|(\d,\d,\d,\d,\d)|(\d,\d,\d,\d)|(\d,\d,\d)|(\d,\d)')
or x.str.findall(r"([, 0-9]+)-")
Please help with the approach
A:
You could use a capture group:
(\d),(?=[\d,]*-)
Explanation
(\d) Capture group 1, match a single digit
, Match literally (to be replaced)
(?=[\d,]*-) Positive lookahead, assert optional digits or comma's to the right followed by a hyphen
See a regex demo.
In the replacement use the first capture group followed by a hyphen \1-
Example
import re
x = ['6,7- dihydro-1,1,2,3,3-pentamethyl-4(5h)-indanone',
'steareth-10, polyacrylamide c1,14 isoparaffin, laureth-7, propylene glycol, hydrolyzed soy protein, aloe barbadensis, 1,2-hexanediol',
'1,1,2,3,3'
]
for s in x:
print(re.sub(r'(\d),(?=[\d,]*-)', r'\1-', s))
Output
6-7- dihydro-1-1-2-3-3-pentamethyl-4(5h)-indanone
steareth-10, polyacrylamide c1,14 isoparaffin, laureth-7, propylene glycol, hydrolyzed soy protein, aloe barbadensis, 1-2-hexanediol
1,1,2,3,3
An example using a positive lookbehind and a match only, where you would just use a - in the replacement:
(?<=\d),(?=[\d,]*-)
And in the code:
re.sub(r'(?<=\d),(?=[\d,]*-)', r'-', s)
Regex demo
|
Nested regex in pandas python
|
I am working on the cosmetic ingredient data and trying to solve a regex problem where I want to replace "," with "-".
For example,
x = ['6,7- dihydro-1,1,2,3,3-pentamethyl-4(5h)-indanone',
'steareth-10, polyacrylamide c1,14 isoparaffin, laureth-7, propylene glycol, hydrolyzed soy protein, aloe barbadensis, 1,2-hexanediol']
Here, I only wish to substitute , between the chemical formula to be replaced with - and not the word separator.
For example, expected outout like
6-7- dihydro-1-1-2-3-3-pentamethyl-4(5h)-indanone
steareth-10, polyacrylamide c1-14 isoparaffin, laureth-7, propylene glycol, hydrolyzed soy protein, aloe barbadensis, 1-2-hexanediol
I have tried creating generic regex and even though I am able to match the data, I am unable to replace.
x.str.contains(r'(\d,\d,\d,\d,\d,\d,\d,\d,\d,\d)|(\d,\d,\d,\d,\d,\d,\d,\d)|(\d,\d,\d,\d,\d,\d,\d)|(\d,\d,\d,\d,\d,\d)|(\d,\d,\d,\d,\d)|(\d,\d,\d,\d)|(\d,\d,\d)|(\d,\d)')
or x.str.findall(r"([, 0-9]+)-")
Please help with the approach
|
[
"You could use a capture group:\n(\\d),(?=[\\d,]*-)\n\nExplanation\n\n(\\d) Capture group 1, match a single digit\n, Match literally (to be replaced)\n(?=[\\d,]*-) Positive lookahead, assert optional digits or comma's to the right followed by a hyphen\n\nSee a regex demo.\nIn the replacement use the first capture group followed by a hyphen \\1-\nExample\nimport re\n\nx = ['6,7- dihydro-1,1,2,3,3-pentamethyl-4(5h)-indanone',\n 'steareth-10, polyacrylamide c1,14 isoparaffin, laureth-7, propylene glycol, hydrolyzed soy protein, aloe barbadensis, 1,2-hexanediol',\n '1,1,2,3,3'\n ]\n\nfor s in x:\n print(re.sub(r'(\\d),(?=[\\d,]*-)', r'\\1-', s))\n\nOutput\n6-7- dihydro-1-1-2-3-3-pentamethyl-4(5h)-indanone\nsteareth-10, polyacrylamide c1,14 isoparaffin, laureth-7, propylene glycol, hydrolyzed soy protein, aloe barbadensis, 1-2-hexanediol\n1,1,2,3,3\n\n\nAn example using a positive lookbehind and a match only, where you would just use a - in the replacement:\n(?<=\\d),(?=[\\d,]*-)\n\nAnd in the code:\nre.sub(r'(?<=\\d),(?=[\\d,]*-)', r'-', s)\n\nRegex demo\n"
] |
[
1
] |
[] |
[] |
[
"dataframe",
"nlp",
"pandas",
"python",
"regex"
] |
stackoverflow_0074572143_dataframe_nlp_pandas_python_regex.txt
|
Q:
pytest: mock method on Path instance to return output depending on the filename of the instance
I am trying to mock pathlib's is_file method so that it returns True/False depending on my logic.
I have a function in mymodule.py to test:
### mymodule.py
from pathlib import Path
def myfun(root: Path):
return root.is_file()
and my pytest function:
import mymodule
# One of my attempts
class MockPathIsFile:
def __init__(self, existing_files):
self.existing_files = existing_files
def is_file(self):
# here I am not able to get the file name (e.g. "foot.txt" or "nope.txt") to be compared with `self.existing_files`.
if <???> in self.existing_files:
return True
return False
def test_mymodule(monkeypatch):
monkeypatch.setattr(mymodule.Path, "is_file", MockPathIsFile(existing_files=["foo.txt"]).is_file)
assert mymodule.myfun(Path("foo.txt")) is True
assert mymodule.myfun(Path("nope.txt")) is False
This is a stripped-down example of more complicate module I am trying to test. In the real case I am also patching Path.glob,Path.open to list and get filenames such as "foo.txt".
A:
def mock_is_file(existing_files):
def mock(self: Path):
return str(self) in existing_files
return mock
monkeypatch.setattr(validate.Path, 'is_file', mock_is_file(existing_files=["foo"]))
assert mymodule.myfun(Path("foo.txt")) is True
assert mymodule.myfun(Path("nope.txt")) is False
|
pytest: mock method on Path instance to return output depending on the filename of the instance
|
I am trying to mock pathlib's is_file method so that it returns True/False depending on my logic.
I have a function in mymodule.py to test:
### mymodule.py
from pathlib import Path
def myfun(root: Path):
return root.is_file()
and my pytest function:
import mymodule
# One of my attempts
class MockPathIsFile:
def __init__(self, existing_files):
self.existing_files = existing_files
def is_file(self):
# here I am not able to get the file name (e.g. "foot.txt" or "nope.txt") to be compared with `self.existing_files`.
if <???> in self.existing_files:
return True
return False
def test_mymodule(monkeypatch):
monkeypatch.setattr(mymodule.Path, "is_file", MockPathIsFile(existing_files=["foo.txt"]).is_file)
assert mymodule.myfun(Path("foo.txt")) is True
assert mymodule.myfun(Path("nope.txt")) is False
This is a stripped-down example of more complicate module I am trying to test. In the real case I am also patching Path.glob,Path.open to list and get filenames such as "foo.txt".
|
[
"def mock_is_file(existing_files):\n def mock(self: Path):\n return str(self) in existing_files\n return mock\n\nmonkeypatch.setattr(validate.Path, 'is_file', mock_is_file(existing_files=[\"foo\"]))\n\nassert mymodule.myfun(Path(\"foo.txt\")) is True\nassert mymodule.myfun(Path(\"nope.txt\")) is False\n\n"
] |
[
0
] |
[] |
[] |
[
"monkeypatching",
"pytest",
"python"
] |
stackoverflow_0074560750_monkeypatching_pytest_python.txt
|
Q:
Best graph from dataframe with different conditions (groups and variables)
I have a dataframe (cells) that it looks like this (it has more rows):
ID
Time(min)
Cell1
Cell2
Cell3
Cell4
Cell5
Cell6
Cell7
AA001
0
10.57
77.28
14.11
15.12
1.56
95.83
3.41
AA001
30
12.99
77.96
15.01
15.35
1.60
96.02
3.37
AA001
90
11.41
79.85
16.69
19.65
1.28
92.14
6.01
AA001
180
15.89
75.11
12.48
11.95
1.34
95.90
3.69
AA001
360
10.16
83.67
19.51
14.68
1.09
70.80
26.21
AA003
0
12.34
81.16
17.77
17.49
1.83
84.94
13.31
AA006
0
21.71
71.24
7.67
11.43
1.56
90.03
7.62
AA006
7
15.23
78.81
15.60
12.19
2.23
93.38
3.4
I have grouped by the variables ID and Time, because I would like to see the "evolution" of each cell for each sample:
inmune %>%
group_by(PID, Time)
So, I have performed a scatter plot, but it's a mess with so many lines connected to each point.
Also I tried transform in a long-data format:
df2<- melt(cells, id = "Time")
But it results in a table with 3 variables (Time, cells, values) so I miss the ID.
The idea is to represent the difference of the values for each time, grouped by the ID.
But any suggestion about other type of graphs more suitable for this kind of data is more than welcome.
Thanks!!
A:
Here are two options separating the ID's in facets.
Dummy data:
df = tibble(ID = sample(letters, 300, TRUE),
value = runif(300, 0, 40))
df = df %>%
group_by(ID) %>%
mutate(Time = seq(0, by = 10, length = n())) %>%
arrange(ID)
Obs: if your problem was the visualization of lots of ID's, it would've been better if you posted your whole data using dput()
One facet for each group:
df %>%
ggplot(aes(Time, value)) +
geom_point() +
facet_wrap(vars(ID)) #try using scales = "free_x"
Grouping several ID's in each facet:
You can choose different concepts to group some ID's together, I choose the number of times they had data for, as that seems to vary in your data.
k = 9 #number of groups, change it as you please
facets = df %>%
group_by(ID) %>%
summarise(n = n(), .groups = "drop") %>%
mutate(facets = ntile(n, k))
df = df %>% mutate(facets = facets$facets[match(ID, facets$ID)])
df %>%
ggplot(aes(Time, value, color = ID)) +
geom_point() +
facet_wrap(vars(facets)) + #try using scales = "free_x"
theme(legend.position = "none")
A:
I would guess you'd like to see something like this:
import seaborn as sns
df1 = df.melt(id_vars=["ID", "Time(min)"], value_vars=["Cell1", "Cell2", "Cell3", "Cell4", "Cell5", "Cell6", "Cell7"])
df1["t"] = df1["ID"]+df1["variable"]
res = sns.relplot(x="t", y="Time(min)", hue="variable", size="value",
sizes=(20, 800), alpha=.5, palette="muted",
height=6, data = df1)
res.set_xticklabels(rotation=30)
|
Best graph from dataframe with different conditions (groups and variables)
|
I have a dataframe (cells) that it looks like this (it has more rows):
ID
Time(min)
Cell1
Cell2
Cell3
Cell4
Cell5
Cell6
Cell7
AA001
0
10.57
77.28
14.11
15.12
1.56
95.83
3.41
AA001
30
12.99
77.96
15.01
15.35
1.60
96.02
3.37
AA001
90
11.41
79.85
16.69
19.65
1.28
92.14
6.01
AA001
180
15.89
75.11
12.48
11.95
1.34
95.90
3.69
AA001
360
10.16
83.67
19.51
14.68
1.09
70.80
26.21
AA003
0
12.34
81.16
17.77
17.49
1.83
84.94
13.31
AA006
0
21.71
71.24
7.67
11.43
1.56
90.03
7.62
AA006
7
15.23
78.81
15.60
12.19
2.23
93.38
3.4
I have grouped by the variables ID and Time, because I would like to see the "evolution" of each cell for each sample:
inmune %>%
group_by(PID, Time)
So, I have performed a scatter plot, but it's a mess with so many lines connected to each point.
Also I tried transform in a long-data format:
df2<- melt(cells, id = "Time")
But it results in a table with 3 variables (Time, cells, values) so I miss the ID.
The idea is to represent the difference of the values for each time, grouped by the ID.
But any suggestion about other type of graphs more suitable for this kind of data is more than welcome.
Thanks!!
|
[
"Here are two options separating the ID's in facets.\nDummy data:\ndf = tibble(ID = sample(letters, 300, TRUE),\n value = runif(300, 0, 40))\n\ndf = df %>%\n group_by(ID) %>%\n mutate(Time = seq(0, by = 10, length = n())) %>%\n arrange(ID)\n\nObs: if your problem was the visualization of lots of ID's, it would've been better if you posted your whole data using dput()\nOne facet for each group:\ndf %>%\n ggplot(aes(Time, value)) +\n geom_point() +\n facet_wrap(vars(ID)) #try using scales = \"free_x\"\n\n\nGrouping several ID's in each facet:\nYou can choose different concepts to group some ID's together, I choose the number of times they had data for, as that seems to vary in your data.\nk = 9 #number of groups, change it as you please\nfacets = df %>%\n group_by(ID) %>%\n summarise(n = n(), .groups = \"drop\") %>%\n mutate(facets = ntile(n, k))\n\ndf = df %>% mutate(facets = facets$facets[match(ID, facets$ID)])\n\ndf %>%\n ggplot(aes(Time, value, color = ID)) +\n geom_point() +\n facet_wrap(vars(facets)) + #try using scales = \"free_x\"\n theme(legend.position = \"none\")\n\n\n",
"I would guess you'd like to see something like this:\nimport seaborn as sns\n\ndf1 = df.melt(id_vars=[\"ID\", \"Time(min)\"], value_vars=[\"Cell1\", \"Cell2\", \"Cell3\", \"Cell4\", \"Cell5\", \"Cell6\", \"Cell7\"])\ndf1[\"t\"] = df1[\"ID\"]+df1[\"variable\"]\n\nres = sns.relplot(x=\"t\", y=\"Time(min)\", hue=\"variable\", size=\"value\",\n sizes=(20, 800), alpha=.5, palette=\"muted\",\n height=6, data = df1)\nres.set_xticklabels(rotation=30)\n\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"group_by",
"plot",
"python",
"r"
] |
stackoverflow_0074572028_group_by_plot_python_r.txt
|
Q:
ImportError: cannot import name 'is_directory' from 'PIL._util' (/usr/local/lib/python3.7/dist-packages/PIL/_util.py)
While using this code, I get this error of Pillow. I tried re-installing pillow but still struggling with this issue. Any help to make this code run?
import layoutparser as lp
model = lp.Detectron2LayoutModel(
config_path ='lp://PubLayNet/faster_rcnn_R_50_FPN_3x/config', # In model catalog
label_map ={0: "Text", 1: "Title", 2: "List", 3:"Table", 4:"Figure"}, # In model`label_map`
extra_config=["MODEL.ROI_HEADS.SCORE_THRESH_TEST", 0.8] # Optional
)
model.detect(image)
Getting this error:
ImportError Traceback (most recent call last)
[<ipython-input-6-59f0fb07b7e3>](https://localhost:8080/#) in <module>
1 import layoutparser as lp
----> 2 model = lp.Detectron2LayoutModel(
3 config_path ='lp://PubLayNet/faster_rcnn_R_50_FPN_3x/config', # In model catalog
4 label_map ={0: "Text", 1: "Title", 2: "List", 3:"Table", 4:"Figure"}, # In model`label_map`
5 extra_config=["MODEL.ROI_HEADS.SCORE_THRESH_TEST", 0.8] # Optional
31 frames
[/usr/local/lib/python3.7/dist-packages/PIL/ImageFont.py](https://localhost:8080/#) in <module>
35 from . import Image
36 from ._deprecate import deprecate
---> 37 from ._util import is_directory, is_path
38
39
ImportError: cannot import name 'is_directory' from 'PIL._util' (/usr/local/lib/python3.7/dist-packages/PIL/_util.py)
A:
This is because of higher version of pillow package. You should install pillow version less than or equal to 6.2.2 to resolve this error.
pip install --upgrade pillow==6.2.2
A:
Run the below command before installing the library:
!pip install fastcore -U
|
ImportError: cannot import name 'is_directory' from 'PIL._util' (/usr/local/lib/python3.7/dist-packages/PIL/_util.py)
|
While using this code, I get this error of Pillow. I tried re-installing pillow but still struggling with this issue. Any help to make this code run?
import layoutparser as lp
model = lp.Detectron2LayoutModel(
config_path ='lp://PubLayNet/faster_rcnn_R_50_FPN_3x/config', # In model catalog
label_map ={0: "Text", 1: "Title", 2: "List", 3:"Table", 4:"Figure"}, # In model`label_map`
extra_config=["MODEL.ROI_HEADS.SCORE_THRESH_TEST", 0.8] # Optional
)
model.detect(image)
Getting this error:
ImportError Traceback (most recent call last)
[<ipython-input-6-59f0fb07b7e3>](https://localhost:8080/#) in <module>
1 import layoutparser as lp
----> 2 model = lp.Detectron2LayoutModel(
3 config_path ='lp://PubLayNet/faster_rcnn_R_50_FPN_3x/config', # In model catalog
4 label_map ={0: "Text", 1: "Title", 2: "List", 3:"Table", 4:"Figure"}, # In model`label_map`
5 extra_config=["MODEL.ROI_HEADS.SCORE_THRESH_TEST", 0.8] # Optional
31 frames
[/usr/local/lib/python3.7/dist-packages/PIL/ImageFont.py](https://localhost:8080/#) in <module>
35 from . import Image
36 from ._deprecate import deprecate
---> 37 from ._util import is_directory, is_path
38
39
ImportError: cannot import name 'is_directory' from 'PIL._util' (/usr/local/lib/python3.7/dist-packages/PIL/_util.py)
|
[
"This is because of higher version of pillow package. You should install pillow version less than or equal to 6.2.2 to resolve this error.\npip install --upgrade pillow==6.2.2 \n\n",
"Run the below command before installing the library:\n!pip install fastcore -U\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"importerror",
"layout_parser",
"python",
"python_imaging_library"
] |
stackoverflow_0073711994_importerror_layout_parser_python_python_imaging_library.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.