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:
Why can't I index variables in dictionary
If dictionary is ordered in Python 3.6+, why can't I call a dictionary variable as print(dictionary_name[index])?
Got error.
A:
You can't do that, but the following might be what you're looking for.
print(list(dictionary_name.values())[index])
This definitely feels like... | Why can't I index variables in dictionary | If dictionary is ordered in Python 3.6+, why can't I call a dictionary variable as print(dictionary_name[index])?
Got error.
| [
"You can't do that, but the following might be what you're looking for.\nprint(list(dictionary_name.values())[index])\n\nThis definitely feels like XY problem territory, as I'm not sure why you'd want to do this.\n"
] | [
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074268697_dictionary_python.txt |
Q:
Tkinter File dialog save is empty
I coded a (not finished) Texteditor but wenn I save, the save file is empty
import sys
import tkinter
import tkinter.filedialog
root=tkinter.Tk("")
root.title("Text Editor")
text=tkinter.Text(root)
text.grid()
def saveas():
global text
t = text.get("1.0", "end-1c")
s... | Tkinter File dialog save is empty | I coded a (not finished) Texteditor but wenn I save, the save file is empty
import sys
import tkinter
import tkinter.filedialog
root=tkinter.Tk("")
root.title("Text Editor")
text=tkinter.Text(root)
text.grid()
def saveas():
global text
t = text.get("1.0", "end-1c")
savelocation=tkinter.filedialog.asksave... | [
"You need to specify what to write to the file and both write and close are methods, not attributes so they need to be called.\nimport sys\nimport tkinter\nimport tkinter.filedialog\n\n\nroot=tkinter.Tk(\"\")\nroot.title(\"Text Editor\")\ntext=tkinter.Text(root)\ntext.grid()\n\ndef saveas():\n global text\n t... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074268734_python_tkinter.txt |
Q:
Convert latitude and longitude to float
I have a dataframe df like these
3 first rows are these
City
Longitude
Latitude
Toluca
W099.6569
N19.2925
Pune
E73.8562
N18.5167
Bloemfontain
E026.216667
S29.116667
For example Bloemfontain row should be like these at the end
City
Longitude
Latitude
Bloemfontain
-29.1... | Convert latitude and longitude to float | I have a dataframe df like these
3 first rows are these
City
Longitude
Latitude
Toluca
W099.6569
N19.2925
Pune
E73.8562
N18.5167
Bloemfontain
E026.216667
S29.116667
For example Bloemfontain row should be like these at the end
City
Longitude
Latitude
Bloemfontain
-29.116667
26.216667
I used t... | [
"I don't see where it is necessary to utilize a pattern search at all. Here is how I would do the task.\n# function to perform the partitioning\ndef cnvrtCoord(val: str) -> float:\n sgn = +1\n if val[0] == 'S' or val[0] == 'W':\n sgn = -1\n return float(val[1:]) * sgn \n\nThen to change the conten... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074267928_pandas_python.txt |
Q:
How to animate n curves in a plot using matplotlib's animation?
I have n curves that I want to draw using matplotlib's animation (each curve corresponds to a gpx file recorded with a fitness tracker or a smartphone). It works well when using only one track or two tracks. But as soon as I want to adapt it to using ... | How to animate n curves in a plot using matplotlib's animation? | I have n curves that I want to draw using matplotlib's animation (each curve corresponds to a gpx file recorded with a fitness tracker or a smartphone). It works well when using only one track or two tracks. But as soon as I want to adapt it to using n curves, I am lost. Here is my code:
import matplotlib.animation as ... | [
"Your are supposed to return an iterable of \"artists\" (that is of things to draw, that is of result of a \"plot\" call for example.\nplt_tracks is such an iterable.\nplt_lastPos also is.\nBut (plt_tracks, plt_lastPos) (with implicit parenthesis here) is a pair of such iterable. So an iterable of iterable of artis... | [
1
] | [] | [] | [
"animation",
"graph",
"matplotlib",
"matplotlib_animation",
"python"
] | stackoverflow_0074268718_animation_graph_matplotlib_matplotlib_animation_python.txt |
Q:
Encode the DNA string in such a way that similar subsequent characters are grouped into number of occurrences along with the char
I need help in writing the Python code which would return the following output_string as mentioned below in the examples.
Example 1:
input_string = "AAABCCCCDDA"
output_string = "3AB4C2... | Encode the DNA string in such a way that similar subsequent characters are grouped into number of occurrences along with the char | I need help in writing the Python code which would return the following output_string as mentioned below in the examples.
Example 1:
input_string = "AAABCCCCDDA"
output_string = "3AB4C2DA"
Example 2:
input_string = "ABBBBCCDDDDAAAAA"
output_string = "A4B2C4D5A"
| [
"You can use itertools.groupby.\nIn python 3.8+, You can use walrus operator (:=) and write a short approach.\n>>> from itertools import groupby\n>>> input_string = \"ABBBBCCDDDDAAAAA\"\n>>> ''.join(f\"{len_g}{k}\" if (len_g := len(list(g))) > 1 else k for k, g in groupby(input_string))\n'A4B2C4D5A'\n\nIn Python < ... | [
1,
0
] | [] | [] | [
"python",
"python_3.x",
"string"
] | stackoverflow_0074268278_python_python_3.x_string.txt |
Q:
How do I remove specific words from columns?
I need to remove "km" from distance column:
[Distance]
0 114 km
1 114 km
2 9.1 km
3 33.1 km
4 182 km
5 93.2 km
6 40.4 km
7 0.0
8 0.0
9 43.4 km
Name: distance, dtype: object
Has to look like this:
[Distance]
0 114
1 114
... | How do I remove specific words from columns? | I need to remove "km" from distance column:
[Distance]
0 114 km
1 114 km
2 9.1 km
3 33.1 km
4 182 km
5 93.2 km
6 40.4 km
7 0.0
8 0.0
9 43.4 km
Name: distance, dtype: object
Has to look like this:
[Distance]
0 114
1 114
2 9.1
3 33.1
4 182
5 93.2
6 40.4
... | [
"Assuming the trailing substring to remove is always km, you can use:\ndf['distance'] = df['distance'].str.replace(r'\\s*km$', '', regex=True)\n\nA more generic method would be to extract the number:\ndf['distance'] = df['distance'].str.extract(r'(\\d+(?:\\.\\d+)?)')\n\nIf you only want the number when there is \"k... | [
2,
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"regex"
] | stackoverflow_0074248482_dataframe_pandas_python_regex.txt |
Q:
how to maintain separate log files for each specific log level in python?
when i set level to INFO in file_handler. am getting other log levels also printed into the file.
how can i get each log level printed into different log file . i dont want duplicate logs in any of the files.Can any one please help?
import l... | how to maintain separate log files for each specific log level in python? | when i set level to INFO in file_handler. am getting other log levels also printed into the file.
how can i get each log level printed into different log file . i dont want duplicate logs in any of the files.Can any one please help?
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
form... | [
"All the levels which you have logged at are above or at the set level for your handler (INFO), so those log messages will all appear in your log file.\nYou can write custom filters that will allow you to include ONLY certain levels and exclude all levels above and below.\nFilters can be set on a handler level to a... | [
1,
1
] | [] | [] | [
"logging",
"python",
"python_3.x"
] | stackoverflow_0074268724_logging_python_python_3.x.txt |
Q:
Trying to find a good example to create a html button in django to run a python function and display result
I've trying for a while now to learn django mostly for my own curiosity. My current goal is to have an button on screen that when pressed does some simple python function at first. Something like display a s... | Trying to find a good example to create a html button in django to run a python function and display result | I've trying for a while now to learn django mostly for my own curiosity. My current goal is to have an button on screen that when pressed does some simple python function at first. Something like display a string value or a random number on the screen. I've found some examples but they're not helping my understanding o... | [
"Here's a basic example of clicking a button in and getting a random number back. I used JQuery, because i find it generally easier and fast- so just take that into account.\nGenerally when you use Ajax you encode the return data with JSON, so that's what I did.\nI used a dictionary, as the JSON return and added my... | [
0
] | [] | [] | [
"ajax",
"django",
"python"
] | stackoverflow_0074266523_ajax_django_python.txt |
Q:
Indices of matching parentheses in Python
Is there a way to get indices of matching parentheses in a string? For example for this one:
text = 'aaaa(bb()()ccc)dd'
I'd like to get a dictionary with values:
result = {4:14, 7:8, 9:10}
which means that parentheses on index 4 and 14 are matching , 7 and 8 an so on.
Th... | Indices of matching parentheses in Python | Is there a way to get indices of matching parentheses in a string? For example for this one:
text = 'aaaa(bb()()ccc)dd'
I'd like to get a dictionary with values:
result = {4:14, 7:8, 9:10}
which means that parentheses on index 4 and 14 are matching , 7 and 8 an so on.
Thanks a lot.
| [
"You mean an automated way?\nI don't think so.\nYou need to create a program using a stack, in which you push the index when you find an open parenthesis, and pop it when you find a closing parenthesis.\nIn Python, you can easily use a list as a stack, since they have the append() and pop() methods.\ndef find_paren... | [
33,
15,
1,
1,
0
] | [] | [] | [
"parentheses",
"python"
] | stackoverflow_0029991917_parentheses_python.txt |
Q:
How to print without a newline without using end=" "?
I need to design a function named firstN that, given a positive integer n, displays on the screen the first n integers on the same line, separated by white space.
An example of using the function could be:
>>> firstN(10)
0 1 2 3 4 5 6 7 8 9
I have done this:
d... | How to print without a newline without using end=" "? | I need to design a function named firstN that, given a positive integer n, displays on the screen the first n integers on the same line, separated by white space.
An example of using the function could be:
>>> firstN(10)
0 1 2 3 4 5 6 7 8 9
I have done this:
def firstN(n):
for i in range(10):
print (i, end... | [
"Thanks for your answers. Yes, my teacher was using the version 2 of python. I have alredy solved the question.\nTo print without a newlineyou need to put a comma:\ndef firstN(n):\n for i in range(10):\n print (i,)\nfirstN(10);\n\n",
"You can use starred expression to unpack iterable arguments:\ndef fir... | [
1,
0
] | [] | [] | [
"function",
"newline",
"numbers",
"python",
"range"
] | stackoverflow_0074244933_function_newline_numbers_python_range.txt |
Q:
Finding the amount of an ER20 token in ethereum transaction web3 from the hash of an ethereum swap?
I'm trying to get the amount of a token sent in a crypto transaction and it's proving to be more difficult than I thought.
I'm using the web3 module as follows, but I can't get the function to work correctly.
I beli... | Finding the amount of an ER20 token in ethereum transaction web3 from the hash of an ethereum swap? | I'm trying to get the amount of a token sent in a crypto transaction and it's proving to be more difficult than I thought.
I'm using the web3 module as follows, but I can't get the function to work correctly.
I believe I need to decode the input section of the transaction as follows:
uniswap_factory = '0x5C69bE... | [
"I think your print(tx) will show the Dict object containing logsBloom, data, blockNumber, transactionHash, logIndex, etc...\nYou have to look inside of \"data\".\nFor example, I tested with a simple token swap using 0.000000000001234567 BNB.\nprint(tx) of my swap transaction returns to me this:\n'data': \n'0x\n00... | [
0
] | [] | [] | [
"ethereum",
"etherscan",
"python",
"web3py"
] | stackoverflow_0074118791_ethereum_etherscan_python_web3py.txt |
Q:
Convert 200+ Excel Files in a Folder into 1 Excel File
I have 200+ excel workbook files in a folder with various sheets and I would like to combine them into one single excel file.
import pandas as pd
import os
excelfolder = 'path to the folder'
path_names = []
for root, folder, files in os.walk(excelfolder):
... | Convert 200+ Excel Files in a Folder into 1 Excel File | I have 200+ excel workbook files in a folder with various sheets and I would like to combine them into one single excel file.
import pandas as pd
import os
excelfolder = 'path to the folder'
path_names = []
for root, folder, files in os.walk(excelfolder):
for file in files:
if file.endswith('.xlsx'):
... | [
"does this do what you want it to?\nimport openpyxl\nimport pandas as pd\nimport os\n\nexcelfolder = \"path to the folder\"\n\npath_names = []\n\nfor root, folder, files in os.walk(excelfolder):\n for file in files:\n if file.endswith(\".xlsx\"):\n fullname = os.path.join(root, file)\n ... | [
0
] | [] | [] | [
"excel",
"pandas",
"python"
] | stackoverflow_0074268974_excel_pandas_python.txt |
Q:
Python: How to append individual dictionaries to Series data structure
My goal is to create an output that has a Series datatype and following output:
I tried to achieve this by using the code below:
series_structure = pd.Series()
for i in table_dtypes[0]:
if i == "object":
type_dict = {'type': 'cate... | Python: How to append individual dictionaries to Series data structure | My goal is to create an output that has a Series datatype and following output:
I tried to achieve this by using the code below:
series_structure = pd.Series()
for i in table_dtypes[0]:
if i == "object":
type_dict = {'type': 'categorical'}
series_structure.append(type_dict)
elif i == "boolean"... | [
"You seem to confuse list.append with Series.append. As per the documentation: the latter expects a \"Series or list/tuple of Series\", hence the error. Apart from that, (1) the method is deprecated, and (2) \"growing\" a df or Series row-wise is generally an ill-advised practice (see this post).\nOne remedy could ... | [
1,
0
] | [] | [] | [
"append",
"dictionary",
"python",
"series",
"typeerror"
] | stackoverflow_0074268896_append_dictionary_python_series_typeerror.txt |
Q:
Reading a particular row in a CSV for a given value X, Y returning variable Z
I have three columns in the CSV file storing the value of X, Y, and Z.
These variables are not related by any equation. I want to get the Z value from the given data for Corresponding X and Y values I got from the equations.
Also, the gi... | Reading a particular row in a CSV for a given value X, Y returning variable Z | I have three columns in the CSV file storing the value of X, Y, and Z.
These variables are not related by any equation. I want to get the Z value from the given data for Corresponding X and Y values I got from the equations.
Also, the given X and Y values come from different equations. Thus, it sometimes doesn't match ... | [
"You could use shortest Euclidean distance:\nexample.csv\nX,Y,Z\n-16.332,35.523,690\n-15.523,35.567,689\n\nCode:\nimport csv\n\nwith open('example.csv', newline='') as file:\n # read all the data converting columns to float\n reader = csv.reader(file)\n next(reader) # skip header\n data = [(float(x),flo... | [
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0074269019_csv_python.txt |
Q:
Unclear array of Array notation in numpy
I am on my way to understand a vectorized approach to calculating (and plotting) Julia sets. On the web, I found the following code (annotations are mainly mine, based on my growing understanding of the ideas behind the code):
import numpy as np
import matplotlib.pyplot as ... | Unclear array of Array notation in numpy | I am on my way to understand a vectorized approach to calculating (and plotting) Julia sets. On the web, I found the following code (annotations are mainly mine, based on my growing understanding of the ideas behind the code):
import numpy as np
import matplotlib.pyplot as plt
c = -0.74543+0.11301j ... | [
"Yes, you can use an array to index another. In many many ways. That a complex matter. And even if I flatter myself to understand numpy quite a bit now, I still sometimes encouter array indexation that make me scratch my head a little bit before I understand.\nBut this case is not a very complex one\nM=np.array([[1... | [
2
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074268620_arrays_numpy_python.txt |
Q:
Python MemoryError not raised - invokes OOM-Killer instead?
I've got a python application which uses a lot of memory, which should be fine as I handle it within loop with try / except MemoryError. Unfortunately, the MemoryError exception is never raised - before that happens, python is killed (on Debian Linux) by... | Python MemoryError not raised - invokes OOM-Killer instead? | I've got a python application which uses a lot of memory, which should be fine as I handle it within loop with try / except MemoryError. Unfortunately, the MemoryError exception is never raised - before that happens, python is killed (on Debian Linux) by the OOM Killer.
Question is why... and how I can catch the error... | [
"numpy tends to put everything in memory, so you can check how many video files you can have in memory at the same time.\n\"Simple\" test of how many files you can load into memory\nimport numpy as np\nimport sys\nimport math\nimport random\n\n\ndef real_size(obj):\n size_bytes = sys.getsizeof(obj)\n if size_... | [
0
] | [] | [] | [
"linux",
"memory",
"out_of_memory",
"python"
] | stackoverflow_0052248531_linux_memory_out_of_memory_python.txt |
Q:
Cross-compiling (unixlike to windows) with PyO3 and Maturin
I'm wondering if anyone has experience with cross-compiling to windows with pyo3 and maturin.
The pyo3 docs say:
Cross compiling PyO3 modules is relatively straightforward and
requires a few pieces of software:
A toolchain for your target. The appropri... | Cross-compiling (unixlike to windows) with PyO3 and Maturin | I'm wondering if anyone has experience with cross-compiling to windows with pyo3 and maturin.
The pyo3 docs say:
Cross compiling PyO3 modules is relatively straightforward and
requires a few pieces of software:
A toolchain for your target. The appropriate options in your Cargo
.config for the platform you're targe... | [
"The goal is a wheel per Python version / architecture / OS.\nAn easy way to achieve this is through external runners (e.g. gitub runners) and an action that compiles the package using maturin for each of the platforms.\nHere is how hyperjson does it.\n",
"pyo3 now has experimental Windows feature to bypass this ... | [
5,
1
] | [] | [] | [
"cross_compiling",
"pyo3",
"python",
"rust"
] | stackoverflow_0060460934_cross_compiling_pyo3_python_rust.txt |
Q:
How to save figure in matplotlib ajusted to the object size?
Hello everyone I am trying to save the figures from matplotlib. It saves with blank spaces around the figure, I mean It adds space, It is no saved with ajusted object size. It is very easy to edit them in Inkscape (I make that in this software), but tha... | How to save figure in matplotlib ajusted to the object size? | Hello everyone I am trying to save the figures from matplotlib. It saves with blank spaces around the figure, I mean It adds space, It is no saved with ajusted object size. It is very easy to edit them in Inkscape (I make that in this software), but that's not nice when there are more than 50 figures.
I do that becaus... | [
"Use constrained layout in:\nplt.figure function\n# 3.5.3 and 3.6\nfig = plt.figure(figsize=(8, 6), layout=\"constrained\")\nfig.add_subplot()\nplt.plot([1, 2], [3, 4])\n\nplt.subplots function\n# 3.5.3 and 3.6\nfig, ax = plt.subplots(figsize=(8, 6), layout=\"constrained\")\nax.plot([1, 2], [3, 4])\n\nSet layout on... | [
0
] | [] | [] | [
"figure",
"matplotlib",
"python",
"save",
"savefig"
] | stackoverflow_0074267842_figure_matplotlib_python_save_savefig.txt |
Q:
How to automatically run a Python script in the cloud on scheduled days
I have a Google Colab notebook. This notebook has to be ran every few days. Is there a way in which I can run a python script in the cloud on scheduled days?
A:
You'll need a server or cloud platform to host your code and schedule it to run ... | How to automatically run a Python script in the cloud on scheduled days | I have a Google Colab notebook. This notebook has to be ran every few days. Is there a way in which I can run a python script in the cloud on scheduled days?
| [
"You'll need a server or cloud platform to host your code and schedule it to run in that environment. I don't think it's possible in Colab.\nHave a look at Heroku Scheduler (a free option): https://devcenter.heroku.com/articles/clock-processes-python\nOther options might be AWS, Google, or Python Anywhere, as menti... | [
0
] | [] | [] | [
"cloud",
"python"
] | stackoverflow_0074269190_cloud_python.txt |
Q:
Trying to understand how variable swapping is used to update a 2d grid
I have the following code used to simulate 2D diffusion.
import time
grid_shape = (640, 640)
@profile
def evolve(grid, dt, out, D=1.0):
xmax, ymax = grid_shape # width and height of the matrix
for i in range(xmax):
for j in ... | Trying to understand how variable swapping is used to update a 2d grid | I have the following code used to simulate 2D diffusion.
import time
grid_shape = (640, 640)
@profile
def evolve(grid, dt, out, D=1.0):
xmax, ymax = grid_shape # width and height of the matrix
for i in range(xmax):
for j in range(ymax):
grid_xx = (
grid[(i + 1) % xmax][j]... | [
"TLDR: to use that no longer needed matrix as an output for next iteration.\nAs you wrote in comment to your answer:\n\nThe code is indeed trying to show a memory efficient approach...\n\nAnd swapping is meant to keep memory efficiency low.\nIn the algorithm you need two matrices in memory, one for input, one for o... | [
0
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0074255475_optimization_python.txt |
Q:
Scrollbar in TKinter class is not interactive
I have a lot of Labels in a frame in TKinter. I would like a scrollbar to see all the labels that appear out of the screen. What I have currently tried does not work. Here is a MWE:
from tkinter import *
from tkinter import ttk
import tkinter.font as font
from tkinter ... | Scrollbar in TKinter class is not interactive | I have a lot of Labels in a frame in TKinter. I would like a scrollbar to see all the labels that appear out of the screen. What I have currently tried does not work. Here is a MWE:
from tkinter import *
from tkinter import ttk
import tkinter.font as font
from tkinter import Tk
from PIL import Image, ImageTk
fontcolor... | [
"You need to make sure that you update the scrollregion whenever you add or remove data to the canvas, or when the data on the canvas changes size. Your code only updates it when the canvas itself is resized.\n"
] | [
0
] | [] | [] | [
"python",
"scrollbar",
"tkinter",
"tkinter_canvas"
] | stackoverflow_0074268251_python_scrollbar_tkinter_tkinter_canvas.txt |
Q:
Numpy: getting clusters from a 2d array black/white image mask
I have a numpy array with dimensions (512, 512, 3), which represents an RGB image. The image is a simple black and white mask, visualisation:
My goal is to identify the x largest clusters of white pixels in this mask and produce new images exclusive t... | Numpy: getting clusters from a 2d array black/white image mask | I have a numpy array with dimensions (512, 512, 3), which represents an RGB image. The image is a simple black and white mask, visualisation:
My goal is to identify the x largest clusters of white pixels in this mask and produce new images exclusive to each cluster. For example, for the image above, if x = 2, my desir... | [
"find your points like this:\nim = Image.open('Nkuf9.png')\ndata = np.array(im)[:,:,0]\nwpoint = np.where(data == 255)\npoints = set((x, y) for x, y in zip(*wpoint) )\n\nand a simple dfs to find each connected region, you could put all in a class.\ndef generate_neighbours(point):\n neighbours = [\n (1, -1... | [
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074268822_numpy_python.txt |
Q:
django.db.utils.ProgrammingError: relation already exists
I'm trying to set up the tables for a new django project (that is, the tables do NOT already exist in the database); the django version is 1.7 and the db back end is PostgreSQL. The name of the project is crud. Results of migration attempt follow:
python m... | django.db.utils.ProgrammingError: relation already exists | I'm trying to set up the tables for a new django project (that is, the tables do NOT already exist in the database); the django version is 1.7 and the db back end is PostgreSQL. The name of the project is crud. Results of migration attempt follow:
python manage.py makemigrations crud
Migrations for 'crud':
0001_init... | [
"This works pretty fine\n./manage.py migrate --fake default\n\nhttps://docs.djangoproject.com/en/2.2/ref/django-admin/#cmdoption-migrate-fake\n",
"Do python manage.py migrate --fake initally.\nhttps://docs.djangoproject.com/en/3.2/ref/django-admin/#django-admin-migrate\n",
"I've faced similar issue when added c... | [
108,
71,
15,
10,
8,
6,
5,
4,
4,
4,
3,
2,
2,
1,
1,
1,
0
] | [
"Do not try to use --fake, because with this you risk corrupting your database.\nInstead, you can backup your current database, recreate it, and then apply backup.\n\nCreate backup: pg_dump -F c -v -h localhost <database_name> -f tmp/<pick_a_file_name>.psql\n\nRecreate it: rails db:drop db:create\n\nRestore backup:... | [
-1
] | [
"django",
"postgresql",
"python",
"ubuntu"
] | stackoverflow_0029830928_django_postgresql_python_ubuntu.txt |
Q:
Save pretty table output as a pandas data frame
How to convert the output I get from a pretty table to pandas dataframe and save it as an excel file.
My code which gets the pretty table output
from prettytable import PrettyTable
prtab = PrettyTable()
prtab.field_names = ['Item_1', 'Item_2']
for item in Items_2:... | Save pretty table output as a pandas data frame | How to convert the output I get from a pretty table to pandas dataframe and save it as an excel file.
My code which gets the pretty table output
from prettytable import PrettyTable
prtab = PrettyTable()
prtab.field_names = ['Item_1', 'Item_2']
for item in Items_2:
prtab.add_row([item, difflib.get_close_matche... | [
"I found this method recently.\npretty_table.get_csv_string()\nthis will convert it to a csv string where you could write to a csv file.\nI use it like this:\ntbl_as_csv = pretty_table.get_csv_string().replace('\\r','')\n\ntext_file = open(\"output_path.csv\", \"w\")\nn = text_file.write(tbl_as_csv)\ntext_file.clos... | [
0,
-3
] | [] | [] | [
"python"
] | stackoverflow_0054918016_python.txt |
Q:
How can I convert a list in a DF column into comma separated values?
Right now I have a DataFrame that outputs to a CSV file. If I were to print out the "Affected IP Address" column, it would look like this:
['10.0.7.248']
['10.0.7.248', '10.0.8.56']
['10.0.6.72']
['10.0.6.72', '10.0.5.46']
['10.0.9.126']
['10.0.9... | How can I convert a list in a DF column into comma separated values? | Right now I have a DataFrame that outputs to a CSV file. If I were to print out the "Affected IP Address" column, it would look like this:
['10.0.7.248']
['10.0.7.248', '10.0.8.56']
['10.0.6.72']
['10.0.6.72', '10.0.5.46']
['10.0.9.126']
['10.0.9.126', '10.0.7.248']
['10.0.9.126', '10.0.7.248', '10.0.8.56']
['10.0.6.72... | [
"Here are few ways to do it\nIf you post the data as a code, it takes away the assumptions I made in creating the data frame to answer the question.\n# if its of type list, then iterate through and concat with ','\ndf['IP'].apply(lambda x: ', '.join(x))\n\n0 10.0.7.248\n1 10... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074269135_pandas_python.txt |
Q:
Matplotlib - Tight layout of multiple subplots with colorbar
I have a series of subplots in a single row, all sharing the same colorbar and I would like to use plt.tight_layout().
However when used naively, the colorbar messes everything up. Luckily, I found this in the matplotlib documentation, but it works only ... | Matplotlib - Tight layout of multiple subplots with colorbar | I have a series of subplots in a single row, all sharing the same colorbar and I would like to use plt.tight_layout().
However when used naively, the colorbar messes everything up. Luckily, I found this in the matplotlib documentation, but it works only for one subplot.
Minimal Working Example
I tried to adapt it to mu... | [
"With the newest matplotlib (3.6), there is a new option layout='compressed' for this situation:\nimport matplotlib.pyplot as plt\nimport numpy as np\n\narr = np.arange(100).reshape((10, 10))\nfig, ax = plt.subplots(ncols=2, figsize=(4, 2), layout='compressed')\nim0 = ax[0].imshow(arr)\nim1 = ax[1].imshow(arr)\n\np... | [
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074267861_matplotlib_python.txt |
Q:
Scraping More than rendered Data with Beautiful Soup
I'm scraping apps names from Google Play Store and for each URL as input I get only 60apps (because the website rendered 60apps if the user doesn't scroll down). How is it working and how can I scrape all the apps from a page using BeautifulSoup and/or Selenium ... | Scraping More than rendered Data with Beautiful Soup | I'm scraping apps names from Google Play Store and for each URL as input I get only 60apps (because the website rendered 60apps if the user doesn't scroll down). How is it working and how can I scrape all the apps from a page using BeautifulSoup and/or Selenium ?
Thank you
Here is my code :
urls = []
urls.extend(["htt... | [
"In this case You need to use Selenium . I try it for you an get the all apps . I will try to explain hope will understand.\nUsing Selenium is more powerful than other Python function .I used ChromeDriver so If you don't install yet You can install it in \n\nhttp://chromedriver.chromium.org/\n\nfrom time import sle... | [
2,
1
] | [] | [] | [
"beautifulsoup",
"python",
"selenium"
] | stackoverflow_0054773357_beautifulsoup_python_selenium.txt |
Q:
Zero padding slice past end of array in numpy
In numpy, is there a way to zero pad entries if I'm slicing past the end of the array, such that I get something that is the size of the desired slice?
For example,
>>> x = np.ones((3,3,))
>>> x
array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
... | Zero padding slice past end of array in numpy | In numpy, is there a way to zero pad entries if I'm slicing past the end of the array, such that I get something that is the size of the desired slice?
For example,
>>> x = np.ones((3,3,))
>>> x
array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
>>> x[1:4, 1:4] # would behave as x[1:3, 1:3] by de... | [
"As far as I know there is no numpy solution (nor in any package I know) for such a problem. You could do it yourself but it will be a really, really complicated one even if you only want basic slicing. I would suggest you manually np.pad your array and simply offset your start/stop/step before you actually slice i... | [
6,
4,
2,
1,
0,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0041153803_numpy_python.txt |
Q:
Reversing in Python
I have two question about reversing in python.
I am learning python and I was doing a practice problem where we need to find if the given word is a palindrome. I thought I reverse the word and compare them. Below is my code to reverse a word or any series.
def is_palindrome(word):
list_word =... | Reversing in Python | I have two question about reversing in python.
I am learning python and I was doing a practice problem where we need to find if the given word is a palindrome. I thought I reverse the word and compare them. Below is my code to reverse a word or any series.
def is_palindrome(word):
list_word = list(word)
reversed_li... | [
"I agree 100% with what others said in the comments. Here is the way I would do it.\ndef is_palindrome(word: str):\n return word == word[::-1]\n\n"
] | [
1
] | [] | [] | [
"python",
"reverse"
] | stackoverflow_0074269292_python_reverse.txt |
Q:
Is there any way to create multiple bounding boxes around non zero numpy array values?
I have a numpy array of an image. I have set non zero values for my region of interest and for rest I have set value as 0. Now if I were to create a single bounding box, I could check for 1st occurance and last occurance of non ... | Is there any way to create multiple bounding boxes around non zero numpy array values? | I have a numpy array of an image. I have set non zero values for my region of interest and for rest I have set value as 0. Now if I were to create a single bounding box, I could check for 1st occurance and last occurance of non zero value and get the coordinates. But what if the non zero values are on different places?... | [
"I tested similar code in my own project, but I didn't test this particular snippet. Comment if you encounter any bugs.\nimport cv2\nimport numpy as np\n\nA = np.array([[0, 0, 0, 0, 0, 0, 0],\n [1, 1, 0, 0, 0, 0, 0],\n [1, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 1, 1],\n [0, 0, ... | [
0
] | [] | [] | [
"bounding_box",
"image_preprocessing",
"numpy",
"opencv",
"python"
] | stackoverflow_0074265550_bounding_box_image_preprocessing_numpy_opencv_python.txt |
Q:
Python: Logical flow for setup and validation
I am having trouble figuring out how to structure the logical flow of my python application's initial setup module. I have a number of functions that perform small steps in finding that required config files are present, validating them if they are there, creating the... | Python: Logical flow for setup and validation | I am having trouble figuring out how to structure the logical flow of my python application's initial setup module. I have a number of functions that perform small steps in finding that required config files are present, validating them if they are there, creating them if they are not, testing a login with the validat... | [
"Going to close this question. Because each function has only 1 possible next step if it evaluates to True, I should be able to call the next function in sequence within the function, provided the original logical test evaluates to true. Then, in my else clauses, I will just kick it back to the step that needs to b... | [
0
] | [] | [] | [
"logic",
"python"
] | stackoverflow_0074267679_logic_python.txt |
Q:
NameError occurs when running program, how to fix it?
Basically, my code creates different fractals and displays them on a canvas. But when I went to run the program this error message popped up:(class SierpinskiTriangle(Fractal):NameError: name 'Fractal' is not defined). I know this specific error occurs when a v... | NameError occurs when running program, how to fix it? | Basically, my code creates different fractals and displays them on a canvas. But when I went to run the program this error message popped up:(class SierpinskiTriangle(Fractal):NameError: name 'Fractal' is not defined). I know this specific error occurs when a variable isn't defined or isn't defined right but I can't fi... | [
"Regarding your code:\nclass SierpinskiTriangle(Fractal):\n\nThis is trying to define the SierpinskiTriangle class as a derived class from Fractal.\nYou do not define (or import) Fractal at any point in that code, which is why you're getting the error.\nHence the solution is to either define or import the Fractal c... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074269507_python.txt |
Q:
PyThreadState_SetAsyncExc has no effect
I'm using multiple interpreters with multiple threads, and I'm trying to use PyThreadState_SetAsyncExc to stop a script, but it has no effect:
void stop()
{
PyThreadState *ts = PyThreadState_Swap(this->tstate);
PyObject *exc = PyObject_CallObject(PyExc_Exception, Py_... | PyThreadState_SetAsyncExc has no effect | I'm using multiple interpreters with multiple threads, and I'm trying to use PyThreadState_SetAsyncExc to stop a script, but it has no effect:
void stop()
{
PyThreadState *ts = PyThreadState_Swap(this->tstate);
PyObject *exc = PyObject_CallObject(PyExc_Exception, Py_BuildValue("(s)", "stopped"));
int n = Py... | [
"It works for me in Linux now:\ne.g: if Threaded to run Flask Web Server in background around other python code\nimport threading\nimport ctypes\nwebserverurl = 127.0.0.1\nwebserverport = 8080\n\nclass thread_with_exception(threading.Thread):\n def __init__(self, name):\n threading.Thread.__init__(self)\... | [
0
] | [] | [] | [
"python",
"python_c_api",
"python_multithreading"
] | stackoverflow_0059249669_python_python_c_api_python_multithreading.txt |
Q:
python decorate class method sending a parameter to the decorator
I have the following class in python:
class MatrixOfCarriers(DataLoader):
def load_data(self):
brands = self.brands
try:
data = self._load_data()
print("'Carrier Matrix' data loaded successfully.\n")
... | python decorate class method sending a parameter to the decorator | I have the following class in python:
class MatrixOfCarriers(DataLoader):
def load_data(self):
brands = self.brands
try:
data = self._load_data()
print("'Carrier Matrix' data loaded successfully.\n")
except Exception as e:
print(
"\nCouldn'... | [
"If you are always decorating a method, and will always need to get the .brands attribute, there are two things that can be changed: first, Python will pass the instance itself as the first argument to your wrapper - just as it pass the self parameter - so you can just use the .brands attribute in that first parame... | [
0
] | [] | [] | [
"decorator",
"python",
"python_decorators"
] | stackoverflow_0074269407_decorator_python_python_decorators.txt |
Q:
Python Relative Path Import: Import packages from another project directory
I know there are many questions on this topic but none of them helped me much.
I have a python project directory i.e. git_project (git repository). What I want is to create a separate directory called notebooks where I will keep all my not... | Python Relative Path Import: Import packages from another project directory | I know there are many questions on this topic but none of them helped me much.
I have a python project directory i.e. git_project (git repository). What I want is to create a separate directory called notebooks where I will keep all my notebooks for analysis using git_project. I don't want to put notebooks within the r... | [
"The issue was when you call open('config/cfg.json', 'r'), the path it opens was relative to the directory where the python code is launched. In this case, it is your my_projects/notebook directory. You can see this by adding the following prints in get_cfg() inside config.py:\nprint(os.getcwd()) # this prints o... | [
2,
0,
0,
0
] | [] | [] | [
"jupyter_notebook",
"python"
] | stackoverflow_0062705385_jupyter_notebook_python.txt |
Q:
list of list comparing
I want to compare the amount of values in a list of a list.
If there would be an empty list in the one of the "sub" lists, it should print "too short".
If the list is long enough, meaning that it has more or 1 value in it, it should print "good". how can I do this?
No library imports please.... | list of list comparing | I want to compare the amount of values in a list of a list.
If there would be an empty list in the one of the "sub" lists, it should print "too short".
If the list is long enough, meaning that it has more or 1 value in it, it should print "good". how can I do this?
No library imports please.
| [
"You can iterate through the sub-lists and check for len, or just for falsey for empty lists as Python evaluates [] as False.\nlists = [[1,2],[],[3,4,5]]\nfor l in lists:\n if len(l) < 1: #or just `if not l:`\n print('too short')\n else:\n print('good')\n\n",
"You need to iterate each element... | [
1,
0
] | [] | [] | [
"list",
"nested_lists",
"python"
] | stackoverflow_0074269496_list_nested_lists_python.txt |
Q:
How to insert a newline in printing list in itertools
I am permuting a few list. How to print the result in a newline?
Code:
import itertools
s=[ [ '1', '2','3'], ['a','b'],
['4','5','6','7'],
['f','g','e','y']]
print (list(itertools.product(*s,)))
Need Result:
#-- with a newline
1 a 4 f
1 a 4 g
1 a 4 e ... | How to insert a newline in printing list in itertools | I am permuting a few list. How to print the result in a newline?
Code:
import itertools
s=[ [ '1', '2','3'], ['a','b'],
['4','5','6','7'],
['f','g','e','y']]
print (list(itertools.product(*s,)))
Need Result:
#-- with a newline
1 a 4 f
1 a 4 g
1 a 4 e
1 a 4 y
Current Result:
#-- not very readable
[('1', 'a'... | [
"Unpack in print just like you already do in product...\nfor p in itertools.product(*s):\n print(*p)\n\n",
"You can unpack the tuples to f-strings, and join them all using \\n as a separator.\nimport itertools\n\ns=[ ['1', '2','3'], \n ['a','b'],\n ['4','5','6','7'],\n ['f','g','e','y'] ]\n\nprint('\\... | [
1,
0,
0
] | [] | [] | [
"python",
"text"
] | stackoverflow_0074269488_python_text.txt |
Q:
The birth date I'm trying to display is not in the format that I want: Day of week, Month Day, Year
I am trying to take user input of a birthday in form MM/DD/YY and change it so it prints day of week, month day, year. I am in an intro class, so I have no experience in this...simple solutions appreciated.
birthday... | The birth date I'm trying to display is not in the format that I want: Day of week, Month Day, Year | I am trying to take user input of a birthday in form MM/DD/YY and change it so it prints day of week, month day, year. I am in an intro class, so I have no experience in this...simple solutions appreciated.
birthday = input("Enter Birthday (MM/DD/YY): ")
birthday = datetime.strptime(birthday, "%m/%d/%y")
if birthday > ... | [
"The year must come first when fixing the datetime year. See help(datetime):\n>>> help(datetime)\nHelp on class datetime in module datetime:\n\nclass datetime(date)\n | datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n ...\n\nSo use the following:\nbirthday = datetime(fixed_birth_... | [
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0074269659_datetime_python.txt |
Q:
Pythonic way to filter a list of weakrefs
I really dislike this approach to loop a list of weakrefs, see if they're still not garbage collected and if they're not perform some operation on the item and then later remove all those stale refs from an array
remove_me = []
for ui_control in self.list_of_weak_r... | Pythonic way to filter a list of weakrefs | I really dislike this approach to loop a list of weakrefs, see if they're still not garbage collected and if they're not perform some operation on the item and then later remove all those stale refs from an array
remove_me = []
for ui_control in self.list_of_weak_references_to_UI_controls:
ui_control = ... | [
"Instead of creating and handling the weak references manually with weakref.ref, and then checking if they are alive like you do, just use one of the higher level containers on the weakref module.\nNot only dead references are removed automatically: any code needing the instances weak-referenced can just retrieve ... | [
1
] | [] | [] | [
"python",
"weak_references"
] | stackoverflow_0074261212_python_weak_references.txt |
Q:
Pythonic way to try reading a file and in case of exception fallback to alternate file
What is the Pythonic way to try reading a file and if this read throws an exception fallback to read an alternate file?
This is the sample code I wrote, which uses nested try-except blocks. Is this pythonic:
try:
with open(f... | Pythonic way to try reading a file and in case of exception fallback to alternate file | What is the Pythonic way to try reading a file and if this read throws an exception fallback to read an alternate file?
This is the sample code I wrote, which uses nested try-except blocks. Is this pythonic:
try:
with open(file1, "r") as f:
params = json.load(f)
except IOError:
try:
with open(fi... | [
"For two files the approach is in my opinion good enough.\nIf you had more files to fallback I would go with a loop:\nfor filename in (file1, file2):\n try:\n with open(filename, \"r\") as fin:\n params = json.load(f)\n break\n except IOError:\n pass\n except Exception as ex... | [
1,
0,
0,
0
] | [] | [] | [
"exception_handling",
"python",
"try_except"
] | stackoverflow_0045955479_exception_handling_python_try_except.txt |
Q:
Loop though decimal that is object type
Adress Rooms m2 Price Floor
196 Skanstes 29a 5 325 2800 24/24
12 Ausekļa 4 5 195 2660 7/7
7 Antonijas 17A 3 86 2200 6/6
31 Blaumaņa 16 4 136 1800 4/6
186 Rūpniecības 21k2 5 ... | Loop though decimal that is object type | Adress Rooms m2 Price Floor
196 Skanstes 29a 5 325 2800 24/24
12 Ausekļa 4 5 195 2660 7/7
7 Antonijas 17A 3 86 2200 6/6
31 Blaumaņa 16 4 136 1800 4/6
186 Rūpniecības 21k2 5 160 1700 7/7
233 Vesetas 24 ... | [
"First solution, using three categories as suggested in the question. Then applying a grouping by category to check the mean price as a simple comparison:\ndef floor_to_categories(floor_str):\n num1, num2 = floor_str.split(\"/\")\n if num1 == num2: return \"Top\"\n elif num1 == \"1\": return \"Bottom\"\n ... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074269705_pandas_python.txt |
Q:
Layer image on top of plot
I'm trying to plot different colors in nine rectangles on top of an image. The easiest solution I've come up with is to plot the rectangles and then layer a transparent background image over it. However when I try to do this the image always appears behind the triangles.
import matplotli... | Layer image on top of plot | I'm trying to plot different colors in nine rectangles on top of an image. The easiest solution I've come up with is to plot the rectangles and then layer a transparent background image over it. However when I try to do this the image always appears behind the triangles.
import matplotlib.pyplot as plt
from matplotlib.... | [
"New code:\nimage_link = r'image.png'\ndx = 301\ndy = 225\nxy0 = (68, 33)\n\nfig = plt.figure()\n\nax1 = fig.add_subplot(121)\nax1.add_patch(Rectangle(xy0 , dx, dy)) \nim1 = plt.imread(image_link)\nimplot1 = plt.imshow(im1, alpha=0.75, zorder=1)\n\nax2 = fig.add_subplot(122)\nax2.add_patch(Rectangle(xy0 , dx, dy)) ... | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074262943_matplotlib_python.txt |
Q:
Iterating through a list for specific instances
I have the following code:
paths = [['E', 'D', 'A', 'B'], ['E', 'D', 'A', 'C', 'B'], ['E', 'D', 'B'], ['E', 'D', 'C', 'B'], ['E', 'B'], ['E', 'C', 'B']]
Now, the lists inside a list represent node paths from start to end which were made using Networkx, however that ... | Iterating through a list for specific instances | I have the following code:
paths = [['E', 'D', 'A', 'B'], ['E', 'D', 'A', 'C', 'B'], ['E', 'D', 'B'], ['E', 'D', 'C', 'B'], ['E', 'B'], ['E', 'C', 'B']]
Now, the lists inside a list represent node paths from start to end which were made using Networkx, however that is some background information. My question is more s... | [
"You can use a use a set and .issubset() like this:\ndef pathways(letters, paths):\n ret = []\n letters = set(letters)\n for path in paths:\n if letters.issubset(path):\n ret.append(path)\n return ret\n\n\nletters = ['A', 'B', 'C', 'D', 'E']\npaths = [['E', 'D', 'A', 'B'], ['E', 'D', '... | [
5
] | [] | [] | [
"for_loop",
"list",
"python",
"python_3.x"
] | stackoverflow_0074269774_for_loop_list_python_python_3.x.txt |
Q:
bash: /home/--------/.local/bin/pip3: /usr/bin/python3: bad interpreter: No such file or directory
I recently had my python versions messed up as they weren't there in my /usr/bin. Now I have mostly gotten it fixed so when I type:
------@--------:~$ python3
Python 3.8.5 (default, Oct 30 2022, 19:55:55) [GCC 9.4.... | bash: /home/--------/.local/bin/pip3: /usr/bin/python3: bad interpreter: No such file or directory | I recently had my python versions messed up as they weren't there in my /usr/bin. Now I have mostly gotten it fixed so when I type:
------@--------:~$ python3
Python 3.8.5 (default, Oct 30 2022, 19:55:55) [GCC 9.4.0]
on linux Type "help", "copyright", "credits" or "license" for more information.
and when I type:
--... | [
"You can see where your pip3 file is:\nwhich pip3\n\nThat should tell you the full path, which is\n/home/jayakumar/.local/bin/pip3\nYou can view that file like this:\nmore /home/jayakumar/.local/bin/pip3\n\nIn the first line, notice that it has #!/usr/bin/python3 or\nThat directive tells your system where to look f... | [
0
] | [] | [] | [
"dependencies",
"pip",
"python",
"python_3.x"
] | stackoverflow_0074269698_dependencies_pip_python_python_3.x.txt |
Q:
Scraping a table Including hyperlinks and upload it to google sheet using python
I'm trying to scrape a table and keep any hyperlinks included then upload the result to a google sheet
I have finished the first part using this code:
from bs4 import BeautifulSoup
import requests
import pandas as pd
import re
# Defin... | Scraping a table Including hyperlinks and upload it to google sheet using python | I'm trying to scrape a table and keep any hyperlinks included then upload the result to a google sheet
I have finished the first part using this code:
from bs4 import BeautifulSoup
import requests
import pandas as pd
import re
# Define URL
url = 'https://www.marefa.org/%D9%82%D8%A7%D8%A6%D9%85%D8%A9_%D8%A3%D9%81%D8%B6%... | [
"I'm not sure how to write hyperlinks in a way that Sheets will recognize them as hyperlinks, but the following will create extra columns to hold the links:\nindiatable_headers = [col for cols in [\n [chead, chead+' [link]'] for chead in [\n c.get_text(strip=True) for c in \n indiatable.select_one(... | [
1
] | [] | [] | [
"beautifulsoup",
"pandas",
"python",
"python_requests",
"web_scraping"
] | stackoverflow_0074263905_beautifulsoup_pandas_python_python_requests_web_scraping.txt |
Q:
Django: How to add to an ArrayField?
I have some questions about the ArrayField mentioned here: https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/fields/#django.contrib.postgres.fields.ArrayField
How do you add to an ArrayField? It's clear you can treat it like a regular field and do things like
my_arra... | Django: How to add to an ArrayField? | I have some questions about the ArrayField mentioned here: https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/fields/#django.contrib.postgres.fields.ArrayField
How do you add to an ArrayField? It's clear you can treat it like a regular field and do things like
my_array_field = []
my_array_field.save()
But wh... | [
"\ndo we need to call save()?\n\nYes, we need to call the save() method to COMMIT the changes to Database. Unless calling the save() method, the value only persists in the scope of the variable, as the python list. So, calling the save() is a must do thing while updating the values.\n\nhow to add values to array fi... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0063698215_django_python.txt |
Q:
Create a bar chart in python but seperate column by a key
I have a dataframe that looks like this
d = {'total_time':[1,2,3,4],
'date': ['2022-09-11', '2022-09-11', '2022-09-13', '2022-09-13'],
'key': ['A', 'B', 'A', 'B']}
df_sample = pd.DataFrame(data=d)
df_sample.head()
I want to compare total_time acros... | Create a bar chart in python but seperate column by a key | I have a dataframe that looks like this
d = {'total_time':[1,2,3,4],
'date': ['2022-09-11', '2022-09-11', '2022-09-13', '2022-09-13'],
'key': ['A', 'B', 'A', 'B']}
df_sample = pd.DataFrame(data=d)
df_sample.head()
I want to compare total_time across the data that should be in the x-axis but I want to compare t... | [
"You can use seaborn and pass the key column to hue argument :\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sb\n\n\nd = {'total_time':[1,2,3,4],\n 'date': ['2022-09-11', '2022-09-11', '2022-09-13', '2022-09-13'],\n 'key': ['A', 'B', 'A', 'B']}\ndf_sample = pd.DataFrame(data=d)\n\np... | [
1,
0
] | [] | [] | [
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074269568_matplotlib_pandas_python.txt |
Q:
How to encode strings to API requests in Python?
I'm trying to filter data from an API request to get only registers that were created or updated yesterday.
There are some notes listed in the documentation, some are shown below.
2. The query must be URL encoded
4. Query string must be enclosed between a pair of do... | How to encode strings to API requests in Python? | I'm trying to filter data from an API request to get only registers that were created or updated yesterday.
There are some notes listed in the documentation, some are shown below.
2. The query must be URL encoded
4. Query string must be enclosed between a pair of double quotes and can have up to 512 characters
5. Logic... | [
"Here's the result if you let requests do the encoding. This is proper URL encoding:\nimport datetime as dt\nimport urllib.parse\nimport requests\n\nurl = \"http://timr.example.com/api/v2/search/tickets\"\napi_key = \"7\"\nparams={}\n\nyesterday = dt.date.today() - dt.timedelta(days = 1)\nquery = f'\"created_at:>{... | [
1
] | [] | [] | [
"python",
"python_requests",
"python_requests_html",
"urlencode"
] | stackoverflow_0074269795_python_python_requests_python_requests_html_urlencode.txt |
Q:
Invalid trace folder when profiling in Jax
I'm trying to test out the Jax profiler by running the example provided in the docs:
import jax
with jax.profiler.trace("/tmp/jax-trace", create_perfetto_link=True):
# Run the operations to be profiled
key = jax.random.PRNGKey(0)
x = jax.random.normal(key, (5000, ... | Invalid trace folder when profiling in Jax | I'm trying to test out the Jax profiler by running the example provided in the docs:
import jax
with jax.profiler.trace("/tmp/jax-trace", create_perfetto_link=True):
# Run the operations to be profiled
key = jax.random.PRNGKey(0)
x = jax.random.normal(key, (5000, 5000))
y = x @ x
y.block_until_ready()
Howe... | [
"There is an open issue on this problem in github. It seems that TensorFlow profiler is no longer dumping the trace.json file.\n"
] | [
0
] | [] | [] | [
"jax",
"python"
] | stackoverflow_0074149439_jax_python.txt |
Q:
What did I do wrong in this for loop attempt?
I've been following CS Dojo's python series and learning on my own. At the end of the for loop tutorial, he asks us to find the sum of every multiple of 3 & 5 in range(1, 100). I did it on my own, but it was different from everyone else's in the comments. Did it again ... | What did I do wrong in this for loop attempt? | I've been following CS Dojo's python series and learning on my own. At the end of the for loop tutorial, he asks us to find the sum of every multiple of 3 & 5 in range(1, 100). I did it on my own, but it was different from everyone else's in the comments. Did it again and got the same answer as everyone.
First attempt:... | [
"In your first for loop, one of your conditions is \"elements % 3\". Since you did not set not actually check if this is == 0, it assumes that you are checking elements % 3 == True. This will be true whenever elements % 3 is nonzero (0 is False and everything else is True). Also, the second part of your conditional... | [
0
] | [] | [] | [
"for_loop",
"python",
"python_3.x"
] | stackoverflow_0074269775_for_loop_python_python_3.x.txt |
Q:
JSON in List to Pandas Data Frame
I have a list with some empty values and some w/ nested JSON. The data looks like this:
[[],
[],
[{'id': 32,
'globalId': 'a73dec29-9431-4806-a4f7-0667872746ce',
'parentGlobalId': 'ad21cef5-cfa7-4e52-ab8f-8b5da30020af',
'name': 'IMG_9774.jpeg',
'contentType': 'image/... | JSON in List to Pandas Data Frame | I have a list with some empty values and some w/ nested JSON. The data looks like this:
[[],
[],
[{'id': 32,
'globalId': 'a73dec29-9431-4806-a4f7-0667872746ce',
'parentGlobalId': 'ad21cef5-cfa7-4e52-ab8f-8b5da30020af',
'name': 'IMG_9774.jpeg',
'contentType': 'image/jpeg',
'size': 157893,
'keywords'... | [
"If lst is your list from the question you can do:\ndf = pd.DataFrame([d for l in lst for d in (l or [{}])])\nprint(df)\n\nPrints:\n id globalId parentGlobalId name contentType size keywords exifInfo\n0 NaN ... | [
1
] | [] | [] | [
"json",
"list",
"pandas",
"python"
] | stackoverflow_0074269821_json_list_pandas_python.txt |
Q:
Scrapy Response is returning 'None' even with correct syntax
I'm trying to get the item's names in a dictionary like this:
import scrapy
class TerrorSpider(scrapy.Spider):
name = 'terror'
start_urls = ['http://books.toscrape.com/catalogue/category/books/travel_2/index.html']
def parse(self, response)... | Scrapy Response is returning 'None' even with correct syntax | I'm trying to get the item's names in a dictionary like this:
import scrapy
class TerrorSpider(scrapy.Spider):
name = 'terror'
start_urls = ['http://books.toscrape.com/catalogue/category/books/travel_2/index.html']
def parse(self, response):
for filme in response.css('h3 a'):
yield{
... | [
"You are trying to get the selector for the selector you have already chosen... In other words all you need to do is call .css('::text').get() on the fileme variables. There is no need to repeat the h3 and a tag elements because you already chose those in the earlier selector.\nimport scrapy\n\n\nclass TerrorSpide... | [
0
] | [] | [] | [
"python",
"scrapy"
] | stackoverflow_0074269338_python_scrapy.txt |
Q:
How to count how many times a value is preceded and followed by a sequence of another value?
Let's consider the following Series:
0 A
1 B
2 A
3 C
4 C
5 D
6 A
7 B
8 A
Let's also suppose that we'd like to see how many times B is preceded and followed by a single 'A'. In the example above... | How to count how many times a value is preceded and followed by a sequence of another value? | Let's consider the following Series:
0 A
1 B
2 A
3 C
4 C
5 D
6 A
7 B
8 A
Let's also suppose that we'd like to see how many times B is preceded and followed by a single 'A'. In the example above, this happens 2 times!
One way to calculate this would be:
(s.shift(-1).eq('A') & s.shift(1).eq('... | [
"Naive version\nLet starts with the naive version (what not to do! But it can be used as a basis to validate the less naive one)\ndef naive(df, A, B, n):\n tot=0\n for i in range(n, len(df)-n):\n if df.iloc[i, 0]==A:\n ok=True\n for j in range(i-n, i):\n if df.iloc[... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074269446_pandas_python.txt |
Q:
In Python (BeautifulSoup), how do I prevent a string from being interpreted as scientific notation?
I'm using BeautifulSoup to parse XML and return a 5-character string. Python is interpreting some of the strings as scientific notation (e.g., 0E001, 1E001), but I need to get the string itself.
I've tried applying ... | In Python (BeautifulSoup), how do I prevent a string from being interpreted as scientific notation? | I'm using BeautifulSoup to parse XML and return a 5-character string. Python is interpreting some of the strings as scientific notation (e.g., 0E001, 1E001), but I need to get the string itself.
I've tried applying str(some_code) and f"{some_code}" in multiple places, but can't seem to figure out how to force Python to... | [
"I think your code works correctly: It may be that the 1E001 is being parsed into scientific notation by the program used for looking at your .csv file (i.e. Excel).\nHowever, from my perspective, it appears that the output eccn identifier is correct (unless I'm missing something). Here's a screenshot from the outp... | [
3
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0074269460_beautifulsoup_python.txt |
Q:
Setup redis-cluster with Django
Problem Statement
Use django-redis with redis clustering.
An error occurs when interacting with the cache.
The error points to a pickle operation on an instance of the ConnectionPool class where
one of it's attributes, a thread lock, cannot be serialized and results in the following... | Setup redis-cluster with Django | Problem Statement
Use django-redis with redis clustering.
An error occurs when interacting with the cache.
The error points to a pickle operation on an instance of the ConnectionPool class where
one of it's attributes, a thread lock, cannot be serialized and results in the following error:
TypeError: cannot pickle '_... | [
"The problem is django_redis.pool.ConnectionFactory.get_connection\nmakes a pool (of class redis.connection.ConnectionPool)\n pool = self.get_or_create_connection_pool(params)\n return self.redis_client_cls(\n connection_pool=pool, **self.redis_client_cls_kwargs)\n\nand passes it to\nredis.cluster.RedisClust... | [
0
] | [] | [] | [
"caching",
"django",
"python",
"redis",
"redis_cluster"
] | stackoverflow_0072347975_caching_django_python_redis_redis_cluster.txt |
Q:
Getting this error while using jupyter notebook "Could not build wheels for psutil, which is required to install pyproject.toml-based projects. "
I am new to python and have installed python 3.11 and in vs code i have installed the python extension. But when i try to create a jupyter notebook and execute a code it... | Getting this error while using jupyter notebook "Could not build wheels for psutil, which is required to install pyproject.toml-based projects. " | I am new to python and have installed python 3.11 and in vs code i have installed the python extension. But when i try to create a jupyter notebook and execute a code it shows me this dialog
I click on install and then i get this error
Not able to know what exactly it means. Any help would be great. Thanks in advance... | [
"Update: I was able to manually fix the issue by following the description in my links provided\nStep 1: Manually download the psutil wheel\nA slightly older version than current (psutil-5.9.0 instead of psutil-5.9.3) is available for download here\nI have used psutil-5.9.0-cp311-cp311-win_amd64.whl running Windows... | [
0
] | [] | [] | [
"jupyter_notebook",
"python",
"python_3.x"
] | stackoverflow_0074217208_jupyter_notebook_python_python_3.x.txt |
Q:
Trouble with Tkinter coordinates and intialization using place()
Very new to tkinter and came across my first major roadbloack. I have a list of labels that is follows around a parent label. I have a function that displays all of these labels based off the coordinates of this parent. Right now the coordinates f... | Trouble with Tkinter coordinates and intialization using place() | Very new to tkinter and came across my first major roadbloack. I have a list of labels that is follows around a parent label. I have a function that displays all of these labels based off the coordinates of this parent. Right now the coordinates for the parent label are set at 0,0 no matter where I place it.
Here is... | [
"While I don't normally recommend using place, you can achieve what you want by place's ability to do relative placement. Since we can't reproduce your problem from the code snippets you've presented, here's a simple example that illustrates the concept.\nThe key is using the in_ parameter which defines what the re... | [
0
] | [] | [] | [
"label",
"python",
"tkinter",
"user_interface"
] | stackoverflow_0074269479_label_python_tkinter_user_interface.txt |
Q:
Relative imports in Python 3
I want to import a function from another file in the same directory.
Usually, one of the following works:
from .mymodule import myfunction
from mymodule import myfunction
...but the other one gives me one of these errors:
ImportError: attempted relative import with no known parent pa... | Relative imports in Python 3 | I want to import a function from another file in the same directory.
Usually, one of the following works:
from .mymodule import myfunction
from mymodule import myfunction
...but the other one gives me one of these errors:
ImportError: attempted relative import with no known parent package
ModuleNotFoundError: No mod... | [
"\nunfortunately, this module needs to be inside the package, and it also\nneeds to be runnable as a script, sometimes. Any idea how I could\nachieve that?\n\nIt's quite common to have a layout like this...\nmain.py\nmypackage/\n __init__.py\n mymodule.py\n myothermodule.py\n\n...with a mymodule.py like th... | [
1086,
569,
253,
64,
36,
21,
14,
11,
11,
9,
8,
8,
6,
6,
6,
4,
3,
3,
2,
2,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0
] | [
"I had a similar problem and solved it by creating a symbolic link to the package in the working directory:\nln -s ../../../my_package my_package\nand then import it as usual:\nimport my_package\nI know this is more like a \"Linux\" solution rather than a \"Python\" solution. but it's a valid approach nonetheless.\... | [
-2
] | [
"python",
"python_3.x",
"python_import"
] | stackoverflow_0016981921_python_python_3.x_python_import.txt |
Q:
How would I call these functions together?
I have a set of different functions that I created and am required to use for a program and I need to figure out how to call them inside one function. Requirements for my code are as follows
The Input processing should only
be done using functions: getPackage, validPackag... | How would I call these functions together? | I have a set of different functions that I created and am required to use for a program and I need to figure out how to call them inside one function. Requirements for my code are as follows
The Input processing should only
be done using functions: getPackage, validPackage, getHours,
validHours, and program control con... | [
"getPackage() and getthehours() shouldn't take a parameter, they should return a value.\nThen you should call validPackage() and validhours() with the result that was returned. These functions should return a boolean indicating whether the input was valid. You can put these calls into a loop to keep asking until yo... | [
0
] | [] | [] | [
"function",
"python"
] | stackoverflow_0074269525_function_python.txt |
Q:
USBError: [Errno 13] Access denied (insufficient permissions)
This problem is old as the world. There are discussions and solutions available. It all boils down to update the rules file and give permissions. So I have followed the recipe. But I still have the same problem. here are screenshots showing I follow ins... | USBError: [Errno 13] Access denied (insufficient permissions) | This problem is old as the world. There are discussions and solutions available. It all boils down to update the rules file and give permissions. So I have followed the recipe. But I still have the same problem. here are screenshots showing I follow instructions.
Versions:
Python 2.7.12 (default, Dec 4 2017, 14:50:18)... | [
"Your rules look a little bit odd. Can you remove all of them and try this instead?\nSUBSYSTEM==\"usb\", ATTRS{idVendor}==\"0683\", MODE=\"0666\"\n\n",
"In case someone runs into this error again, I want to add to David Grayson's answer that you additionally have to refresh udev and unplug-and-replug the USB devi... | [
10,
3,
1,
0,
0
] | [] | [] | [
"python",
"ubuntu_16.04",
"usb"
] | stackoverflow_0050625363_python_ubuntu_16.04_usb.txt |
Q:
'EntryPoints' object has no attribute 'get' - Digital ocean
I have made a deplyoment to Digital ocean, on staging (Heroku server) the app is working well, but Digital ocean it's failing with the error below, what could be the issue :
AttributeError at /admin/
'EntryPoints' object has no attribute 'get'
Request Met... | 'EntryPoints' object has no attribute 'get' - Digital ocean | I have made a deplyoment to Digital ocean, on staging (Heroku server) the app is working well, but Digital ocean it's failing with the error below, what could be the issue :
AttributeError at /admin/
'EntryPoints' object has no attribute 'get'
Request Method: GET
Request URL: https://xxxx/admin/
Django Version: 3.1
... | [
"Because importlib-metadata releases v5.0.0 yesterday which it remove deprecated endpoint.\nYou can set importlib-metadata<5.0 in ur setup.py so it does not install latest version.\nOr if you use requirements.txt, you can as well set importlib-metadata below version 5.0 e.g importlib-metadata==4.13.0\nFor more info... | [
81,
10,
9,
6,
0
] | [] | [] | [
"digital_ocean",
"django",
"python"
] | stackoverflow_0073929564_digital_ocean_django_python.txt |
Q:
How to send dictionary values to a function
I have a Python dictionary assigned to a variable.
mpm_holidays = {
"New Year's Day (Observed)": (None, True),
"Martin Luther King Jr. Day": ("art/MLKDay.png", True),
"2022-02-14": ("art/ValentinesDay.png", False),
"Good Friday": ("art/GoodFriday.png", Tr... | How to send dictionary values to a function | I have a Python dictionary assigned to a variable.
mpm_holidays = {
"New Year's Day (Observed)": (None, True),
"Martin Luther King Jr. Day": ("art/MLKDay.png", True),
"2022-02-14": ("art/ValentinesDay.png", False),
"Good Friday": ("art/GoodFriday.png", True),
"2022-04-16": ("art/GoodFriday.png", Tru... | [
"Loop over mpm_holidays.values() to get all the values.\nfor art, closed in mpm_holidays.values():\n overlays(art, closed)\n\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0074269935_python.txt |
Q:
How do you check a random number against multiple lists in Python?
I'm making a little text-based game in python for school. I also play a lot of runescape, so I wanted to incorporate some chance instead of just forcing interactions with monsters. I have four different rarites (common 1/5, uncommon 1/15, etc.) I w... | How do you check a random number against multiple lists in Python? | I'm making a little text-based game in python for school. I also play a lot of runescape, so I wanted to incorporate some chance instead of just forcing interactions with monsters. I have four different rarites (common 1/5, uncommon 1/15, etc.) I want to roll at each part of the dungeon to determine the level/difficult... | [
"Combining some of the earlier remarks:\n\nEnsure that your 'rarities' are correctly weighted. If you want to assign ranges for the randomint, the most common result must have the largest weight.\nThere is no need to create entire lists of integers to evaluate the random value. It is sufficient to store the beginni... | [
0
] | [] | [] | [
"dictionary",
"list",
"loops",
"python",
"random"
] | stackoverflow_0074268495_dictionary_list_loops_python_random.txt |
Q:
Working with javascript and API exasperates me: Always Response 400
I am trying to work with an API (that provides data about movies in the media centers of german public broadcasting) but I can't get a single useful response.
I got an example code in javascript but since I dont know anything about that language I... | Working with javascript and API exasperates me: Always Response 400 | I am trying to work with an API (that provides data about movies in the media centers of german public broadcasting) but I can't get a single useful response.
I got an example code in javascript but since I dont know anything about that language I try to understand as much as I can and write an equivalent python progra... | [
"Don't use XMLHttpRequest. This adds to the confusion.\nHere is the fetch option:\nconst query = {\n queries: [\n {\n fields: ['title', 'topic'],\n query: 'sturm der liebe',\n },\n {\n fields: ['channel'],\n query: 'ard',\n },\n ],\n sortBy: 'timestamp',\n sortOrder: 'desc',\n f... | [
1
] | [] | [] | [
"api",
"javascript",
"python",
"request"
] | stackoverflow_0074269806_api_javascript_python_request.txt |
Q:
Internal Server Error when deploying simple Flask app onto GCloud
When I run this app locally, it works fine. In the cloud, I get the error below. I think it's my yaml file. As a side note, if there is anything in the logs I should not be sharing, I'd appreciate knowing. Thank you!
Internal Server Error
The serv... | Internal Server Error when deploying simple Flask app onto GCloud | When I run this app locally, it works fine. In the cloud, I get the error below. I think it's my yaml file. As a side note, if there is anything in the logs I should not be sharing, I'd appreciate knowing. Thank you!
Internal Server Error
The server encountered an internal error and was unable to complete your reques... | [
"Your code is producing a list and trying to return a list as you're doing in flask will lead to the error -\nTypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a list.\nTo fix the error, modify your code to us... | [
2
] | [] | [] | [
"flask",
"google_app_engine",
"python"
] | stackoverflow_0074269826_flask_google_app_engine_python.txt |
Q:
dockerpy sdk unable to connect to remote server
I'm currently trying to use the dockerpy sdk to connect to my remote ubuntu server so i can manage my docker containers via python.
I am getting a few issues when attempting to do this.
docker.APIClient(base_url="ssh://user@ip")
When doing the following I am getting... | dockerpy sdk unable to connect to remote server | I'm currently trying to use the dockerpy sdk to connect to my remote ubuntu server so i can manage my docker containers via python.
I am getting a few issues when attempting to do this.
docker.APIClient(base_url="ssh://user@ip")
When doing the following I am getting the error:
paramiko.ssh_exception.PasswordRequiredEx... | [
"It's possible to make a connection as Mr. Piere answered here. Even with that question about docker.client.DockerClient which uses docker.api.client.APIClient under the hood.\nYou are trying to establish a connection using Password Authentication that's why you asked to prompt a password.\nI guess you need to conf... | [
0
] | [] | [] | [
"docker",
"dockerpy",
"python"
] | stackoverflow_0074241484_docker_dockerpy_python.txt |
Q:
NoReverseMatch at /'blog' is not a registered namespace
I am trying to link two pages. Page files are home.html and pageOne.html. I am getting "NoReverseMatch at /'blog' is not a registered namespace". I am using django. When I first created the app, I named it artclBlog, I then created a templates folder and an... | NoReverseMatch at /'blog' is not a registered namespace | I am trying to link two pages. Page files are home.html and pageOne.html. I am getting "NoReverseMatch at /'blog' is not a registered namespace". I am using django. When I first created the app, I named it artclBlog, I then created a templates folder and another folder within that one, this one I named blog. I think... | [
"You did not define an app_name in your urls.py, hence that means that blog: in blog:PageOne makes no sense. You thus either define an app_name, or remove the namespace.\nOption 1: Add an app_name in urls.py\nYou can specify the namespace by writin an app_name in the urls.py:\nfrom django.contrib import admin\nfrom... | [
4,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0063492544_django_python.txt |
Q:
Why is my output going in an infinity loop?
I tried taking each string elements out of the list which contains 10 elements and pass it to the isPalindrome method to check whether it is palindrome or not. But the output gives me "It is palindrome." to an infinite times that it crashes the kernel.
`
class Palindrome... | Why is my output going in an infinity loop? | I tried taking each string elements out of the list which contains 10 elements and pass it to the isPalindrome method to check whether it is palindrome or not. But the output gives me "It is palindrome." to an infinite times that it crashes the kernel.
`
class Palindrome():
def isPalindrome(self, x):
stack ... | [
"in your __init__() method, there is a while True wrapping everything - there is nothing \"breaking\" this loop, so it carries on forever and \"It is palindrome.\" keeps printing\n",
"I tried out your program and added a couple of tweaks to it to make it produce the type of output I believe you were looking for. ... | [
1,
0
] | [] | [] | [
"list",
"palindrome",
"python",
"stack"
] | stackoverflow_0074270014_list_palindrome_python_stack.txt |
Q:
making an etchasketch program having trouble keeping the turtle going on just a press of a button
This program is an etchasketch program that uses turtle and I'm trying to figure out how to keep the turtle going without holding down the keys for the direction of the turtle.
from turtle import *
import sys
import k... | making an etchasketch program having trouble keeping the turtle going on just a press of a button | This program is an etchasketch program that uses turtle and I'm trying to figure out how to keep the turtle going without holding down the keys for the direction of the turtle.
from turtle import *
import sys
import keyboard
PIXEL_MOVE = 20
def main():
running = True
pen_down = False
keep_moving = True
... | [
"One way to do this is to store the last pressed key or last moved direction in a variable.\nlastPressed = None\nwhile running:\n # Code before reading event\n if event.event_type == keyboard.KEY_DOWN:\n lastPressed = event.name\n if lastPressed:\n # Check if \"w\", \"a\", \"s\", \"d\", etc. ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074269934_python.txt |
Q:
Regular Expression to Pull Information from String in Python
What I am trying to do is take my current string and remove all data from it that doesn't contain the actual software version. Here is the string I am currently working with:
print (CurrentVersion)
Delivers the output:
2018, \\\\some\\directory\\is\\he... | Regular Expression to Pull Information from String in Python | What I am trying to do is take my current string and remove all data from it that doesn't contain the actual software version. Here is the string I am currently working with:
print (CurrentVersion)
Delivers the output:
2018, \\\\some\\directory\\is\\here, \\\\some\\directory\\is\\here, 2019, \\\\here\\is\\another\\d... | [
"You might use a capture group:\n(?:^|,\\s*)(\\d{4}\\w*)(?=,|$)\n\nThe pattern matches:\n\n(?:^|,\\s*) Match either the start of the string, or match a comma followed by optional whitespace chars\n(\\d{4}\\w*) Capture at least 4 digits followed by optional word characters\n(?=,|$) Assert either a comma or the end o... | [
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074269941_python_regex.txt |
Q:
WeakKeyDictionary with tuple of objects as key
I want to use a WeakKeyDictionary where the keys are tuples of other objects, e.g. of type Tuple[A,B], in such a way:
# a,b,c defined somewhere
d = WeakKeyDictionary()
d[(a, b)] = c
This does not work because: TypeError: cannot create weak reference to 'tuple' object... | WeakKeyDictionary with tuple of objects as key | I want to use a WeakKeyDictionary where the keys are tuples of other objects, e.g. of type Tuple[A,B], in such a way:
# a,b,c defined somewhere
d = WeakKeyDictionary()
d[(a, b)] = c
This does not work because: TypeError: cannot create weak reference to 'tuple' object. But even if it could create a weak ref to a tuple,... | [
"You need to \"implement your own\" in this case - and the problem is that you will need an auxiliar dictionary with stand-alone keys - so that when the time comes to del one the paired keys, you are able to find them back.\nThe implementation of WeakrefDicts themselves are pretty simple and straightforward, using ... | [
0
] | [] | [] | [
"python",
"weak_references",
"weakhashmap"
] | stackoverflow_0073717872_python_weak_references_weakhashmap.txt |
Q:
How would I be able to take a card from hand1 and give it to hand2?
I want to know if there is a way in def main where I can take the first random card from hand1 and be able to transfer it to hand2.
At first I tried something like this, but it doesnt seem to work.
i = hand[0]
i.give(0, hands[1])
The car... | How would I be able to take a card from hand1 and give it to hand2? | I want to know if there is a way in def main where I can take the first random card from hand1 and be able to transfer it to hand2.
At first I tried something like this, but it doesnt seem to work.
i = hand[0]
i.give(0, hands[1])
The card shuffle randomly to each hand can have a different set of cards each ti... | [
"the first argument of give() should be a card in the hand, not an index\nsomething like this should work:\nhand1.give(hand1.cards[0], hand2)\n\n"
] | [
0
] | [] | [] | [
"blackjack",
"indexing",
"list",
"python"
] | stackoverflow_0074268309_blackjack_indexing_list_python.txt |
Q:
How to access args of generic class
If I have a class A:
T = TypeVar("T")
class A(Generic[T]):
a: T
How do I access the Generic[T] with the type-object A
typing.get_origin(A[...]).__bases__ just returns a <class 'typing.Generic'> instead of typing.Generic[~T]
A:
You are looking for __orig_bases__. That is ... | How to access args of generic class | If I have a class A:
T = TypeVar("T")
class A(Generic[T]):
a: T
How do I access the Generic[T] with the type-object A
typing.get_origin(A[...]).__bases__ just returns a <class 'typing.Generic'> instead of typing.Generic[~T]
| [
"You are looking for __orig_bases__. That is set by the type metaclass when a new class is created. It is mentioned here in PEP 560, but is otherwise hardly documented.\nThis attribute contains (as the name suggests) the original bases as they were passed to the metaclass constructor in the form of a tuple. This di... | [
3
] | [] | [] | [
"python",
"python_typing"
] | stackoverflow_0074269920_python_python_typing.txt |
Q:
fitting a tanh curve and estimating parameters
I have two sets of data (say x and y). I want to fit a tanh curve (hyperbolic tangent) for y=x-a-btanh[(x-a)/b)] and return a and b parameters. I tried the follwing code, but get an error, TypeError: 'numpy.ufunc' object is not subscriptable. Also, I want to know if ... | fitting a tanh curve and estimating parameters | I have two sets of data (say x and y). I want to fit a tanh curve (hyperbolic tangent) for y=x-a-btanh[(x-a)/b)] and return a and b parameters. I tried the follwing code, but get an error, TypeError: 'numpy.ufunc' object is not subscriptable. Also, I want to know if the following function is a right way to fit a tanh ... | [
"The problem is here: np.tanh[(x-a)/b]\nThat might be the mathematical notation, but it's not valid python syntax.\nFunction are called with parentheses (). So it should be: np.tanh((x-a)/b)\n"
] | [
1
] | [] | [] | [
"curve_fitting",
"numpy",
"python",
"scipy"
] | stackoverflow_0074269928_curve_fitting_numpy_python_scipy.txt |
Q:
Why am I not getting the right mathematical output?
hrs = input("Enter Hours:")
rate = input("Enter rate per hour:")
h = float(hrs)
r = float(rate)
if h > 40:
overtime_pay = float((h % 40)) * float((1.5 * r))
gross_pay = float((h * r)) + float(overtime_pay)
print(gross_pay)
hrs = 45
rate = 10.50
I need to cal... | Why am I not getting the right mathematical output? | hrs = input("Enter Hours:")
rate = input("Enter rate per hour:")
h = float(hrs)
r = float(rate)
if h > 40:
overtime_pay = float((h % 40)) * float((1.5 * r))
gross_pay = float((h * r)) + float(overtime_pay)
print(gross_pay)
hrs = 45
rate = 10.50
I need to calculate the gross pay, including overtime
Gross_pay shou... | [
"First, by my calculation, the gross pay should be $498.75, not $497.85. Second, calculating h % 40 will cause problems if h is greater than 40, so it should be h - 40 instead. Your biggest problem, however, is that you include hours beyond the 40th in your calculation of base pay, even though those are already acc... | [
0
] | [] | [] | [
"math",
"python"
] | stackoverflow_0074270104_math_python.txt |
Q:
Python / Pandas Join records when they match in at least one column
I have the following dataframe:
id phone email
10352897
10352897 10225967
10352897 user@gmail.com
10352897 10225967 user@gmail.com
10225967
10225967 user@gmail.com
... | Python / Pandas Join records when they match in at least one column | I have the following dataframe:
id phone email
10352897
10352897 10225967
10352897 user@gmail.com
10352897 10225967 user@gmail.com
10225967
10225967 user@gmail.com
user@gmail.com
23578910
23578910 382567... | [
"This is quite a specific requirement and I'm not aware of any in-built pandas function that does what you're looking for, so I tried to define exactly what you are looking to do and recreate it from scratch.\nThe best I could come up with is that reading from the top of the dataframe, we will look at the values in... | [
0,
0,
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074269119_numpy_pandas_python.txt |
Q:
Python won't find a file that actually is there
I am trying to make a game where you can give it a song and it checks for the note with the highest volume in intervals eg, 5 seconds or so. This way it can place a button on the screen at that time for the player to click. I'm currently trying to wrap my head around... | Python won't find a file that actually is there | I am trying to make a game where you can give it a song and it checks for the note with the highest volume in intervals eg, 5 seconds or so. This way it can place a button on the screen at that time for the player to click. I'm currently trying to wrap my head around the way some of this audio analysing stuff works and... | [
"Hello Mate. I don't really use windows but it appears you need to install FFmpeg in your system. I was able to find a link that might help with setting up the Windows System Variables\nLink - How to setup FFmpeg on Windows\n"
] | [
0
] | [] | [] | [
"audio",
"file",
"python"
] | stackoverflow_0074260190_audio_file_python.txt |
Q:
How to reduce size of the database?
I have a folder with more than 150 txt files.
To combine the data
Resulting file has a size of 320 MB. I create a database and insert combined data:
with open("resall.TXT", "r") as f:
result = f.readlines()
result = [x.split(",") for x in result]
import sqlite3 as sq3
con ... | How to reduce size of the database? | I have a folder with more than 150 txt files.
To combine the data
Resulting file has a size of 320 MB. I create a database and insert combined data:
with open("resall.TXT", "r") as f:
result = f.readlines()
result = [x.split(",") for x in result]
import sqlite3 as sq3
con = sq3.connect("popular.db")
con.execute(... | [
"The problem is not SQLite, it is your import script. SQLite can easily handle that much data, 320 MB is not that large.\nThe first problem is you're slurping all 320 MB into memory. Instead, iterate over the lines.\nwith open(\"resall.TXT\", \"r\") as f:\n for line in f:\n rows = line.split(\",\")\n ... | [
1
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0074268857_python_sqlite.txt |
Q:
how to make list to dataframe?
["BANYULE : 'Abbotsford', 'Airport West', 'Albert Park', 'Alphington'",
"BRIMBANK : 'Altona', 'Altona North', 'Armadale', 'Ascot Vale'"]
I have one string list, and I want to change it to pandas dataframe:
BANYULE BRIMBANK
Abbotsford Altona
Airport West Altona North
Albert Park ... | how to make list to dataframe? | ["BANYULE : 'Abbotsford', 'Airport West', 'Albert Park', 'Alphington'",
"BRIMBANK : 'Altona', 'Altona North', 'Armadale', 'Ascot Vale'"]
I have one string list, and I want to change it to pandas dataframe:
BANYULE BRIMBANK
Abbotsford Altona
Airport West Altona North
Albert Park Armadale
Alphington Ascot Vale
t... | [
"Short answer:\nchange your list to dictionary\nlocal_list = {\"BANYULE\" : ['Abbotsford', 'Airport West', 'Albert Park', 'Alphington'], \n \"BRIMBANK\" : ['Altona', 'Altona North', 'Armadale', 'Ascot Vale']}\n\n#only use .T if you want transpose your index and columns.\ntest = pd.DataFrame(local_list)... | [
0
] | [] | [] | [
"dataframe",
"list",
"pandas",
"python"
] | stackoverflow_0074270037_dataframe_list_pandas_python.txt |
Q:
opening Python script mode on a mac
I have a MacBook air and have tried opening Python in terminal but when I open it, it opens Python interactive mode. Does anyone know how to open Python script mode please.
I’ve tried typing in things such as Python or Python 3 like safari suggests but that didn’t work.
A:
Wh... | opening Python script mode on a mac | I have a MacBook air and have tried opening Python in terminal but when I open it, it opens Python interactive mode. Does anyone know how to open Python script mode please.
I’ve tried typing in things such as Python or Python 3 like safari suggests but that didn’t work.
| [
"When you open the terminal, you need to type python or python3 and then press enter. After that, you are in the \"python mode\" and can use python commands.\nIf this also doesn't help you, you need to specify in more detail what youÄve done so far.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074270287_python.txt |
Q:
Keras LSTM Autoencoder time-series reconstruction
I am trying to reconstruct time series data with LSTM Autoencoder (Keras).
Now I want train autoencoder on small amount of samples (5 samples, every sample is 500 time-steps long and have 1 dimension). I want to make sure that model can reconstruct that 5 samples a... | Keras LSTM Autoencoder time-series reconstruction | I am trying to reconstruct time series data with LSTM Autoencoder (Keras).
Now I want train autoencoder on small amount of samples (5 samples, every sample is 500 time-steps long and have 1 dimension). I want to make sure that model can reconstruct that 5 samples and after that I will use all data (6000 samples).
windo... | [
"Update:\nThe answer below is based on the old version and based on the current LSTM doc, the input should be shaped as [batch, timesteps, feature]!\nSee this: https://github.com/keras-team/keras/blob/b80dd12da9c0bc3f569eca3455e77762cf2ee8ef/keras/layers/rnn/lstm.py#L481\n\nOld Answer:\nIt seems to me, a time serie... | [
6,
2,
0
] | [] | [] | [
"autoencoder",
"keras",
"lstm",
"python",
"time_series"
] | stackoverflow_0053509911_autoencoder_keras_lstm_python_time_series.txt |
Q:
How should I extend a color palette?
I am writing a script that is to combine multiple histograms into a stack plot. The script is to be able to handle a fairly arbitrary number of histograms. I want to be able to color the histograms in the stack plot according to a defined color palette and also to be able to ex... | How should I extend a color palette? | I am writing a script that is to combine multiple histograms into a stack plot. The script is to be able to handle a fairly arbitrary number of histograms. I want to be able to color the histograms in the stack plot according to a defined color palette and also to be able to extend that color palette when it is insuffi... | [
"You can use colorir for that.\nfrom colorir import *\npal = Palette.load(\"spectral\") # Load a categorical palette, a full list can be found in the docs\ngrad = Grad(pal) # Object to automatically \"mix\" the colors\n\n# Now to generate a dynamic list of colors based on the number of inputs:\nfor i in range(15)... | [
0
] | [] | [] | [
"colors",
"list",
"mean",
"palette",
"python"
] | stackoverflow_0032320999_colors_list_mean_palette_python.txt |
Q:
Training spaCy - NameError
I need to train a spaCy model to improve the accuracy to identify products. I'm struggling with training my spacy model. I have the following code:
TRAIN_DATA = [('..., {'entities': [(36,55,'PRODUCT')]})]
nlp = spacy.load("en_core_web_lg")
ner = nlp.get_pipe("ner")
optimizer = nlp.creat... | Training spaCy - NameError | I need to train a spaCy model to improve the accuracy to identify products. I'm struggling with training my spacy model. I have the following code:
TRAIN_DATA = [('..., {'entities': [(36,55,'PRODUCT')]})]
nlp = spacy.load("en_core_web_lg")
ner = nlp.get_pipe("ner")
optimizer = nlp.create_optimizer()
other_pipes = [pip... | [
"It's hot here...\nthanks for the hint I missed importing:\nfrom spacy.training import Example\nwhen moving the code from Jupyter to Visual Studio Code for the deployment\n"
] | [
-1
] | [
"# 4] Format of the training examples\n# training data\n\nTRAIN_DATA = [\n (\"Walmart is a leading e-commerce company\", {\"entities\": [(0, 7, \"ORG\")]}),\n (\"I reached Chennai yesterday.\", {\"entities\": [(19, 28, \"GPE\")]}),\n (\"I recently ordered a book from Amazon\",... | [
-2
] | [
"nlp",
"python",
"spacy"
] | stackoverflow_0068048737_nlp_python_spacy.txt |
Q:
Write a program to calculate the value of an expression step by step in Python:
Enter the string “(2 + 3 * 4) / 2 – (3^2 - 3)”. Export:
= (2 + 12) / 2 – (3^2 – 3)
= 14/2 – (3^2 – 3)
= 7 – (3^2 – 3)
= 7 – (9 – 3)
... | Write a program to calculate the value of an expression step by step in Python: | Enter the string “(2 + 3 * 4) / 2 – (3^2 - 3)”. Export:
= (2 + 12) / 2 – (3^2 – 3)
= 14/2 – (3^2 – 3)
= 7 – (3^2 – 3)
= 7 – (9 – 3)
= 7 – 6
= 1
How should I deal with such results?
| [
"Here's some code that does something slightly like what you asked for:\nimport ast\nimport copy\n\nexpr = \"(2 + 3 * 4) / 2 - (3**2 - 3)\"\ntree = ast.parse(expr,mode=\"eval\")\n\nclass EvalLeaves(ast.NodeTransformer):\n def visit_BinOp(self, node):\n match node:\n case ast.BinOp(left=ast.Cons... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074269944_python.txt |
Q:
How to filter in HTML using a field from model?
I want to implement a page with check boxes from university's subjects and the user can select which ones are already completed, I code a for loop that displays in the page all subjects from that course, but I want to separate the subjects by semester in a div, but i... | How to filter in HTML using a field from model? | I want to implement a page with check boxes from university's subjects and the user can select which ones are already completed, I code a for loop that displays in the page all subjects from that course, but I want to separate the subjects by semester in a div, but in the same page, can I do this with a custom template... | [
"The regroup template tag can help.\nExample template code:\n{% regroup subjects by semester as semester_list %}\n\n{% for semester, grouped_subjects in semester_list %}\n<div>\n {# your code for semester here #}\n <div>\n {% for subject in grouped_subjects %}\n {# your code for subject here #}\n ... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074270323_django_python.txt |
Q:
How do you append a specific row from one data frame to another Data frame?
I have one data frame. I am sorting out particular values from it and want to input that row of data. In this case the time, which is the index, and the action of which is happening. I have the row number that I want to input however, when... | How do you append a specific row from one data frame to another Data frame? | I have one data frame. I am sorting out particular values from it and want to input that row of data. In this case the time, which is the index, and the action of which is happening. I have the row number that I want to input however, when I try doing this,
a = a.append(data.values[i])
or
a = a.append(data.iloc[i])
I... | [
"Try this:\na = pd.concat([a, data.iloc[i].to_frame().T], axis=0)\n\n\nEdit\nMade some changes to the solution based on your replies. Is this what you're looking for?\n\nimport numpy as np\nimport pandas as pd\n\n# NOTE: If you get an ImportError message, execute\n# ``pip install dateutil`` and then try impor... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074270221_dataframe_pandas_python.txt |
Q:
cv2.imshow() function isn't displaying anything when I call it
I'm following one of the openCV python tutorials on displaying a live video feed from your camera. When I run the program, the green light for the webcam comes on (as I'm on a Mac) and there aren't any errors. Theres also a python rocketship thing that... | cv2.imshow() function isn't displaying anything when I call it | I'm following one of the openCV python tutorials on displaying a live video feed from your camera. When I run the program, the green light for the webcam comes on (as I'm on a Mac) and there aren't any errors. Theres also a python rocketship thing that comes up in my dock, but it doesn't show any windows or anything. T... | [
"Try to use cv.named Window command to open a new window :\ncv2.namedWindow('frame', cv2.WINDOW_AUTOSIZE)\ncv2.imshow('frame',gray)\ncv2.WaitKey(1)\ncv2.destroyAllWindows()\n\nI hope this works well with you\n",
"I found a solution in here. Try adding below line on top.\nimport cv2.\ncv2.startWindowThread()\n\nAn... | [
0,
0,
0
] | [] | [] | [
"cv2",
"opencv",
"python"
] | stackoverflow_0064959618_cv2_opencv_python.txt |
Q:
Python: Normalizing eigenfunctions over the range of the for loop
I am trying to plot the probability density of a wavefunction, however with my current code:
import numpy as np
from numpy import linalg as LA
for x in range(0,steps+1):
...
w,v=LA.eig(H)
probdensity = v@np.conj(v.T)
I am getting no... | Python: Normalizing eigenfunctions over the range of the for loop | I am trying to plot the probability density of a wavefunction, however with my current code:
import numpy as np
from numpy import linalg as LA
for x in range(0,steps+1):
...
w,v=LA.eig(H)
probdensity = v@np.conj(v.T)
I am getting normalized wavefunctions for each step such that the probability density... | [
">>> X = [[ 1., -1., 2.],\n... [ 2., 0., 0.],\n... [ 0., 1., -1.]]\n>>> X_normalized = preprocessing.normalize(X, norm='l2')\n\n>>> X_normalized\narray([[ 0.40..., -0.40..., 0.81...],\n [ 1. ..., 0. ..., 0. ...],\n [ 0. ..., 0.70..., -0.70...]])\n\n\nhttps://scikit-learn.org/stable... | [
0
] | [] | [] | [
"eigenvector",
"linear_algebra",
"math",
"physics",
"python"
] | stackoverflow_0074248233_eigenvector_linear_algebra_math_physics_python.txt |
Q:
swap name and surename with that is spaced with ,
I am fetching names from tags in wikipedia like this:
k = BeautifulSoup(str(Position),"html.parser")
name = k.find('a')['title']
names in this case will result in this
'Bassey, Charles'
Is there a way I can convert the names that are spaced like this to ... | swap name and surename with that is spaced with , | I am fetching names from tags in wikipedia like this:
k = BeautifulSoup(str(Position),"html.parser")
name = k.find('a')['title']
names in this case will result in this
'Bassey, Charles'
Is there a way I can convert the names that are spaced like this to this:
'Charles Bassey'
| [
"last_first = 'Bassey, Charles'\nlast_name,first_name = last_first.split(',')\nfullname = f'{first_name},{last_name}'\nprint(fullname)\n\noutput\nCharles,Bassey\n\n"
] | [
3
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074270405_python_string.txt |
Q:
How to grab specific cell values in Excel sheet using Pandas
I am working on the code below. How can I grab a specific cell value like highlighted boxes:
Code:
import pandas as pd
import numpy as np
file_xlsx = "Book1.xlsx"
yellow_cell = pd.read_excel(file_xlsx , sheet_name='Temp', usecols= 'Season')
red_cell = p... | How to grab specific cell values in Excel sheet using Pandas | I am working on the code below. How can I grab a specific cell value like highlighted boxes:
Code:
import pandas as pd
import numpy as np
file_xlsx = "Book1.xlsx"
yellow_cell = pd.read_excel(file_xlsx , sheet_name='Temp', usecols= 'Season')
red_cell = pd.read_excel(file_xlsx , sheet_name='Temp', usecols= 'Ave')
So at... | [
"df = pd.read_excel(\"/path/to/file/Book1.xlsx\", sheet_name=\"Temp\")\n\nyellow_cell = df.query(\"Group.eq('B')\")[\"Season\"].squeeze()\nred_cell = df.query(\"Group.eq('D')\")[\"Ave\"].squeeze()\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074270368_pandas_python_python_3.x.txt |
Q:
How do I tokenize this input sentences by the following stopwords ("!", "?", ".", “,”) using split in python?
My background is javascript and php. So yesterday I went for an entry level position interview that uses python. There's a test for the interview. The test is an open-book test, so I tried looking on the n... | How do I tokenize this input sentences by the following stopwords ("!", "?", ".", “,”) using split in python? | My background is javascript and php. So yesterday I went for an entry level position interview that uses python. There's a test for the interview. The test is an open-book test, so I tried looking on the net and tried to understand every method use out there and the closest method that may solve the problem is by using... | [
"Use re.split:\nimport re\n\nre.split(r\"[!?., ]+\", text)\n\n",
"First step, using re.split to split the text.\ninput = \"Excuse me, where can I find a chicken rice shop?\"\nresult = re.split(r\"[!?.,]+\", input)\nprint(result)\n\n['Excuse me', ' where can I find a chicken rice shop', '']\n\nThe second text havi... | [
1,
0,
0
] | [] | [] | [
"python",
"tokenize"
] | stackoverflow_0074261238_python_tokenize.txt |
Q:
Issues with handling special characters when reading environment variables from python script
I have setup environment variables for to access MongoDB database. All works except for the MongoDB connection string which is pretty long.
Mongodb string can be provided in different format,
mongodb://myDBReader:D1fficul... | Issues with handling special characters when reading environment variables from python script | I have setup environment variables for to access MongoDB database. All works except for the MongoDB connection string which is pretty long.
Mongodb string can be provided in different format,
mongodb://myDBReader:D1fficultP%40ssw0rd@mongodb0.example.com:27017/?authSource=admin
Other examples are here - https://www.fos... | [
"One other way to handle this situation is to use single quotes when preparing the environment variables and it work bash and csh scripts.\nInstead of this\nexport MGDB_CON_STRING=\"mongodb://myMGDB:someuname....................server/dbname?authSource=$external&authMechanism=PLAIN.....\"\n\nDo this\nexport MGDB_CO... | [
2,
1
] | [] | [] | [
"config",
"environment_variables",
"python",
"string",
"unix"
] | stackoverflow_0074267081_config_environment_variables_python_string_unix.txt |
Q:
update the dropdown without using submit button
Here is a flask application
Use this link to run the application : (Replace XXX with your machine url) http://XXX.0.0.1:5050/?tickers_get=Company2&open_price_get=23
What i am trying is, when the user selects Company2 from the dropdown, the other dropdown should get u... | update the dropdown without using submit button | Here is a flask application
Use this link to run the application : (Replace XXX with your machine url) http://XXX.0.0.1:5050/?tickers_get=Company2&open_price_get=23
What i am trying is, when the user selects Company2 from the dropdown, the other dropdown should get updated to only 2 prices (22 and 40) without hitting s... | [
"In order to dynamically fill your second select box with data depending on the first, you need JavaScript.\nIn the following example, an event listener is registered for the first input field, which responds to events of type change. If the selection changes within this field, the required data is obtained asynchr... | [
0
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0074260429_flask_python.txt |
Q:
Python transpose/swap dataframe column and row in csv file
I would like transpose/swap all the columns into the row of my csv files.
I tried this code:
import pandas as pd
import glob
import numpy as np
path =r'/Users/orochimaru/Documents/ParisSportif/foo/merge.csv'
stockstats_data = pd.DataFrame.transpose(path)
... | Python transpose/swap dataframe column and row in csv file | I would like transpose/swap all the columns into the row of my csv files.
I tried this code:
import pandas as pd
import glob
import numpy as np
path =r'/Users/orochimaru/Documents/ParisSportif/foo/merge.csv'
stockstats_data = pd.DataFrame.transpose(path)
list_ = []
for file_ in path:
df = pd.read_csv(file_)
s... | [
"import glob\nimport pandas as pd\n\npath =r'/Users/orochimaru/Documents/ParisSportif/foo/*.csv'\nfiles = glob.glob(path)\n\nframe = []\nfor file in files:\n frame.append(pd.read_csv(file))\n\ndf = pd.concat(frame)\ndf.T.to_csv('merget.csv', index=False)\n\n"
] | [
0
] | [] | [] | [
"csv",
"dataframe",
"pivot",
"python",
"transpose"
] | stackoverflow_0074270503_csv_dataframe_pivot_python_transpose.txt |
Q:
How to extract text based on parts from a PDF file in JSON format?
From this file https://github.com/pymupdf/PyMuPDF-Utilities/blob/master/text-extraction/Dart.pdf
I would like to get this kind of result:
{
"file": {
"title": "Dart Programming Language Specification",
"1 Scope": {
... | How to extract text based on parts from a PDF file in JSON format? | From this file https://github.com/pymupdf/PyMuPDF-Utilities/blob/master/text-extraction/Dart.pdf
I would like to get this kind of result:
{
"file": {
"title": "Dart Programming Language Specification",
"1 Scope": {
"text": "This Ecma standard specifies the syntax and semantics of the Da... | [
"Once you have text you can convert it to json text e.g. https://www.npmjs.com/package/text-2-json (PDF binary needs convert to text first)\nIn order to maintain indentation the strings of text need a replacement for the voids at each side of a line (RTL or LTR) one way is to use textual HTML as output rather than ... | [
0
] | [] | [] | [
"ocr",
"pdf_parsing",
"pdfminer",
"python",
"tesseract"
] | stackoverflow_0074269773_ocr_pdf_parsing_pdfminer_python_tesseract.txt |
Q:
Is 16 X 16 the maximum coordinates for minimap array in python pygame? I need a bigger map but collision system not working
mini_map = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, 1, _, 1, 1, _, _, _,... | Is 16 X 16 the maximum coordinates for minimap array in python pygame? I need a bigger map but collision system not working | mini_map = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, 1, _, 1, 1, _, _, _, _, _, 1, 1, _, _, _, 1],
[1, _, _, _, _, 1, 1, _, _, _, 1, 1, 1, _, _, _, 1, 1, _, _, _, _, _, 1, 1, 1, _, _, 1, 1, _, 1],
... | [
"No you can have any size map, limited only by your system memory.\nLooking at your code. The collision algorithm only checks the destination is clear. If your ray moves more than 1-unit at a time, the collision routine ignores everything in between.\nOne way to implement this is to determine the set of steps betw... | [
0
] | [] | [] | [
"arrays",
"collision",
"pygame",
"python",
"python_3.x"
] | stackoverflow_0074269154_arrays_collision_pygame_python_python_3.x.txt |
Q:
Converts from timedelta into minutes
I'm calculating with the variables current time and end_program to get the remaining minutes.
current_time = datetime.timedelta(hours = get_24_hours, minutes = get_24_minutes)
end_program = datetime.timedelta(hours = int(program_hours), minutes = int(program_minutes))
current_p... | Converts from timedelta into minutes | I'm calculating with the variables current time and end_program to get the remaining minutes.
current_time = datetime.timedelta(hours = get_24_hours, minutes = get_24_minutes)
end_program = datetime.timedelta(hours = int(program_hours), minutes = int(program_minutes))
current_program = end_program - current_time
Outpu... | [
"You can convert the seconds into minutes:\nprint int(current_program.total_seconds() / 60)\n\n",
"Look:\n>>> import datetime\n>>> current_time = datetime.timedelta(hours=24, minutes=24)\n>>> end_program = datetime.timedelta(hours = 30, minutes=26)\n>>> current_program = end_program - current_time\n>>> minutes = ... | [
8,
1,
0,
0,
0
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0035368639_python_python_2.7.txt |
Q:
Visual studio Code : Import "pandas" could not be resolved from source
Hi there,
I have installed Python 3.10.8 from Microsoft store and installed Pandas (via pip), but still got this message.
Thanks
A:
This is usually due to not having the correct Python interpreter selected in VsCode.
Press Cntrl+Shift+P, sear... | Visual studio Code : Import "pandas" could not be resolved from source |
Hi there,
I have installed Python 3.10.8 from Microsoft store and installed Pandas (via pip), but still got this message.
Thanks
| [
"This is usually due to not having the correct Python interpreter selected in VsCode.\nPress Cntrl+Shift+P, search for Select Python Interpreter and try to change between the options.\nHope this helps!\n",
"you can have to install http://conda.pydata.org/miniconda.html\nand then you can just do\n\nconda install p... | [
0,
0,
0
] | [] | [] | [
"pandas",
"python",
"visual_studio_code"
] | stackoverflow_0074265123_pandas_python_visual_studio_code.txt |
Q:
Vscode Docker Compose not making it past setup on remote machine
I am remoting in to a raspberry pi to do all my programming.
The machine is running OpenMediaVault with Docker and Portainer Installed.
If anyone needs to know exactly what I do and install, I have it all documented.
I've been doing this for a while ... | Vscode Docker Compose not making it past setup on remote machine | I am remoting in to a raspberry pi to do all my programming.
The machine is running OpenMediaVault with Docker and Portainer Installed.
If anyone needs to know exactly what I do and install, I have it all documented.
I've been doing this for a while and it works great, I want to start using docker containers on this ma... | [
"This issue has been fixed in Dev Containers 0.262.1-pre-release.\nUpdating should solve the problem\n"
] | [
1
] | [] | [] | [
"docker",
"python",
"visual_studio_code",
"vscode_devcontainer"
] | stackoverflow_0074192572_docker_python_visual_studio_code_vscode_devcontainer.txt |
Q:
How to implement list of checkable buttons with pyqt
I want to implement list of radiobuttons, but radiobutton shouldn't have a circle and if radiobutton is checked, then the background color is different from the others.
Like in this photo.
(https://i.stack.imgur.com/LsOeE.png)
I think I can use radiobuttons or t... | How to implement list of checkable buttons with pyqt | I want to implement list of radiobuttons, but radiobutton shouldn't have a circle and if radiobutton is checked, then the background color is different from the others.
Like in this photo.
(https://i.stack.imgur.com/LsOeE.png)
I think I can use radiobuttons or tabs, but i don't know how to change the styles of this thi... | [
"i set css rule:\ncss = '''\nQRadioButton::indicator {\n image: none;\n}\nQRadioButton::checked\n{\n background-color : red; \n}\n'''\nradioButton.setStyleSheet(css)\n\n",
"If you don't need the circle of a radio button, then you probably don't need a radio button at all.\nInstead, use standard QPushButtons (... | [
0,
0
] | [] | [] | [
"pyqt",
"python",
"tabs"
] | stackoverflow_0074267730_pyqt_python_tabs.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.