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:
how to split characters into separate column stored in data frame using python
i have a dataset with many columns and i have below columns need to separate it as a new column, below are example of what a kind of dataset i have:
using python, my goal is to subset a character into separate column to have an abiliti... | how to split characters into separate column stored in data frame using python | i have a dataset with many columns and i have below columns need to separate it as a new column, below are example of what a kind of dataset i have:
using python, my goal is to subset a character into separate column to have an abilities to working on numbers as the first 6 numbers after characters representing the da... | [
"IIUC, you can use:\ndf[['y', 'z']] = df['x'].str.extract(r'(\\D+)(\\d{6})')\n\nIf you want to exclude the first letter in y, use:\ndf[['y', 'z']] = df['x'].str.extract(r'.(\\D+)(\\d{6})')\n\n"
] | [
1
] | [] | [] | [
"data_cleaning",
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074182592_data_cleaning_dataframe_numpy_pandas_python.txt |
Q:
Create variables based on conditions for different groups
I want to label entities by its value. Here is what I have done:
data=pd.DataFrame({'Group':['group1','group1','group1','group2','group2','group2'],
'Value':[30,40,10,40,60,70]})
conditions=[(data['Value']<50) & (data['Value']>=40),
... | Create variables based on conditions for different groups | I want to label entities by its value. Here is what I have done:
data=pd.DataFrame({'Group':['group1','group1','group1','group2','group2','group2'],
'Value':[30,40,10,40,60,70]})
conditions=[(data['Value']<50) & (data['Value']>=40),
(data['Value']<40) & (data['Value']>=30)]
results=['Larg... | [
"You can generalize with a function:\ndef conditions(x,y,z,group):\n return [(data.loc[data['Group']==group,'Value']<x) & (data.loc[data['Group']==group,'Value']>=y),\n (data.loc[data['Group']==group,'Value']<y) & (data.loc[data['Group']==group,'Value']>=z)]\n\nresults=['Large','Small']\n\ndata.loc[data['... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074182191_pandas_python.txt |
Q:
Is it possible to skip chosen parameters from cookiecutter.json?
I'm wondering, if it's possible to skip prompt for chosen parameters in cookiecutter.json based on value of other parameter? For example for cookiecutter.json:
{
"ask_for_more": ["y", "n"],
"some_parameter": "test"
}
I'd like to skip prompt for ... | Is it possible to skip chosen parameters from cookiecutter.json? | I'm wondering, if it's possible to skip prompt for chosen parameters in cookiecutter.json based on value of other parameter? For example for cookiecutter.json:
{
"ask_for_more": ["y", "n"],
"some_parameter": "test"
}
I'd like to skip prompt for some_parameter if the answer to ask_for_more was n.
Is it possible ?
| [
"At the time of this writing, it is not possible to do it directly via the cookiecutter.json\nI think even with pre-gen hook it might not be possible as the cookiecutter jinja templating executes regardless of the if/else python conditions.\nThere are however lots of PR's and discussions to add this feature. See t... | [
0
] | [] | [] | [
"cookiecutter",
"python"
] | stackoverflow_0040680658_cookiecutter_python.txt |
Q:
AttributeError: 'Polygon' object has no attribute 'to_wkt'
I am new to geopandas and to begin with I am trying to replicate the example in the link guide with some shapefiles of my own to work in pyspark.
https://ncar.github.io/PySpark4Climate/tutorials/pyspark-geo-analysis/geopandas-and-spark/
import os.path, jso... | AttributeError: 'Polygon' object has no attribute 'to_wkt' | I am new to geopandas and to begin with I am trying to replicate the example in the link guide with some shapefiles of my own to work in pyspark.
https://ncar.github.io/PySpark4Climate/tutorials/pyspark-geo-analysis/geopandas-and-spark/
import os.path, json, io
import matplotlib.pyplot as plt
import matplotlib
matplotl... | [
"Polygon and Point objects are shapely geometry objects, not geopandas, and have .wkt attributes, not .to_wkt() methods. See the shapely docs for more info.\nSo your last block of code should be:\ngeo_df['wkt'] = pd.Series(\n map(lambda geom: geom.wkt, geo_df['geometry']),\n index=geo_df.index, dtype=... | [
1
] | [] | [] | [
"dataframe",
"geopandas",
"gis",
"python"
] | stackoverflow_0074179881_dataframe_geopandas_gis_python.txt |
Q:
Add a new logging handler with the same formatter
When we add a new additional handler:
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s: %(name)s: %(levelname)s: %(message)s')
logging.getLogger().addHandler(logging.FileHandler("debug.log"))
logging.info('an info')
by default, it doesn't... | Add a new logging handler with the same formatter | When we add a new additional handler:
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s: %(name)s: %(levelname)s: %(message)s')
logging.getLogger().addHandler(logging.FileHandler("debug.log"))
logging.info('an info')
by default, it doesn't keep the same formatter.
So here we would need to have... | [
"If you use logging.config.dictConfig() to configure logging, you can do this relatively straightforwardly. The documentation is too long to reproduce here, but I've linked to the official documentation.\nA configuration in YAML format might be:\nversion: 1\ndisable_existing_loggers: false\nformatters:\n default:\... | [
0
] | [] | [] | [
"logging",
"python",
"python_logging"
] | stackoverflow_0074178739_logging_python_python_logging.txt |
Q:
disable or lock mouse and keyboard in Python?
Is there a way of disabling or locking mouse and keyboard using python? I want to freeze the mouse and disable the keyboard.
A:
I haven't tested (actually I've tested the mouse part, and it annoyingly works) but something like this using pyhook would do what you want... | disable or lock mouse and keyboard in Python? | Is there a way of disabling or locking mouse and keyboard using python? I want to freeze the mouse and disable the keyboard.
| [
"I haven't tested (actually I've tested the mouse part, and it annoyingly works) but something like this using pyhook would do what you want:\nimport pythoncom, pyHook \n\ndef uMad(event):\n return False\n\nhm = pyHook.HookManager()\nhm.MouseAll = uMad\nhm.KeyAll = uMad\nhm.HookMouse()\nhm.HookKeyboard()\npython... | [
28,
14,
12,
6,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007529991_python.txt |
Q:
Why are the results different depending on how to assign?
When I tried to reverse the Linked list, I noticed that the results varied depending on how I did the assignments.
Why does it happen as bellow?
class ListNode:
def __init__(self, val=0, next: Optional["ListNode"] = None):
self.val = val
... | Why are the results different depending on how to assign? | When I tried to reverse the Linked list, I noticed that the results varied depending on how I did the assignments.
Why does it happen as bellow?
class ListNode:
def __init__(self, val=0, next: Optional["ListNode"] = None):
self.val = val
self.next = next
# It works as expected with unpacking assig... | [
"What applies here is\nrev, rev.next, nodes = nodes, rev, nodes.next\n\nthe right-hand expression is evaluated before the left-hand assignement. So you assign nodes.next to nodes and rev to rev.next. That's why it is correct.\nIn the second loop. You killing the link here\nrev.next = rev\n\nafter this it can not st... | [
0,
0
] | [] | [] | [
"linked_list",
"list",
"python",
"reference",
"variable_assignment"
] | stackoverflow_0074182600_linked_list_list_python_reference_variable_assignment.txt |
Q:
Tabula.read_pdf - IndexError: list index out of range
may I know why I will get IndexError when running the below code
import tabula
df = tabula.read_pdf("123.pdf", pages='all')[0]
IndexError: list index out of range
A:
because the list that is returned to you is of course empty, which is like []
| Tabula.read_pdf - IndexError: list index out of range | may I know why I will get IndexError when running the below code
import tabula
df = tabula.read_pdf("123.pdf", pages='all')[0]
IndexError: list index out of range
| [
"because the list that is returned to you is of course empty, which is like []\n"
] | [
0
] | [] | [] | [
"python",
"tabula_py"
] | stackoverflow_0074182786_python_tabula_py.txt |
Q:
Two threads reading/writing on the same serial port at the same time
Imagine we have a thread reading a temperature sensor 10 times per second via USB serial port.
And, when a user presses a button, we can change the sensor mode, also via USB serial.
Problem: the change_sensor_mode() serial write operation can hap... | Two threads reading/writing on the same serial port at the same time | Imagine we have a thread reading a temperature sensor 10 times per second via USB serial port.
And, when a user presses a button, we can change the sensor mode, also via USB serial.
Problem: the change_sensor_mode() serial write operation can happen in the middle of the polling thread "write/read_until" serial operatio... | [
"You should use a threading.Lock that is shared by any thread that wants to write to this serial port.\nimport threading\n\nwrite_lock = threading.Lock() # all writers have to lock this\nread_lock = threading.Lock() # all readers have to lock this\n\ndef poll_temperature():\n while True:\n with write_lo... | [
1
] | [] | [] | [
"multithreading",
"python",
"serial_port"
] | stackoverflow_0074182624_multithreading_python_serial_port.txt |
Q:
fastAPI : How to print all the excecuted actual queries in terminal in every request and response
How can I print all the excecuted actual queries in terminal in every request and response , in fastapi.
it will be helpfull if you can give me a sample code.
Im using raw queries like :
await db.database.execute('''I... | fastAPI : How to print all the excecuted actual queries in terminal in every request and response | How can I print all the excecuted actual queries in terminal in every request and response , in fastapi.
it will be helpfull if you can give me a sample code.
Im using raw queries like :
await db.database.execute('''INSERT INTO users(firstname, lastname)
VALUES (:firstname, :lastname)''',
... | [
"If you are using SQLAlchemy, you can set echo True to display all queries by doing this:\nengine = create_engine(\n \"mysql://ajay:123_114@hostname/dbname\",\n echo=True,\n)\n\nor this:\nagent_db = SQLAlchemy(\n uri=os.environ.get('SQLALCHEMY_DATABASE_URI','mysql://ajay:123_114@hostname/dbname'),\n ech... | [
1
] | [] | [] | [
"fastapi",
"python",
"sql"
] | stackoverflow_0074182487_fastapi_python_sql.txt |
Q:
How to write a Python program to calculate the deciles, percentiles, and quantiles for a given data set
I am writing a Python program to perform a set of steps as outlined below:
# Author: Evan Gertis
# Date : 10/22
# program : quantile decile calculator
import csv
import logging
import numpy as np
import pandas... | How to write a Python program to calculate the deciles, percentiles, and quantiles for a given data set | I am writing a Python program to perform a set of steps as outlined below:
# Author: Evan Gertis
# Date : 10/22
# program : quantile decile calculator
import csv
import logging
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import colors
from matplotlib.ticke... | [
"I suppose, that your csv contains float values and what you want to achieve is to convert every element to integer.\nHere is a working example, without the csv.\nimport numpy as np\nimport pandas as pd\n\n# Step 1: read data\ntestScoresData = pd.DataFrame([2.2,3.3,83.2,4,2,5,1,2,3,2],columns=[\"score\"])\ntes... | [
0,
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074165783_numpy_pandas_python.txt |
Q:
PowerBI: Refresh automation with Python
I'm trying to automate the refresh function on PowerBI Desktop (For now I don't want to pay for the Pro Licence) with Python but there are so many packages and I'm getting a bit lost. I wanted to use the win32com package first but PowerBI isn't in the application list of the... | PowerBI: Refresh automation with Python | I'm trying to automate the refresh function on PowerBI Desktop (For now I don't want to pay for the Pro Licence) with Python but there are so many packages and I'm getting a bit lost. I wanted to use the win32com package first but PowerBI isn't in the application list of the package. I saw that we can use some Microsof... | [
"Just call the REST API: Refresh Dataset in Group. This article looks right: Refresh a Power BI Dataset from Python.\n"
] | [
0
] | [] | [] | [
"automation",
"powerbi",
"python"
] | stackoverflow_0074182661_automation_powerbi_python.txt |
Q:
Displaying from models to a template page in django
I want to display the data of models to my template file but it just can't work it doesn't even show an error message, even when I pass a QuerySet of message objects as context to the render function.
App Name is CD
Here my code
models.py
from django.db import mo... | Displaying from models to a template page in django | I want to display the data of models to my template file but it just can't work it doesn't even show an error message, even when I pass a QuerySet of message objects as context to the render function.
App Name is CD
Here my code
models.py
from django.db import models
# Create your models here.
class Task(models.Model... | [] | [] | [
"you should use text instead of texts in template\nuse this :\n {% for task in tasks %}\n <h1>{{task.text}}</h1>\n {% endfor %}\n\n"
] | [
-1
] | [
"django",
"python"
] | stackoverflow_0074182111_django_python.txt |
Q:
convert the result in the context manager
I have my own context manager class: my_context_manager, I want to convert the result to the giving output_type, can be for example str, list, int whatever, I tried to play with the __enter__ , __exit__ methods, in my_context_manager, but I didn't find how to get the vari... | convert the result in the context manager | I have my own context manager class: my_context_manager, I want to convert the result to the giving output_type, can be for example str, list, int whatever, I tried to play with the __enter__ , __exit__ methods, in my_context_manager, but I didn't find how to get the variable used inside the with scope,
with my_contex... | [
"You can't manipulate the code running in the with block with a context manager.\nBasically all that with does is call __enter__ and __exit__ on the object you with, so your code is (if we skip exception handling) equivalent to\n_anonymous_var = my_context_manager(output_type)\n_anonymous_var.__enter__()\nresult =... | [
3,
0
] | [] | [] | [
"contextmanager",
"python",
"python_3.x"
] | stackoverflow_0074181206_contextmanager_python_python_3.x.txt |
Q:
Sum two values on the previous row
I have two columns in my dataframe: "Cust_ID" and "Fill_days". I need to add a column for "Adjusted Days", like this:
The idea: for every first row for "Cust_ID", the "Adjusted Days" value should be 0. For the following rows,
if previous row's "Fill_days" + "Adjusted Days" < 0 t... | Sum two values on the previous row | I have two columns in my dataframe: "Cust_ID" and "Fill_days". I need to add a column for "Adjusted Days", like this:
The idea: for every first row for "Cust_ID", the "Adjusted Days" value should be 0. For the following rows,
if previous row's "Fill_days" + "Adjusted Days" < 0 then 0, else previous row's "Fill_days" +... | [
"First of all, you need a column for order. Spark does not know the order. All the rows can be at any position unless you have a column which can tell exact order. I have added the column \"order\".\nSecondly, referencing the same column is not possible per se. You need a workaround. The following will collect date... | [
2
] | [] | [] | [
"apache_spark",
"apache_spark_sql",
"pyspark",
"python",
"sum"
] | stackoverflow_0074146685_apache_spark_apache_spark_sql_pyspark_python_sum.txt |
Q:
Probabilities and rpg dice goes wrong for high values
I made this short code to calculate the chances of a success rolling dice, and it worked very well... but not in big numbers. Se the code, I'll explain better below.
def calc_dados(f_sucessos = 1, faces = 6, n_dados = 1):
p_max = ((f_sucessos/faces)**n_dados... | Probabilities and rpg dice goes wrong for high values | I made this short code to calculate the chances of a success rolling dice, and it worked very well... but not in big numbers. Se the code, I'll explain better below.
def calc_dados(f_sucessos = 1, faces = 6, n_dados = 1):
p_max = ((f_sucessos/faces)**n_dados) #chance de todos
fator = 1
p_meio = 0
for i in ra... | [
"To be honest, I don't get how exactly 'calc_dados' calculate the probability of a success rolling dice.\nSo instead, I implemented maybe a more naive approach:\n\nFirst, we calculate the total of possible outcomes: outcomes_total = faces ** n_dados\nSecond, we calculate the successful outcomes: outcomes_success\nA... | [
0,
0,
0
] | [] | [] | [
"dice",
"probability",
"python"
] | stackoverflow_0074148439_dice_probability_python.txt |
Q:
For-loop in tf.function returns Tensor("while/Placeholder:0", shape=(), dtype=int32)
I want to use a for loop over a tensor in a tf.function, like this:
@tf.function
def test(x):
for i in range(tf.shape(x)[0]):
print(i)
I define:
S = tf.random.uniform([2,2],0,1)
Then
test(S)
gives
Tensor("while/Plac... | For-loop in tf.function returns Tensor("while/Placeholder:0", shape=(), dtype=int32) | I want to use a for loop over a tensor in a tf.function, like this:
@tf.function
def test(x):
for i in range(tf.shape(x)[0]):
print(i)
I define:
S = tf.random.uniform([2,2],0,1)
Then
test(S)
gives
Tensor("while/Placeholder:0", shape=(), dtype=int32)
While
for i in range(tf.shape(S)[0]):
print(i)
re... | [
"Use tf.print:\nimport tensorflow as tf\n\n@tf.function\ndef test(x):\n for i in range(tf.shape(x)[0]):\n tf.print(i)\n\nS = tf.random.uniform([2,2],0,1)\ntest(S)\n# 0\n# 1\n\nKindly check the side effects of using python operations in tf.function here.\n"
] | [
2
] | [] | [] | [
"for_loop",
"python",
"tensorflow"
] | stackoverflow_0074182597_for_loop_python_tensorflow.txt |
Q:
how to exclude a character once
I'm trying to exclude a character once (and everything after):
here is some example
val=aabbcc,val2==aabb,val3=aa==bb, val4=a=bccc
the pattern is: (any character except =) = (any character)
,here is the result that I wanted :
val='aabbcc',val2='=aabb',val3='aa==bb', val4='a=bccc... | how to exclude a character once | I'm trying to exclude a character once (and everything after):
here is some example
val=aabbcc,val2==aabb,val3=aa==bb, val4=a=bccc
the pattern is: (any character except =) = (any character)
,here is the result that I wanted :
val='aabbcc',val2='=aabb',val3='aa==bb', val4='a=bccc'
I tried : ([^=]+)=([^=]+)
and ([^=... | [
"You can use\n([^,=]+)=(.*?)(?=,[^,=]+=|$)\n\nSee the regex demo.\nDetails:\n\n([^,=]+) - Group 1: one or more chars other than comma and =\n= - = char\n(.*?) - Group 2: any zero or more chars other than line break chars as few as possible\n(?=,[^,=]+=|$) - a location that is either immediately followed with a c... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074182868_python_regex.txt |
Q:
How to ignore deleted records using dbf-module in python?
I'm using dbf-module by Ethan Furman version 0.96.005 (latest one) in Python 2.7 using old-fashioned FoxPro2.x-tables. Since I want to ignore deleted records, I set tbl.use_deleted = False after assigning tbl = dbf.Table(dbf_path). I tried to set this befor... | How to ignore deleted records using dbf-module in python? | I'm using dbf-module by Ethan Furman version 0.96.005 (latest one) in Python 2.7 using old-fashioned FoxPro2.x-tables. Since I want to ignore deleted records, I set tbl.use_deleted = False after assigning tbl = dbf.Table(dbf_path). I tried to set this before and after opening the table doing with tbl.open('read-only') ... | [
"use_deleted and has_been_deleted no longer exist, and have been replaced with the function is_deleted.\nSo your choices at this point are (assuming a from dbf import is_deleted):\n# check each record\nfor rec in tbl:\n if is_deleted(rec):\n continue\n\nor\n# create active/inactive indices\n\ndef active(r... | [
4,
0
] | [] | [] | [
"dbf",
"foxpro",
"python"
] | stackoverflow_0038149255_dbf_foxpro_python.txt |
Q:
Giving error of maximum recursion at some values
I wrote a program to search a element recursively. Logic is simple
return Search(array,start+1,end-1,element)
explains how i am searching again and again. It is working fine for smaller values
Example
In the sorted array of 1000000 elements if i search 500 or less t... | Giving error of maximum recursion at some values | I wrote a program to search a element recursively. Logic is simple
return Search(array,start+1,end-1,element)
explains how i am searching again and again. It is working fine for smaller values
Example
In the sorted array of 1000000 elements if i search 500 or less than 500 it works fine but if i search larger values li... | [
"Your solution has linear complexity O(n). That is, it's not logically wrong, but you're using too much memory (to save the function state). because you're possibly calling your function n times. Instead, you should call it at most log(n) times, i.e. you can reach O(log(n)) complexity:\ndef search(arr, start, end, ... | [
2
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0074182859_python_recursion.txt |
Q:
Problems Populating Chart.js OHLC Financial Chart from JSON Array (Ajax call from Django model)
Has anyone had success dynamically creating a Chart.js OHLC financial chart from a JSON array? In this case, I'm using an Ajax call to import the data from a Django model:
<script src="https://cdnjs.cloudflare.com/ajax/... | Problems Populating Chart.js OHLC Financial Chart from JSON Array (Ajax call from Django model) | Has anyone had success dynamically creating a Chart.js OHLC financial chart from a JSON array? In this case, I'm using an Ajax call to import the data from a Django model:
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js" integrity="sha512-ElRFoEQdI5Ht6kZvyzXhYG9NqjtkmlkfYk0wr6wHxU9JEHakS... | [
"Marking this as answered. I pivoted to canvasjs because I prefer the chart options. But, as I said, you have to push each data point to the end of the array before populating the chart, as shown here (spline instead of OHLC, but same principle):\nwindow.onload = function () {\n var chart = new CanvasJS.Chart(\"... | [
1
] | [] | [] | [
"chart.js",
"javascript",
"jquery",
"python"
] | stackoverflow_0073680544_chart.js_javascript_jquery_python.txt |
Q:
Python 3: Flatten Dictionary including lists
Is there an elegant way to achieve this in python 3? It is supposed to flatten the dictionary, while treating list indices like keys and thus including them in the flattening.
in:
{
"a": 1,
"b": {
"c": 2
},
"d": [3,4],
"e": [
{
"f": 5
},
... | Python 3: Flatten Dictionary including lists | Is there an elegant way to achieve this in python 3? It is supposed to flatten the dictionary, while treating list indices like keys and thus including them in the flattening.
in:
{
"a": 1,
"b": {
"c": 2
},
"d": [3,4],
"e": [
{
"f": 5
},
{
"g": 6
}
]
}
out:
{
"a": 1,
"b.... | [
"d= {\n \"a\": 1,\n \"b\": {\n \"c\": 2\n },\n \"d\": [3,4],\n \"e\": [\n {\n \"f\": 5\n },\n {\n \"g\": 6\n }\n ]\n }\nresult={}\ndef f(d,s=''):\n if type(d)==dict:\n for k,v in d.items():\n f(v,s=s+k+'.')\n elif type(d)==list:\n for i,v in en... | [
1,
1
] | [] | [] | [
"dictionary",
"flatten",
"list",
"python",
"python_3.x"
] | stackoverflow_0074157806_dictionary_flatten_list_python_python_3.x.txt |
Q:
Django filtering doesn't work with float field
I'm trying to get some records from the MySQL database but it seems that filtering by float field doesn't work. When I filter just by user_id I receive all records but when I add the value clause just got DoesNotExist exception.
I have the following models and query:
... | Django filtering doesn't work with float field | I'm trying to get some records from the MySQL database but it seems that filtering by float field doesn't work. When I filter just by user_id I receive all records but when I add the value clause just got DoesNotExist exception.
I have the following models and query:
class Record(models.Model):
user_id = models.In... | [
"It has to do with how Python represents floating point values (Django's FloatField translates to Python's float and Django's DecimalField maps to Python's decimal; see https://docs.python.org/2/library/decimal.html).\nThe distinction is that floats are not exact due to the way they are represented on your computer... | [
0
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0074182937_django_mysql_python.txt |
Q:
Scraping results from multiple pages into one item using Scrapy
How can I scrape results from multiple pages into one item using Scrapy?
The pages that should be considered:
an original page o (e.g. given by start_requests())
all pages url in urls, where urls is a field created by scraping o according to parse().... | Scraping results from multiple pages into one item using Scrapy | How can I scrape results from multiple pages into one item using Scrapy?
The pages that should be considered:
an original page o (e.g. given by start_requests())
all pages url in urls, where urls is a field created by scraping o according to parse().
Note that urls for different o might not be disjoint.
Specific exam... | [
"To combine info from the main website with info picked from individual clinics' websites, you can do the following (EDIT: included custom_settings,as well as redirection to 'google.com' for the ones without a website, and now it will yield 56 results out of 63 - needs further debugging):\nimport scrapy\nfrom germa... | [
1
] | [] | [] | [
"python",
"scrapy",
"web_scraping"
] | stackoverflow_0074179777_python_scrapy_web_scraping.txt |
Q:
Ho do I get a list from compounded names with strange characters in python?
How can I generate a list with regex in python for countries with compounded names?
names = ['Nizhniy Novgorod', 'Cần Thơ', 'Ba Beja', 'Bandar Bampung', 'Benin City', 'Ciudad Nezahualcóyotl', 'Biên Hòa', 'São Gonçalo', 'São Luís', 'New Orl... | Ho do I get a list from compounded names with strange characters in python? | How can I generate a list with regex in python for countries with compounded names?
names = ['Nizhniy Novgorod', 'Cần Thơ', 'Ba Beja', 'Bandar Bampung', 'Benin City', 'Ciudad Nezahualcóyotl', 'Biên Hòa', 'São Gonçalo', 'São Luís', 'New Orleans', 'Thủ Đức']
I was trying to do this but it returns all names:
import re
l... | [
"Ok - so I have two answers for you.\nOne that uses REGEX, and the other that doesn't.\nHere is the REGEX version:\nimport re\n\nnames = ['Nizhniy Novgorod', 'Cần Thơ', 'Ba Beja', 'Bandar Bampung', 'Benin City', 'Ciudad Nezahualcóyotl', 'Biên Hòa', 'São Gonçalo', 'São Luís', 'New Orleans', 'Thủ Đức']\n\npattern = r... | [
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074177280_python_regex.txt |
Q:
Extract labels and the text in between using regex in Python
I'm trying to extract the labels, the uppercase words, and the text in between until the next label using regex. Here is a sample text:
Iron DEFINITION it is a chemical element with symbol Fe (from Latin: ferrum) and atomic number 26. CATEGORY It is a me... | Extract labels and the text in between using regex in Python | I'm trying to extract the labels, the uppercase words, and the text in between until the next label using regex. Here is a sample text:
Iron DEFINITION it is a chemical element with symbol Fe (from Latin: ferrum) and atomic number 26. CATEGORY It is a metal that belongs to the first transition series and group 8 of the... | [
"You can use\n\\b(DEFINITION|CATEGORY|USE AND PROPERTIES|MISC\\.|HISTORY)\\s*(\\S.*?)(?=DEFINITION|CATEGORY|USE AND PROPERTIES|MISC\\.|HISTORY|$)\n\nSee the regex demo.\nDetails:\n\n\\b(DEFINITION|CATEGORY|USE AND PROPERTIES|MISC\\.|HISTORY) - a word boundary and then Group 1 capturing either DEFINITION, CATEGORY, ... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074182856_python_regex.txt |
Q:
How can i get bluetooth devices array with python (for windows)?
How can i get bluetooth devices array with python (for windows)?
Almost all libraries are for linux. But i need to use windows. İf you know python bluetooth libraries and methods can you suggest me? Especially i need to get a devices array.
A:
You ... | How can i get bluetooth devices array with python (for windows)? | How can i get bluetooth devices array with python (for windows)?
Almost all libraries are for linux. But i need to use windows. İf you know python bluetooth libraries and methods can you suggest me? Especially i need to get a devices array.
| [
"You can use pybluez\nExample code for basic start:\nimport bluetooth\n\nnearby_devices = bluetooth.discover_devices()\n\n\nExample code from github:\n# bluetooth low energy scan\nfrom bluetooth.ble import DiscoveryService\n\nservice = DiscoveryService()\ndevices = service.discover(2)\n\nfor address, name in device... | [
0
] | [] | [] | [
"bluetooth",
"python",
"web",
"windows"
] | stackoverflow_0074182385_bluetooth_python_web_windows.txt |
Q:
Python script killed from another script but no signal callback is called
I am trying to kill a script from another script by calling os.kill(PID, signal.SIGTERM). This part works, the process with PID is killed. The thing is I set a signal callback in the killed script but I was not called.
This is how I set the ... | Python script killed from another script but no signal callback is called | I am trying to kill a script from another script by calling os.kill(PID, signal.SIGTERM). This part works, the process with PID is killed. The thing is I set a signal callback in the killed script but I was not called.
This is how I set the callback
signals = signal.valid_signals()
for sig in signals:
signal.signal... | [
"I suppose it's a Windows issue. Check the Windows note on the os.kill docs.\n\nWindows: The signal.CTRL_C_EVENT and signal.CTRL_BREAK_EVENT signals are special signals which can only be sent to console processes which share a common console window, e.g., some subprocesses. Any other value for sig will cause the pr... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074179997_python_python_3.x.txt |
Q:
Why is Twine 1.9.1 still uploading to legacy PyPi?
I want to upload packages to pypi.org as mentioned in the Migrating to PyPI.org documentation, but Twine uploads to https://upload.pypi.org/legacy/.
It's available on pypi.python.org/pypi/mypolr, but is not found on pypi.org.
I've tried to read
several other que... | Why is Twine 1.9.1 still uploading to legacy PyPi? | I want to upload packages to pypi.org as mentioned in the Migrating to PyPI.org documentation, but Twine uploads to https://upload.pypi.org/legacy/.
It's available on pypi.python.org/pypi/mypolr, but is not found on pypi.org.
I've tried to read
several other questions, tutorials, and guides.
My pip.ini-file (I'm on W... | [
"You appear to be doing everything correctly. Twine is not uploading via legacy PyPI (https://pypi.python.org). It is uploading to the new PyPI (https://pypi.org, a.k.a. \"Warehouse\") via the original (and so far only) PyPI API, and this API just happens to be named \"legacy\".\nAlso, your package is present on ... | [
9,
3,
1
] | [] | [] | [
"pypi",
"python",
"twine"
] | stackoverflow_0047584147_pypi_python_twine.txt |
Q:
Custom python solver for pyomo
I am responsible for a series of exercises for nonlinear optimization.
I thought it would be cool to start with some examples of optimization problems and solve them with pyomo + some black box solvers.
However, as the students learn more about optimization algorithms I wanted them t... | Custom python solver for pyomo | I am responsible for a series of exercises for nonlinear optimization.
I thought it would be cool to start with some examples of optimization problems and solve them with pyomo + some black box solvers.
However, as the students learn more about optimization algorithms I wanted them to also implement some simple methods... | [
"The short answer is, \"Yes: Pyomo is designed to be extensible and user-defined solvers are definitely supported.\"\nThe details are a bit more involved. While Pyomo defines several \"solver\" class hierarchies, they are by no means required. The core Pyomo relies on duck-typing and not inheritance when register... | [
0,
0
] | [] | [] | [
"optimization",
"pyomo",
"python"
] | stackoverflow_0074179391_optimization_pyomo_python.txt |
Q:
Get the top line from a Shapely polygon
From a Shapely polygon, how can the top be obtained as a line? A line that describes the projection from above.
Let's assume the following Polygon:
Polygon([
[3, 2],
[2, 3],
[4, 4],
[4, 3],
[8, 3],
[7, 4],
[9, 4],
[8, 1],
])
In this case the ... | Get the top line from a Shapely polygon | From a Shapely polygon, how can the top be obtained as a line? A line that describes the projection from above.
Let's assume the following Polygon:
Polygon([
[3, 2],
[2, 3],
[4, 4],
[4, 3],
[8, 3],
[7, 4],
[9, 4],
[8, 1],
])
In this case the "projection" from above, or what a top viewer... | [
"from shapely import Polygon\n\np = Polygon([\n [3, 2],\n [2, 3],\n [4, 4],\n [4, 3],\n [8, 3],\n [7, 4],\n [9, 4],\n [8, 1],\n])\n\ny_min = p.bounds[1]\ncontainer = Polygon()\nfor (c1, c2) in zip(p.exterior.coords[:-1], p.exterior.coords[1:]):\n container = Polygon([c1, c2, (c2[0], y_min... | [
1
] | [] | [] | [
"python",
"python_3.x",
"shapely"
] | stackoverflow_0065492735_python_python_3.x_shapely.txt |
Q:
Python Indexing for a 2d Array
Supposing you had an array (in the latest version of Python):
list = [
['1', '2', '3'], ['4', '5', '6'], ['7', '8', ' ']
]
How do you find the index of the value that has the empty (' ') space?
Like list.index(' ') would return [2][2] or smthn.
I think for a 1D list it w... | Python Indexing for a 2d Array | Supposing you had an array (in the latest version of Python):
list = [
['1', '2', '3'], ['4', '5', '6'], ['7', '8', ' ']
]
How do you find the index of the value that has the empty (' ') space?
Like list.index(' ') would return [2][2] or smthn.
I think for a 1D list it was string.index() but I was wonderin... | [
"Use a list comprehension with enumerate:\nlst = [\n ['1', '2', '3'], ['4', '5', '6'], ['7', '8', ' ']\n ]\n\nout = [(i,j) for i,l in enumerate(lst) for j,x in enumerate(l) if x == ' ']\n\noutput:\n[(2, 2)]\n\nIf you want only the first found value, else a default value (here 'not found'):\nout = next(((i... | [
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074183101_list_python.txt |
Q:
How to use a dictionary to modify an array in python
I am trying to use a dictionary (created by reading the content of a first file) to modify the content of an array(created by reading the content of a second file) in order to return as many modified arrays as their are keys in the dictionary with the modificati... | How to use a dictionary to modify an array in python | I am trying to use a dictionary (created by reading the content of a first file) to modify the content of an array(created by reading the content of a second file) in order to return as many modified arrays as their are keys in the dictionary with the modification corresponding the position and change in the original a... | [
"In your code s1 isn't a copy of s, it's just another name for s.\nI'd suggest doing this by just building a new list in a comprehension, e.g.:\n>>> change={'change 1': [(1, 'B'), (3, 'B'), (5, 'B'), (7, 'B')], 'change 2': [(2, 'B'), (4, 'B'), (6, 'B')]}\n>>> s=['A', 'A', 'A', 'A', 'A', 'A', 'A']\n\n>>> for t in ch... | [
1,
0
] | [] | [] | [
"arrays",
"dictionary",
"list",
"python"
] | stackoverflow_0074183090_arrays_dictionary_list_python.txt |
Q:
I am getting 100% accuracy in my decision tree model. Where I was wrong?
#split dataset in features and target variable
feature_cols = ['RIAGENDR_0', 'RIDAGEYR', 'RIDRETH3_2', 'RIDRETH3_3', 'RIDRETH3_4', 'RIDRETH3_6', 'RIDRETH3_7', 'INDFMPIR', 'DMDMARTZ_1.0', 'DMDMARTZ_2.0', 'DMDMARTZ_3.0', 'DMDMARTZ_4.0', 'DMDMAR... | I am getting 100% accuracy in my decision tree model. Where I was wrong? | #split dataset in features and target variable
feature_cols = ['RIAGENDR_0', 'RIDAGEYR', 'RIDRETH3_2', 'RIDRETH3_3', 'RIDRETH3_4', 'RIDRETH3_6', 'RIDRETH3_7', 'INDFMPIR', 'DMDMARTZ_1.0', 'DMDMARTZ_2.0', 'DMDMARTZ_3.0', 'DMDMARTZ_4.0', 'DMDMARTZ_6.0', 'DMDEDUC2', 'RFXT010', 'BMXWT', 'BMXBMI', 'URXUMA', 'LBDHDD', 'LBXFER... | [] | [] | [
"Why do you think you are doing something wrong? Perhaps your data are such that you can achieve a perfect classification... e.g., see this mushroom classification.\nHaving said that, it is also possible that there is some leakage in your data as specified by @gtomer. That means an exact point that is present in tr... | [
-1
] | [
"decision_tree",
"machine_learning",
"python",
"scikit_learn"
] | stackoverflow_0074177127_decision_tree_machine_learning_python_scikit_learn.txt |
Q:
Pyrevit ISelectionFilter don't work with linked elements
I have problem with pick objects(linked elements). My "allow Element" filter works for elements in revit model but if i use the same ISelectionFilter for linked elements i can't pick enything. My code:
##imports
doc = revit.doc
uidoc = revit.uidoc
... | Pyrevit ISelectionFilter don't work with linked elements | I have problem with pick objects(linked elements). My "allow Element" filter works for elements in revit model but if i use the same ISelectionFilter for linked elements i can't pick enything. My code:
##imports
doc = revit.doc
uidoc = revit.uidoc
###Thanks to Cyril Waechter https://pythoncvc.net/?p=116 custo... | [
"This worked for me\nimport clr\nfrom Autodesk.Revit.UI.Selection import *\nfrom pyrevit import revit\n\ndoc = revit.doc\nuidoc = revit.uidoc\n\n\nclass CustomISelectionFilter(ISelectionFilter):\n def __init__(self, category_name, document):\n self.category_name = category_name\n self.document = do... | [
1
] | [] | [] | [
"pyrevit",
"python",
"revit_api",
"revitpythonshell"
] | stackoverflow_0073900872_pyrevit_python_revit_api_revitpythonshell.txt |
Q:
__rand__ across np array dimensions
How to compare values in val against arr based on operators o?
import numpy as np
from operator import gt, lt
val = np.array([[3,7,1], [4,8,5], [5,10,3]])
arr = np.array([[1,2,3,4,5], [6,7,8,9,10], [9,7,5,3,1]])
o = (gt, gt, lt)
# [3,7,1]
# (3 gt [1,2,3,4,5]) & (7 gt [6,7,8,9,... | __rand__ across np array dimensions | How to compare values in val against arr based on operators o?
import numpy as np
from operator import gt, lt
val = np.array([[3,7,1], [4,8,5], [5,10,3]])
arr = np.array([[1,2,3,4,5], [6,7,8,9,10], [9,7,5,3,1]])
o = (gt, gt, lt)
# [3,7,1]
# (3 gt [1,2,3,4,5]) & (7 gt [6,7,8,9,10] & (1 lt [9,7,5,3,1])
# [True, True, F... | [
"You can try this:\nimport numpy as np\n\nval = np.array([[3,7,1], [4,8,5], [5,10,3]])\narr = np.array([[1,2,3,4,5], [6,7,8,9,10], [9,7,5,3,1]])\no = (np.greater, np.greater, np.less)\n\nout = np.logical_and.reduce([o[i](val[:, i, None], arr[i]) for i in range(len(o))])\nprint(out)\n\nIt gives:\n[[ True False False... | [
1
] | [] | [] | [
"numpy",
"pandas",
"python",
"vector",
"vectorization"
] | stackoverflow_0074181798_numpy_pandas_python_vector_vectorization.txt |
Q:
PIP3 ModuleNotFoundError: No module named 'pip._internal.cli.main' on Mac OS
I get stuck on a thing today and i don't find how to resolve it.
I already check most of common answer for this problem on stackoverflow and other platforms but can't manage to unblock the situation.
I'm on MacOs Big Sure with python3.7 a... | PIP3 ModuleNotFoundError: No module named 'pip._internal.cli.main' on Mac OS | I get stuck on a thing today and i don't find how to resolve it.
I already check most of common answer for this problem on stackoverflow and other platforms but can't manage to unblock the situation.
I'm on MacOs Big Sure with python3.7 and pip3
Let me explain, everything started today while wanting to install new pack... | [
"I ended by uninstalling anaconda.\nIn fact anaconda was causing many troubles on his own.\nAfter uninstalling anaconda, i used to reinstall pip with\ncurl https://bootstrap.pypa.io/get-pip.py -o get-pip.py\npython3 get-pip.py --force-reinstall\n\n\nAdding to my bash_profile and\n/Library/Frameworks/Python.framewor... | [
0
] | [] | [] | [
"pip",
"python",
"python_3.x"
] | stackoverflow_0074153821_pip_python_python_3.x.txt |
Q:
How to predict product reaction using rdkit?
how to predict product chemical reaction using rdkit, this is my code:
disodium_tetraborat = Chem.MolFromSmiles('B1(OB2OB(OB(O1)O2)[O-])[O-]')
kanamycin = Chem.MolFromSmiles('C1C(C(C(C(C1N)OC2C(C(C(C(O2)CN)O)O)O)O)OC3C(C(C(C(O3)CO)O)N)O)N')
rxn_smarts = '[NH2:1][C:2](=[... | How to predict product reaction using rdkit? | how to predict product chemical reaction using rdkit, this is my code:
disodium_tetraborat = Chem.MolFromSmiles('B1(OB2OB(OB(O1)O2)[O-])[O-]')
kanamycin = Chem.MolFromSmiles('C1C(C(C(C(C1N)OC2C(C(C(C(O2)CN)O)O)O)O)OC3C(C(C(C(O3)CO)O)N)O)N')
rxn_smarts = '[NH2:1][C:2](=[S:3])[NH0:4].[C:5](=[O:6])[C:7][Cl:8]>>[N:4][c:2]1... | [
"you get an error because the reaction doesn't go through, and the products tuple is empty. The reaction you defined in rxn is unrelated to your reagents, it's a cyclization of a thiourea with a alpha halo carbonyl to form an aminothiazole. But your reagents don't satisfy those criteria.\nHere's a codeblock with re... | [
0
] | [] | [] | [
"python",
"rdkit"
] | stackoverflow_0074149561_python_rdkit.txt |
Q:
How to fix "ValueError: Series.replace cannot use dict-like to_replace and non-None value "
I tried to use this following line of code to replace the retirees' incorrect days values with 9000, but I get the error in the title. This is the line:
df.replace(df.loc[(df['days_employed']>100000) & (df['income_type']... | How to fix "ValueError: Series.replace cannot use dict-like to_replace and non-None value " | I tried to use this following line of code to replace the retirees' incorrect days values with 9000, but I get the error in the title. This is the line:
df.replace(df.loc[(df['days_employed']>100000) & (df['income_type']=='retiree')], 9000)
| [
"refer to the LOC documentation, section 'setting values'\nthe second parameter to the loc is the column to update\n# replace the col-to-update, with the column you like to update\ndf.loc[(df['days_employed']>100000) & (df['income_type']=='retiree'),'col-to-update']= 9000\n\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074183308_pandas_python.txt |
Q:
Pandas aggregate two columns at max
I have a data frame with two columns
df = DataFrame.from_records([
{"time": 10, "amount": 200},
{"time": 70, "amount": 1000},
{"time": 10, "amount": 300},
{"time": 10, "amount": 100},
])
I want to, given a period of time 80ms, calculate the max amount that is possible, ... | Pandas aggregate two columns at max | I have a data frame with two columns
df = DataFrame.from_records([
{"time": 10, "amount": 200},
{"time": 70, "amount": 1000},
{"time": 10, "amount": 300},
{"time": 10, "amount": 100},
])
I want to, given a period of time 80ms, calculate the max amount that is possible, in this case, the output should be 1300 b... | [
"This is a knapsack problem, you can solve it with a dedicated library (e.g., knapsack):\nfrom knapsack import knapsack\ntotal, idx = knapsack(df['time'], df['amount']).solve(80)\n\ndf.out = df.iloc[idx]\n\noutput:\n time amount\n1 70 1000\n2 10 300\n\nOther examples:\n# with max = 75\n time amou... | [
5,
1
] | [] | [] | [
"aggregate",
"knapsack_problem",
"optimization",
"pandas",
"python"
] | stackoverflow_0074182632_aggregate_knapsack_problem_optimization_pandas_python.txt |
Q:
Cut out a smaller array shape from a bigger array
I have two sets of data in x and y arrays, one is from a theoretical calculation so it is far larger.
x1 = [1,2,3,4,5,6,7,8,9,10] y1 = [1,4,9,16,25,36,49,64,81,100]
the other is experimental so it has the same values of x (but with a smaller data set, different st... | Cut out a smaller array shape from a bigger array | I have two sets of data in x and y arrays, one is from a theoretical calculation so it is far larger.
x1 = [1,2,3,4,5,6,7,8,9,10] y1 = [1,4,9,16,25,36,49,64,81,100]
the other is experimental so it has the same values of x (but with a smaller data set, different start and different intervals) with slightly different y ... | [
"Python way:\ny1_new = [y1[x-1] for x in x2]\n\nOr learn numpy:\nimport numpy as np\ny1_new = np.array(y1)[np.array(x2)-1] \n\n"
] | [
0
] | [] | [] | [
"arrays",
"matplotlib",
"numpy",
"python"
] | stackoverflow_0074183267_arrays_matplotlib_numpy_python.txt |
Q:
Find and copy values between 2 dataframes
I'm having trouble copying some data between 2 dataframes. I have the main_df:
main_df = pd.DataFrame({"id": [123, 456, 789, 357, 159], "date": [None, "2022-10-10", "2022-09-15", None, "2022-09-15"], "stuff": [3, 6, 2, 9, 3]})
id date stuff
123 N... | Find and copy values between 2 dataframes | I'm having trouble copying some data between 2 dataframes. I have the main_df:
main_df = pd.DataFrame({"id": [123, 456, 789, 357, 159], "date": [None, "2022-10-10", "2022-09-15", None, "2022-09-15"], "stuff": [3, 6, 2, 9, 3]})
id date stuff
123 NaN 3
456 2022-10-10 6
789 ... | [
"you can use map to bring over the date value\ndf2['date']=df2['id'].map(df.set_index('id')['date'])\ndf2\n\nid stuff date\n0 321 3 NaN\n1 456 6 2022-10-10\n2 789 2 2022-09-15\n3 351 4 NaN\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074183409_dataframe_pandas_python.txt |
Q:
I am getting "ValueError: A document must have an even number of path elements"
I am trying to read data from excel and store the text data in firestore. When I try to add it one by one without for loop it is working but if I try to automate the process it is not working.
Working Code:
import firebase_admin
from f... | I am getting "ValueError: A document must have an even number of path elements" | I am trying to read data from excel and store the text data in firestore. When I try to add it one by one without for loop it is working but if I try to automate the process it is not working.
Working Code:
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
cred = credent... | [
"As mentioned in the documentation, document IDs cannot contain a slash but in the provided screenshot there are 3. The value of cert is PSDC/2022/TCS/01 so the final path becomes certs/PSDC/2022/TCS/01 that has 5 segments i.e. a sub-collection. You can either replace the / with some other character like _:\ndb.col... | [
0
] | [] | [] | [
"firebase_admin",
"google_cloud_firestore",
"python",
"python_3.x"
] | stackoverflow_0074182208_firebase_admin_google_cloud_firestore_python_python_3.x.txt |
Q:
AttributeError: module 'transformers.modeling_bert' has no attribute 'gelu'
import pandas as pd
from ast import literal_eval
from cdqa.utils.filters import filter_paragraphs
from cdqa.utils.download import download_model, download_bnpp_data
from cdqa.pipeline.cdqa_sklearn import QAPipeline
# Download data and mo... | AttributeError: module 'transformers.modeling_bert' has no attribute 'gelu' | import pandas as pd
from ast import literal_eval
from cdqa.utils.filters import filter_paragraphs
from cdqa.utils.download import download_model, download_bnpp_data
from cdqa.pipeline.cdqa_sklearn import QAPipeline
# Download data and models
download_bnpp_data(dir='./data/bnpp_newsroom_v1.1/')
download_model(model='b... | [
"from transformers.activations import gelu\n"
] | [
0
] | [
"I ended up using a different version. Issue was I had a requirement for this version so I changed other parts of my program too.\n"
] | [
-1
] | [
"huggingface_transformers",
"nlp_question_answering",
"python",
"pytorch",
"torch"
] | stackoverflow_0066133626_huggingface_transformers_nlp_question_answering_python_pytorch_torch.txt |
Q:
Google Colab: "wandb" ModuleNotFoundError after installation
The "wandb" package cannot be found even after I see it has been listed in pip list.
To be more clear, I upgrade my python version to 3.9.15 in Colab, and then force to reinstall pip since somehow the pip module will disappear if I try to upgrade the pyt... | Google Colab: "wandb" ModuleNotFoundError after installation | The "wandb" package cannot be found even after I see it has been listed in pip list.
To be more clear, I upgrade my python version to 3.9.15 in Colab, and then force to reinstall pip since somehow the pip module will disappear if I try to upgrade the python in colab. Below is my installation detail.
# update python ver... | [
"Maybe try\npython3 -m pip install wandb ?\nor\npip3 install wandb\n",
"Restarting the runtime after doing the pip install did it for me.\n"
] | [
0,
0
] | [] | [] | [
"google_colaboratory",
"pip",
"python",
"wandb"
] | stackoverflow_0074073322_google_colaboratory_pip_python_wandb.txt |
Q:
Ranking with multiple ocurrence of ties in Pandas
I need to rank my df by some columns. Have a look at the print below
The lines need to be ranked from 1 to 20 by the column df['pontos_na_rodada']
If we issue some ties - which will occur - they have to be resolved by the highest value in column df['saldo_gols']. ... | Ranking with multiple ocurrence of ties in Pandas | I need to rank my df by some columns. Have a look at the print below
The lines need to be ranked from 1 to 20 by the column df['pontos_na_rodada']
If we issue some ties - which will occur - they have to be resolved by the highest value in column df['saldo_gols']. Then if the tie persist resolve it again by the column ... | [
"I just figured out an answer to show here:\ndf['rank'] = np.nan\ndf['Red Cards'] = df['Red Cards']*-1\ndf['Yellow Cards'] = df['Yellow Cards']*-1\ndf['rank'] = df.sort_values(by = ['league_season','league_round','pontos_na_rodada',\\\n 'saldo_gols','gols_feitos','Red Cards','Yellow... | [
0
] | [] | [] | [
"pandas",
"python",
"rank",
"ranking",
"ranking_functions"
] | stackoverflow_0074181639_pandas_python_rank_ranking_ranking_functions.txt |
Q:
SAP GUI script sometimes randomly crashes (object not found by ID)
So, I have two SAP GUI scripts, both of them are running a simple report in SE16, exporting it to Excel and that's all. My Python script heavily relies on this data, yet, half of the time when I go back to the computer the VBS script crashed.
Nothi... | SAP GUI script sometimes randomly crashes (object not found by ID) | So, I have two SAP GUI scripts, both of them are running a simple report in SE16, exporting it to Excel and that's all. My Python script heavily relies on this data, yet, half of the time when I go back to the computer the VBS script crashed.
Nothing changes between the attempts, sometimes it works, sometimes it doesn'... | [
"I've done something very similar to your code.\nI had a python script that first opened SAP and logged in, and then ran a VBS script to download two excel files, and then run another python script to process the data.\nOnly recently have I managed to merge it all into one python script. Although it's still VBS cod... | [
0
] | [] | [] | [
"python",
"sap_gui"
] | stackoverflow_0070260538_python_sap_gui.txt |
Q:
(Docker) "Failed building wheel for cmake" error when trying to install opencv-python
Here's a Dockerfile that demonstrates the problem:
FROM php:7.1
RUN apt-get update
RUN apt-get install -y python3-pip
RUN pip3 install opencv-python
It works fine if I do FROM php:8.0 but not FROM php:7.1. The error I get is as... | (Docker) "Failed building wheel for cmake" error when trying to install opencv-python | Here's a Dockerfile that demonstrates the problem:
FROM php:7.1
RUN apt-get update
RUN apt-get install -y python3-pip
RUN pip3 install opencv-python
It works fine if I do FROM php:8.0 but not FROM php:7.1. The error I get is as follows:
Running setup.py bdist_wheel for cmake: finished with status 'error'
Comp... | [
"I got this working. I needed to add RUN pip3 install --upgrade pip setuptools wheel to my Dockerfile after RUN apt-get install -y python3-pip.\n"
] | [
1
] | [] | [] | [
"docker",
"opencv",
"python"
] | stackoverflow_0073793245_docker_opencv_python.txt |
Q:
Cannot run python with nodejs "ModuleNotFoundError"
I want to run python with nodejs, the module is installed and the scripts work when I start them manually
Nodejs code
app.post("/exec/py", function (req, res) {
const spawn = require("child_process").spawn;
const python = spawn('python3', ["run.py", req.body.... | Cannot run python with nodejs "ModuleNotFoundError" | I want to run python with nodejs, the module is installed and the scripts work when I start them manually
Nodejs code
app.post("/exec/py", function (req, res) {
const spawn = require("child_process").spawn;
const python = spawn('python3', ["run.py", req.body.link]);
python.stderr.on("data", data => {
console... | [
"my mistake was that i ran this under another user who did not have the module\n"
] | [
0
] | [] | [] | [
"node.js",
"python",
"python_3.10"
] | stackoverflow_0074181190_node.js_python_python_3.10.txt |
Q:
Python Tkinter: How do you loop through a list and display items on a new line in a new root
I am building a translation app using tkinter, and I am trying to get the translated results to appear on a new line in a new root window. So if the user translates
one
two
three
The new tkinter root window should show
uno... | Python Tkinter: How do you loop through a list and display items on a new line in a new root | I am building a translation app using tkinter, and I am trying to get the translated results to appear on a new line in a new root window. So if the user translates
one
two
three
The new tkinter root window should show
uno
dos
tres
Here is the function that displays the translated words
def display_translated(text_to_t... | [
"You need to explicitly insert a newline between each element. The simplest way is with join:\ntextbox1.insert(\"1.0\", \"\\n\".join(display_words))\n\n"
] | [
1
] | [] | [] | [
"function",
"loops",
"python",
"tkinter"
] | stackoverflow_0074183173_function_loops_python_tkinter.txt |
Q:
Python, Pandas create a combination of value in the same column - Pandas
I'm tring to create a new dataframe that is a combination of all the different txt with the same id as shown below.
I tried to use .protuct but i'have not manage to take into account that it should only be considered for the same id.
id
txt... | Python, Pandas create a combination of value in the same column - Pandas | I'm tring to create a new dataframe that is a combination of all the different txt with the same id as shown below.
I tried to use .protuct but i'have not manage to take into account that it should only be considered for the same id.
id
txt
1
A1
1
A2
1
A3
2
A4
2
A5
id
txt
txt2
1
A1
A2
1
A1... | [
"One approach would be using combinations in the itertools library as below.\nfrom itertools import combinations\nimport pandas as pd\n\ninput_df = pd.DataFrame([(1, 'A1'), (1, 'A2'), (1, 'A3'), (2, 'A4'), (2, 'A5')], columns=['id', 'txt'])\n\noutput_data = []\nfor group_id, group_data in input_df.groupby('id'):\n ... | [
0,
0,
0
] | [] | [] | [
"combinations",
"pandas",
"product",
"python"
] | stackoverflow_0074171941_combinations_pandas_product_python.txt |
Q:
Resignation function invalidates the index value of other employee objects stored in a list
I have a class ResignationSystem. I also have an Employee and Company class.
class ResignationSystem:
def accept_resignation(self, employee):
self.employee_list.pop(employee.employee_num)
def resignat... | Resignation function invalidates the index value of other employee objects stored in a list | I have a class ResignationSystem. I also have an Employee and Company class.
class ResignationSystem:
def accept_resignation(self, employee):
self.employee_list.pop(employee.employee_num)
def resignation_from_employee(self, employee):
resign = self.accept_resignation(employee)
if ... | [
"You could use a dictionary instead of a list to store your employees, using employee_num as the keys of that dictionary.\nyour employee_list would look like:\n{\n 0 : {'name': 'Rob', 'number': 9606239371, 'working_days': 300, 'bonus_percent': 30, 'has_job': True, 'grades_percent_average': 90, 'employee_num': 0,... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074182253_python.txt |
Q:
Python: elif statements using list comprehension
Lets take the next reproducible example:
I have a numpy array with a sequence of datetime.datetime elements in an hourly frequency,
From that array, I want to create a list datesVect which I want to be True for datetimes between Februrary and April and else False.... | Python: elif statements using list comprehension | Lets take the next reproducible example:
I have a numpy array with a sequence of datetime.datetime elements in an hourly frequency,
From that array, I want to create a list datesVect which I want to be True for datetimes between Februrary and April and else False.
following the validated answer of this question and... | [
"I recommend to just use the and operator. Your current code is functioning similar to the or operator, hence why you get an array of all True values. To be between Feb and April the month must be greater than 1 and less than 5.\ndatesVect = [True if (j.month < 5 and j.month > 1) else False for j in dateHour]\n\n"
... | [
1
] | [] | [] | [
"datetime",
"list_comprehension",
"python"
] | stackoverflow_0074183441_datetime_list_comprehension_python.txt |
Q:
error using pipes in python using os.pipe() and using os.fork()
So I made a simple piece of code to add 1 to a value. I create two process and I am creating a pipe for storage the information beetween iterations. In the first cycle it gives the correct value but in the second iterration it gives two errors.
My cod... | error using pipes in python using os.pipe() and using os.fork() | So I made a simple piece of code to add 1 to a value. I create two process and I am creating a pipe for storage the information beetween iterations. In the first cycle it gives the correct value but in the second iterration it gives two errors.
My code:
def processMain():
number = 0
r, w = os.pipe()
for _ ... | [
"Re-assigning r = os.fdopen(r) is problematic here because the return value of os.fdopen is a TextIOWrapper, while the functions that use r require the value to be an integer. The first time you run the loop it works just fine because r is assigned to the first return from os.pipe(), however, then on it's converted... | [
0,
0
] | [] | [] | [
"oserror",
"pipe",
"process",
"python"
] | stackoverflow_0074181399_oserror_pipe_process_python.txt |
Q:
Filter groupby by combos with either category types
I have a dataset that looks something like this:
df = pd.DataFrame(
[[1,'A','X','1/2/22 12:00:00AM', 'Alpha'],
[1,'A','X','1/3/22 12:00:00AM', 'Alpha'],
[1,'A','X','1/1/22 12:00:00AM', 'Beta'],
[1,'A','X','1/2/22 1:00:00AM', 'Gamma'],
[1,'B','Y','1/1/22 1:00:... | Filter groupby by combos with either category types | I have a dataset that looks something like this:
df = pd.DataFrame(
[[1,'A','X','1/2/22 12:00:00AM', 'Alpha'],
[1,'A','X','1/3/22 12:00:00AM', 'Alpha'],
[1,'A','X','1/1/22 12:00:00AM', 'Beta'],
[1,'A','X','1/2/22 1:00:00AM', 'Gamma'],
[1,'B','Y','1/1/22 1:00:00AM', 'Alpha'],
[2,'A','Z','1/2/22 12:00:00AM', 'Alpha']... | [
"aaa = []\n\ndef my_func(x):\n ind = x['Type'] == 'Alpha'\n alf = x.loc[ind, 'Type'].count()\n if alf >= 2 and len(x[x['Type'] != 'Alpha']) != 0:\n difference = (x.loc[ind, 'Task Completed'].max() - x.loc[ind, 'Task Completed'].min()).days\n bbb = x[ind][['ID', 'Category', 'Site']].values[0]\... | [
1
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0074181661_dataframe_group_by_pandas_python.txt |
Q:
how to replace some columns' values with their log forms and create a new DataFrame in python?
I have a Data Frame with 4 columns. I want to calculate the log form of three columns values and then make a new Data Frame. my problem is that after getting the log form of values, their type become as series. My questi... | how to replace some columns' values with their log forms and create a new DataFrame in python? | I have a Data Frame with 4 columns. I want to calculate the log form of three columns values and then make a new Data Frame. my problem is that after getting the log form of values, their type become as series. My question is that how I can create a new dataframe with these new series.
Here is my dataset:
year ... | [
"Considering the following simple dataset:\ndf = pd.DataFrame({'year':[1,2,3,4,5], \n 'gnp':[100, 200, 300, 400, 500], \n 'labor':[1000, 2000, 3000, 4000, 5000],\n 'capital':[1e4, 2e4, 3e4, 4e4, 5e4]},\n )\ndf\n\n\nHere is one of the solutions:\ndf[... | [
1,
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074183421_dataframe_pandas_python.txt |
Q:
Invalid HTTP_HOST header: '0.0.0.0:8000'. You may need to add '0.0.0.0' to ALLOWED_HOSTS
Django does not seem to find my host 0.0.0.0
I have already added "0.0.0.0" to my ALLOWED_HOSTS. In fact, if I print(ALLOWED_HOSTS) I get
['localhost', '127.0.0.1', '0.0.0.0', '[::1]']. I am working in docker. Is there anythi... | Invalid HTTP_HOST header: '0.0.0.0:8000'. You may need to add '0.0.0.0' to ALLOWED_HOSTS | Django does not seem to find my host 0.0.0.0
I have already added "0.0.0.0" to my ALLOWED_HOSTS. In fact, if I print(ALLOWED_HOSTS) I get
['localhost', '127.0.0.1', '0.0.0.0', '[::1]']. I am working in docker. Is there anything I am overlooking?
.env.dev
DEBUG=1
SECRET_KEY=foo
DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1... | [
"I just added the ip in ALLOWED_HOSTS property in the file <your_app_path>/settings.py.\ne.g.\n...\nALLOWED_HOSTS = ['0.0.0.0']\n...\n\nAnd it worked fine.\n",
"Take a look at settings.py and fill the ALLOWED_HOSTS as follows.\nFor local host:\nALLOWED_HOSTS = [\"0.0.0.0\"]\n\nOR you can do\nALLOWED_HOSTS = [\"*\... | [
12,
5,
2,
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0061095316_django_python.txt |
Q:
Extract year from corrupted timestamp column
I'm working with a pandas dataframe similar to the sample data below.
I need to be able to create a new column, year, by looking at the data in a timestamp field.
However, the timestamp field is a bit corrupted. Sometimes the years are invalid (see Spa record), or there... | Extract year from corrupted timestamp column | I'm working with a pandas dataframe similar to the sample data below.
I need to be able to create a new column, year, by looking at the data in a timestamp field.
However, the timestamp field is a bit corrupted. Sometimes the years are invalid (see Spa record), or there were two entries entered into the field (see Pope... | [
"You need change df in your extract_year to row\ndef extract_year(row):\n if row['is_date_check'] ==True:\n year = row[\"Swipe timestamp\"][:4] # <--- here\n else:\n year=''\n return year\n\ndf['year'] = df.apply(extract_year, axis=1)\n\nOr with np.where\ndf['year'] = np.where(df['is_date_che... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074183401_dataframe_pandas_python.txt |
Q:
max()function Capitals
What does uppercase and lowercase have to do with max function. When I ask it to print max in "Hello World", it print "r". But when I ask it max for "Hello world", it prints "w". What does uppercase and lowercase have to do with this?
A:
This is simply the ordering of the letters on the ke... | max()function Capitals | What does uppercase and lowercase have to do with max function. When I ask it to print max in "Hello World", it print "r". But when I ask it max for "Hello world", it prints "w". What does uppercase and lowercase have to do with this?
| [
"This is simply the ordering of the letters on the keyboard.\nEach letter is assigned a value, so if the capitals (A,B,C ...) come after then lower case (a,b,c...) then the values will be higher (or visa versa).\nSo capital W has a different value to lower case w.\nHere us the ascii table with the ordering of lette... | [
0
] | [] | [] | [
"function",
"max",
"python"
] | stackoverflow_0074182320_function_max_python.txt |
Q:
'list' object has no attribute 'move_to'
So i am coding on a bot that kicks people out of the voice channel after a specific time but I am getting this error:'list' object has no attribute 'move_to'
@client.command(pass_context = True)
async def outro(ctx,):
#Loads opus
#if not discord.opus.is_loaded():
... | 'list' object has no attribute 'move_to' | So i am coding on a bot that kicks people out of the voice channel after a specific time but I am getting this error:'list' object has no attribute 'move_to'
@client.command(pass_context = True)
async def outro(ctx,):
#Loads opus
#if not discord.opus.is_loaded():
# discord.opus.load_opus('libopus.so')
... | [
"meminds is a list of members ids. You probably have to get specific user by id from this list, and then kick him from channel. What library do you use?\n",
"Following that url https://github.com/Rapptz/discord.py/issues/2128\nChannel_members return a 'discord.Member' type, so it should have the method you're loo... | [
0,
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074183458_discord_discord.py_python.txt |
Q:
Why cant I import/use installed libraries in Python
I recently downloaded Python 3.10 because I used 3.9. At first, everything worked fine. Sadly, I can't use installed libraries nor use newly downloaded ones, since I deleted Python 3.9. What can I do about this problem?
VSCode gives me this Error message:
Traceba... | Why cant I import/use installed libraries in Python | I recently downloaded Python 3.10 because I used 3.9. At first, everything worked fine. Sadly, I can't use installed libraries nor use newly downloaded ones, since I deleted Python 3.9. What can I do about this problem?
VSCode gives me this Error message:
Traceback (most recent call last):
File "e:\XXXX\XXXX.py", li... | [
"You can check installed packages using this command:\npip freeze\n\nor\npip list\n\nUninstall and install using command pip install <package-name>\n"
] | [
1
] | [] | [] | [
"libraries",
"python"
] | stackoverflow_0074183639_libraries_python.txt |
Q:
filtering pandas df when value is in a list
lets say I have the following pandas dataframe. I would like to filter the row, where for example the name is Julia. But how can I filter if the names are in a list?
| Index | Department | Names |
|-------|------------| --------------------|
| 0 | Histo... | filtering pandas df when value is in a list | lets say I have the following pandas dataframe. I would like to filter the row, where for example the name is Julia. But how can I filter if the names are in a list?
| Index | Department | Names |
|-------|------------| --------------------|
| 0 | History |[Carl, Julia, Jens] |
| 1 | Economics... | [
"You can try:\ndf.loc[\"Julia\" not in df.Names,:];\n\nHope it solves the problem.\n",
"you could try converting the list into a string with join and then use contains():\ndf = pd.DataFrame([\n ['History',['Carl', 'Julia', 'Jens']],\n ['Economics',['Maggie', 'Lisa', 'Jules']],\n ['Pysics',['Freddy', 'Mar... | [
0,
0,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074113318_pandas_python.txt |
Q:
Python set.add() is triggering outside a conditional statement
I'm tokenizing some document and I want to find out which tokens are shared between one or more tokenizations. To do this, for each tokenization, I am looping through the set of all tokens in all tokenizations, called all_tokens and checking if a given... | Python set.add() is triggering outside a conditional statement | I'm tokenizing some document and I want to find out which tokens are shared between one or more tokenizations. To do this, for each tokenization, I am looping through the set of all tokens in all tokenizations, called all_tokens and checking if a given token exists in the current tokenization. If it does exist in the c... | [
"set.add is only called inside the conditional. The problem is: there is only one set, and all entries in token_dict point to the exact same set instance.\nThe culprit is this line:\ntoken_dict = dict.fromkeys(all_tokens, set())\n\nFrom the python docs:\n\nAll of the values refer to just a single instance, so it ge... | [
0
] | [
"import numpy as np\nnp.random.seed(42)\n\nall_tokens = ['a', 'b', 'c', 'd', 'e', 'f', 'g']\n\ntokenizations = [[all_tokens[np.random.randint(0, len(all_tokens))] for i in range(4)] for i in range(10)]\ntoken_dict = dict.fromkeys(all_tokens, set())\nfor i, tokenization in enumerate(tokenizations):\n token_set = ... | [
-1
] | [
"python",
"set",
"tokenize"
] | stackoverflow_0074182863_python_set_tokenize.txt |
Q:
Merging dictionaries not including duplicate values in python
I would like to merge two dictionaries, but if they have the same key, I would only merge non-duplicate values.
The following code works, but I have a question if it's possible to rewrite this when trying to get a union by using | or (**dict1, **dict2)?... | Merging dictionaries not including duplicate values in python | I would like to merge two dictionaries, but if they have the same key, I would only merge non-duplicate values.
The following code works, but I have a question if it's possible to rewrite this when trying to get a union by using | or (**dict1, **dict2)? When I tried using |, my output would be from this dict_merge({ 'A... | [
"Giving your two dictionaries names, let's get the union of their keys.\n>>> d1 = { 'A': [1, 2, 3] }\n>>> d2 = { 'A': [2, 3, 4] }\n>>> d1.keys() | d2.keys()\n{'A'}\n\nAssuming the lists are really sets based on your code, we can now iterate over the union of the keys in a dictionary comprehension, and union those t... | [
0
] | [
"Is that the solution you're wanting?\nIn [61]: my_dict = {}\n ...: d1 = {'A': [1, 2, 3], 'C': 123}\n ...: d2 = {'B': [2, 3, 4], 'A': [1, 2, 3]}\n ...: for i in set(d1).symmetric_difference(set(d2)):\n ...: my_dict[i] = d1[i] if i in d1 else d2[i]\n ...: print(my_dict)\n\nOutput :\n{'B': [2, 3, 4... | [
-2
] | [
"mergeddictionaries",
"python"
] | stackoverflow_0074182370_mergeddictionaries_python.txt |
Q:
Why is loss function giving "nan" value?
I was trying to implement logistic regression using pytorch but the output of loss function is "nan"? How can I solve it?
Data loading and manupulation
dataLoad=load_breast_cancer()
X_train,X_test,Y_train,Y_test=train_test_split(dataLoad.data,dataLoad.target,test_size=0.33)... | Why is loss function giving "nan" value? | I was trying to implement logistic regression using pytorch but the output of loss function is "nan"? How can I solve it?
Data loading and manupulation
dataLoad=load_breast_cancer()
X_train,X_test,Y_train,Y_test=train_test_split(dataLoad.data,dataLoad.target,test_size=0.33)
scaler=StandardScaler()
X_train=scaler.fit_tr... | [
"you are using the sigmoid as your activation function. mean your output (predictions) could be 0 and log of that will be -Inf, in your loss function add epsilon for stability purposes.\nlog(x) -> replace with log(x + eps) // eps= 1e-7 (somehting small)\n\nif you use the builtin loss functions there are many checks... | [
0
] | [] | [] | [
"logistic_regression",
"loss_function",
"machine_learning",
"python",
"pytorch"
] | stackoverflow_0074182828_logistic_regression_loss_function_machine_learning_python_pytorch.txt |
Q:
Why does my code return 4390 instead of 5062 for Oxford dataset?
I wrote a code to read Oxford building dataset. Based on the official website, the dataset contains 5062 images and groundtruth to say which one belongs to [good,bad,ok,junk]. There is no "bad" in the groundtruth. There are about 100 query files. The... | Why does my code return 4390 instead of 5062 for Oxford dataset? | I wrote a code to read Oxford building dataset. Based on the official website, the dataset contains 5062 images and groundtruth to say which one belongs to [good,bad,ok,junk]. There is no "bad" in the groundtruth. There are about 100 query files. Therefore, there should be around 4900 images.
My code is as follows:
fil... | [
"After a while and be somehow an expert, I found what the reason is. I posted as an answer to help other people who came across this problem with old version of the dataset.\nThe reason is the corrupted images that PIL or OpenCV cannot read and simply ignore.\nYou should write an error handler helper or even use tr... | [
0
] | [] | [] | [
"dataset",
"python",
"python_3.x"
] | stackoverflow_0069978521_dataset_python_python_3.x.txt |
Q:
Multiple regression model using scikit learn in python
when I am taking the independent variable 'age' ....reg.fit() showing an error like " ['age'] not in index ".....can anyone please help me ?
import pandas as pd
import numpy as np
from sklearn import linear_model
df=pd.read_csv('homeprices_multivariate.csv')
... | Multiple regression model using scikit learn in python | when I am taking the independent variable 'age' ....reg.fit() showing an error like " ['age'] not in index ".....can anyone please help me ?
import pandas as pd
import numpy as np
from sklearn import linear_model
df=pd.read_csv('homeprices_multivariate.csv')
import math
median_bedrooms=math.floor(df.bedrooms.median())... | [
"Strip the column names and it should work:\ndf.columns=[c.strip() for c in df.columns]\n\n",
"The age column heading has an extra space in your data set. Your last line should be changed to:\nreg.fit(df[['area','bedrooms','age ']],df.price)\n\n"
] | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0061939947_pandas_python.txt |
Q:
No callback results returned
I have a minimal script that uses twisted backend to return the GET request from yahoo finance. However, nothing is returned to the console but the code runs successfully. Am I missing something here. How do I get a successful returned result?
import asyncio
from collections import nam... | No callback results returned | I have a minimal script that uses twisted backend to return the GET request from yahoo finance. However, nothing is returned to the console but the code runs successfully. Am I missing something here. How do I get a successful returned result?
import asyncio
from collections import namedtuple
from twisted.internet impo... | [
"You need to change\nif '__name__' == '__main__':\n\nTo\nif __name__ == '__main__':\n\nThis still reveals your program has an error\nRuntimeError: Task got bad yield: <Deferred at 0x7f75a50e3d30>\n\nBut it answers why you are not seeing any output.\n"
] | [
1
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0074183894_python_twisted.txt |
Q:
How to raise a canvas item above a canvas window item
There is a solution for raising canvas windows over other canvas windows: How do you change the stacking order of window items in a canvas?
But I am not able to raise a not-canvas-window item (for example a canvas rectangle) above a canvas window item.
How can ... | How to raise a canvas item above a canvas window item | There is a solution for raising canvas windows over other canvas windows: How do you change the stacking order of window items in a canvas?
But I am not able to raise a not-canvas-window item (for example a canvas rectangle) above a canvas window item.
How can I do this?
Here is an example code where I try to raise the... | [
"\nBut I am not able to raise a not-canvas-window item (for example a\ncanvas rectangle) above a canvas window item. How can I do this?\n\nYou can't. The documentation says:\n\nThe items in a canvas are ordered for purposes of display, with the\nfirst item in the display list being displayed first, followed by the\... | [
1
] | [] | [] | [
"canvas",
"python",
"raise",
"tkinter"
] | stackoverflow_0074183718_canvas_python_raise_tkinter.txt |
Q:
Mantain wagtail category across pages
I've a pagination system on my Wagtail website that works just fine with normal posts. However, I wanted to make pagination of post categories and I wasn't able to do it, it loads the "Posts" URL losing the category.
You can see an example here when clicking page 2
https://wiz... | Mantain wagtail category across pages | I've a pagination system on my Wagtail website that works just fine with normal posts. However, I wanted to make pagination of post categories and I wasn't able to do it, it loads the "Posts" URL losing the category.
You can see an example here when clicking page 2
https://wizardeo.es/publicaciones/?category=guias
This... | [
"Your template code is not passing your filter parameters and that is why you are losing your category. Have a look at this blog post and adapt it to your needs: https://www.caktusgroup.com/blog/2018/10/18/filtering-and-pagination-django/#combining-filtering-and-pagination\n"
] | [
0
] | [] | [] | [
"django",
"html",
"python",
"wagtail"
] | stackoverflow_0074183882_django_html_python_wagtail.txt |
Q:
Simple use of Python’s Subprocess.call to open multiple Mac apps
I’d like to open a few apps using a very simple python script:
from subprocess import call
call("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")
call("/Applications/MongoDB Compass.app/Contents/MacOS/MongoDB Compass")
The problem is t... | Simple use of Python’s Subprocess.call to open multiple Mac apps | I’d like to open a few apps using a very simple python script:
from subprocess import call
call("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")
call("/Applications/MongoDB Compass.app/Contents/MacOS/MongoDB Compass")
The problem is that opening them this way seems to open a terminal window along with t... | [
"Updated Answer\nThis also appears to work and doesn't involve the shell:\nimport subprocess as sp\nprint(\"start\")\nsp.run([\"open\", \"-a\", \"Google Chrome\"])\nprint(\"end\")\n\nOriginal Answer\nThis appears to do what you want, though I have no explanation as to why:\nimport subprocess as sp\n\nprint(\"start\... | [
1
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0074167786_macos_python.txt |
Q:
Python: Dataclass that inherits from base Dataclass, how do I upgrade a value from base to the new class?
How can I upgrade values from a base dataclass to one that inherits from it?
Example (Python 3.7.2)
from dataclasses import dataclass
@dataclass
class Person:
name: str
smell: str = "good"
@data... | Python: Dataclass that inherits from base Dataclass, how do I upgrade a value from base to the new class? | How can I upgrade values from a base dataclass to one that inherits from it?
Example (Python 3.7.2)
from dataclasses import dataclass
@dataclass
class Person:
name: str
smell: str = "good"
@dataclass
class Friend(Person):
# ... more fields
def say_hi(self):
print(f'Hi {self.name... | [
"What you are asking for is realized by the factory method pattern, and can be implemented in python classes straight forwardly using the @classmethod keyword.\nJust include a dataclass factory method in your base class definition, like this:\nimport dataclasses\n\n@dataclasses.dataclass\nclass Person:\n name: s... | [
16,
3,
1,
0
] | [] | [] | [
"python",
"python_3.7",
"python_dataclasses"
] | stackoverflow_0054824893_python_python_3.7_python_dataclasses.txt |
Q:
Setting a date + 8 days inside a value in a pandas column
I want to create a new column in pandas in which I get a comment that says: Opened today() need update in today + 8 days. This is what I've got, but have not been able to fix this error.
This is my code:
import pandas as pd
import datetime
from datetime imp... | Setting a date + 8 days inside a value in a pandas column | I want to create a new column in pandas in which I get a comment that says: Opened today() need update in today + 8 days. This is what I've got, but have not been able to fix this error.
This is my code:
import pandas as pd
import datetime
from datetime import timedelta
Today = datetime.date.today()
def add_days_to_... | [
"df['Replied/sent date']=(df.loc[(df['col1'] != ' ') & (df['col2'] != ' ')]['date']\n .apply(lambda x: \"Opened \" + str(x.strftime('%F') ) + \" , need update, \" + str((x+ pd.offsets.Day(8)).strftime('%F')))\n)\ndf\n\ncol1 col2 date Replied/sent date\n0 2021-01-04 Opened... | [
0,
0
] | [] | [] | [
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074181689_pandas_python_python_3.x.txt |
Q:
unable to run test using tox.ini file
I am using unittest as the library for the unit testing purposes. I was trying to run the below test via tox.ini file.
from services.snowflake_api import SnowflakeApi
from unittest import TestCase
from mock import patch
class SnowflakeDbTest(TestCase):
@patch('services.S... | unable to run test using tox.ini file | I am using unittest as the library for the unit testing purposes. I was trying to run the below test via tox.ini file.
from services.snowflake_api import SnowflakeApi
from unittest import TestCase
from mock import patch
class SnowflakeDbTest(TestCase):
@patch('services.SnowflakeAPI.snowflake.connector') # Decor... | [
"This is not a tox issue, but rather a pytest one.\nLet's have a look at the error message:\ncollecting ... collected 0 items\n\npytest has not collected a single test, returns a non-zero exit code, and so tox also fails.\nHaving a look at pytest's test discovery convention it is clear, that pytest only collects te... | [
0
] | [] | [] | [
"pytest",
"python",
"python_unittest",
"tox"
] | stackoverflow_0074183160_pytest_python_python_unittest_tox.txt |
Q:
Add new column to existing dataframe from substring of existing column
I have a df that looks similar to this:
|email|first_name|last_name|id|group_email|
|-|-|-|-|-|
|drew@mail.com|drew|barry|05|san-red-gate-rate@mail.com|
|nate@mail.com|nate|lewis|03|san-blue-gate-factor@mail.com|
|chris@mail.com|chris|ryan|04|s... | Add new column to existing dataframe from substring of existing column | I have a df that looks similar to this:
|email|first_name|last_name|id|group_email|
|-|-|-|-|-|
|drew@mail.com|drew|barry|05|san-red-gate-rate@mail.com|
|nate@mail.com|nate|lewis|03|san-blue-gate-factor@mail.com|
|chris@mail.com|chris|ryan|04|san-red-wheels-drive@mail.com|
I parse out the group_code, the sub string af... | [
"Let's try\ndf['group_code'] = (df['group_email'].str.extract('(-[^@]*){3}')[0]\n .str.lstrip('-'))\n\nprint(df)\n\n email first_name last_name id group_email group_code\n0 drew@mail.com drew barry 5 san-red-gate-rate@mail.com rate\n1 nate@... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074183385_dataframe_pandas_python.txt |
Q:
Python import Mariadb: 'ModuleNotFoundError'
I'm trying to use python to connect to a database that uses MariaDB, I'm taking the script on the MariaDB webpage but it gives me an error trying to import the MariaDB module. If I try to import this manually I get the same error message. This is the script:
# Module Im... | Python import Mariadb: 'ModuleNotFoundError' | I'm trying to use python to connect to a database that uses MariaDB, I'm taking the script on the MariaDB webpage but it gives me an error trying to import the MariaDB module. If I try to import this manually I get the same error message. This is the script:
# Module Imports
import mariadb
import sys
# Connect to Mari... | [
"You have probably two different python interpreters installed. Check if you have selected the right one in your code editor.\n"
] | [
0
] | [] | [] | [
"mariadb",
"python",
"python_3.x"
] | stackoverflow_0074183866_mariadb_python_python_3.x.txt |
Q:
University Question including for loops and lists
the question is asking me to do this In a small highland village, everyone has the surname McIntosh, McGregor, McDonald or McKenzie.
Everyone is called Angus, Hamish, Morag or Mhairi
No two people have the same name.
Create a program to compile a list of the inhabi... | University Question including for loops and lists | the question is asking me to do this In a small highland village, everyone has the surname McIntosh, McGregor, McDonald or McKenzie.
Everyone is called Angus, Hamish, Morag or Mhairi
No two people have the same name.
Create a program to compile a list of the inhabitants of the village.
It makes use of lists and loops b... | [
"You have the right idea with doing a nested loop, but you need to use a different variable name for the for var in iterable part, and you need to print the variables from both loops.\n>>> surnames = [\"Mcintosh\", \"McGregor\", \"McDonald\", \"Mckenzie\"]\n>>> forenames = [\"Angus\", \"Hamish\", \"Morag\", \"Mhair... | [
1,
1,
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0074184013_loops_python.txt |
Q:
Strange message when running `python` or `pip` command "dyld[19439]: rebase opcodes terminated early at offset 1 of 9040
I'm using OSX. When I'm running python --version or any other command which starts with the python or pip, I get this message
"dyld[19439]: rebase opcodes terminated early at offset 1 of 9040
I... | Strange message when running `python` or `pip` command "dyld[19439]: rebase opcodes terminated early at offset 1 of 9040 | I'm using OSX. When I'm running python --version or any other command which starts with the python or pip, I get this message
"dyld[19439]: rebase opcodes terminated early at offset 1 of 9040
I didn't find what that could be. I tried a few times to remove Python and install it again, but it didn't work.
Right now, I'v... | [
"I've removed all Python versions and all aliases.\nAfter I also removed the pyenv using brew command.\nAfter all these steps, I installed pyenv.\nUsing pyenv, I installed two python versions:\npyenv install 3.10.4\npyenv install 2.7.15\n\nFinally, I set the python versions in the following way:\npyenv global 3.10.... | [
0
] | [] | [] | [
"macos",
"neovim",
"pip",
"python"
] | stackoverflow_0074183011_macos_neovim_pip_python.txt |
Q:
pygame screen.fill command has undefined error
It looks like in pygame, screen command, like in screen.fill() is not in pygame. How do I set the background color?
Here is the code if needed:
pygame.display.set_mode([800, 600])
run = True
while run:
for event in pygame.event.get():
if event.type == py... | pygame screen.fill command has undefined error | It looks like in pygame, screen command, like in screen.fill() is not in pygame. How do I set the background color?
Here is the code if needed:
pygame.display.set_mode([800, 600])
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
screen.fill(... | [
"screen is not a built-in variable. It seems that in your case screen should be the pygame.Surface object associated with the display. This pygame.Surface is returned when the Pygame window is created with pygame.display.set_mode():\nscreen = pygame.display.set_mode([800, 600])\n\nThe other option is to get the dis... | [
2
] | [] | [] | [
"background",
"pygame",
"python"
] | stackoverflow_0074184047_background_pygame_python.txt |
Q:
Importing parquet file in chunks and insert in DuckDB
I am trying to load the parquet file with row size group = 10 into duckdb table in chunks. I am not finding any documents to support this.
This is my work so on: see code
import duckdb
import pandas as pd
import gc
import numpy as np
# connect to an in-memory ... | Importing parquet file in chunks and insert in DuckDB | I am trying to load the parquet file with row size group = 10 into duckdb table in chunks. I am not finding any documents to support this.
This is my work so on: see code
import duckdb
import pandas as pd
import gc
import numpy as np
# connect to an in-memory database
con = duckdb.connect(database='database.duckdb', r... | [
"df1 = pd.read_parquet(\"file1.parquet\")\n\nThis statement will read the entire parquet file into memory. Instead, I assume you want to read in chunks (i.e one row group after another or in batches) and then write the data frame into DuckDB.\nThis is not possible as of now using pandas. You can use something like ... | [
1,
0
] | [] | [] | [
"duckdb",
"pandas",
"parquet",
"pyarrow",
"python"
] | stackoverflow_0074152013_duckdb_pandas_parquet_pyarrow_python.txt |
Q:
Maximum height of people in a room given entry and exit times
People arrive and depart a room at various times. Given their entry and exit times and their heights, what's an efficient way (in Python / Pandas) to find the maximum height of people in the room at all times?
Input:
people = pd.DataFrame({
"height"... | Maximum height of people in a room given entry and exit times | People arrive and depart a room at various times. Given their entry and exit times and their heights, what's an efficient way (in Python / Pandas) to find the maximum height of people in the room at all times?
Input:
people = pd.DataFrame({
"height": [175, 180, 160],
"arrive": pd.to_datetime(["2017-04-05 14:20"... | [
"I'm not sure this is an efficient way, but it may achieve what you want.\nimport panda as pd\n\npeople = pd.DataFrame({\n \"height\": [175, 180, 160],\n \"arrive\": pd.to_datetime([\"2017-04-05 14:20\", \"2017-04-05 13:10\", \"2017-04-05 10:30\"]),\n \"depart\": pd.to_datetime([\"2017-04-05 17:54\", \"201... | [
1,
0
] | [] | [] | [
"algorithm",
"pandas",
"python",
"time_series"
] | stackoverflow_0074183415_algorithm_pandas_python_time_series.txt |
Q:
Pygame doesn't draw line
import pygame
import sys
pygame.init()
width, height = 1000, 800
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("Colonizer")
win.fill("white")
pygame.display.update()
def draw():
pygame.draw.line(win, ("black"), [width,height/2], [width*2,height/2], 5)
... | Pygame doesn't draw line | import pygame
import sys
pygame.init()
width, height = 1000, 800
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("Colonizer")
win.fill("white")
pygame.display.update()
def draw():
pygame.draw.line(win, ("black"), [width,height/2], [width*2,height/2], 5)
while True:
for event in p... | [
"You cannot \"see\" the line because it is outside the window. The line starts to the right of the window and continues even further out to the right. Change the coordinates. e.g.:\npygame.draw.line(win, (\"black\"), [width,height/2], [width*2,height/2], 5)\npygame.draw.line(win, (\"black\"), [0, height//2], [width... | [
1
] | [] | [] | [
"line",
"pygame",
"python"
] | stackoverflow_0074184252_line_pygame_python.txt |
Q:
FTX API error "Missing parameter accounts"
I hope someone could help me in this.
Following this official doc from FTX:
https://docs.ftx.com/#request-historical-balances-and-positions-snapshot
I'm continue to get this error:
{'success': False, 'error': 'Missing parameter accounts', 'errorCode': 'parameter_missing'}... | FTX API error "Missing parameter accounts" | I hope someone could help me in this.
Following this official doc from FTX:
https://docs.ftx.com/#request-historical-balances-and-positions-snapshot
I'm continue to get this error:
{'success': False, 'error': 'Missing parameter accounts', 'errorCode': 'parameter_missing'}
The code was ok and getting all the response fr... | [
"Try switching request = requests.Request(\"POST\", url, params=params) to request = requests.Request(\"POST\", url, data=params) or request = requests.Request(\"POST\", url, json=params), because I believe they want you to send them accounts and endTime as body of request, not as url parameters.\n"
] | [
-1
] | [] | [] | [
"python"
] | stackoverflow_0074183887_python.txt |
Q:
python how to code one line if else with a None value
I want to use one line to code the logic :
if the user email is None then user email equal to 'test@abc.com'.
I have tried:
user_email = 'test@abc.com' if user_email is None
Error:
if user_email is None
^
Sy... | python how to code one line if else with a None value | I want to use one line to code the logic :
if the user email is None then user email equal to 'test@abc.com'.
I have tried:
user_email = 'test@abc.com' if user_email is None
Error:
if user_email is None
^
SyntaxError: invalid syntax
Any friend can help ?
| [] | [] | [
"if len(email) == 0: email = \"test@abc.com\"\n\nHope it helps.\n"
] | [
-2
] | [
"python",
"python_3.x"
] | stackoverflow_0074184254_python_python_3.x.txt |
Q:
Cannot run Spyder because No module named 'PySide'
I wanted to try using Spyder IDE. I was reading this page on how to open and run Spyder: https://github.com/spyder-ide/spyder/releases
I typed the following commands as specified in the page:
conda update qt pyqt
conda update spyder
Both commands gave "# All requ... | Cannot run Spyder because No module named 'PySide' | I wanted to try using Spyder IDE. I was reading this page on how to open and run Spyder: https://github.com/spyder-ide/spyder/releases
I typed the following commands as specified in the page:
conda update qt pyqt
conda update spyder
Both commands gave "# All requested packages already installed.".
I then typed spyder ... | [
"try below commands let me know if it works.\n pip install msgpack\n conda install qt=5.6 pyqt=5.6 sip=4.18\n\n",
"While other solutions found on the web didn't work for me (such as the one above and using $ pip install pyqt5), I solved this by uninstalling and reinstalling Spyder via terminal, using pip.\n\n$ pi... | [
9,
2,
1,
0,
0
] | [] | [] | [
"python",
"spyder"
] | stackoverflow_0051317382_python_spyder.txt |
Q:
Build a custom vim binary with python support and syntax highlighting
Background
The Debian 11 vim package doesn't include python3 support. See the section titled "No python support in Debian 11 vim - evidence" below
I need vim with python3 support for the YouCompleteMe vim plugin. Syntax highlighting is also re... | Build a custom vim binary with python support and syntax highlighting | Background
The Debian 11 vim package doesn't include python3 support. See the section titled "No python support in Debian 11 vim - evidence" below
I need vim with python3 support for the YouCompleteMe vim plugin. Syntax highlighting is also required. To build a new vim, I downloaded the vim 9.0 tarball into /opt/ on ... | [
"\nI need vim with python syntax highlighting\n\nPython syntax highlighting is built-in so you don't need to build Vim manually to get it. You are wasting your and everyone's time.\n\"Python support\" is unrelated to syntax highlighting. It refers to the Python scripting interface that allow users to (partially) wr... | [
1
] | [
"It seems that I have to set $VIMRUNTIME to my new vim/runtime source directory when I try to edit with the new vim binary... Setting this in my ~/.bashrc fixed the problem...\nexport VIMRUNTIME=\"/opt/vim/runtime/\"\n\nNow I have vim with both python3 and functional syntax highlighting.\n"
] | [
-1
] | [
"linux",
"python",
"vim"
] | stackoverflow_0074182575_linux_python_vim.txt |
Q:
Subclassing Python Enum with `auto()`, string values, and an extra property
I have an Enum subclass that I would like to do two things:
Use the lowercased name of the enum as the value for each item and a property called function. I don't want to have to type this out each time, so I'm using auto().
Optionally, a... | Subclassing Python Enum with `auto()`, string values, and an extra property | I have an Enum subclass that I would like to do two things:
Use the lowercased name of the enum as the value for each item and a property called function. I don't want to have to type this out each time, so I'm using auto().
Optionally, allow the user to pass a custom function name that overrides the lowercased name.
... | [
"Until this is fixed (in 3.12), you'll need to use aenum:\nfrom aenum import Enum\n\n...\n\nclass Task(str, LowerNameEnum):\n ...\n DO_ANOTHER_THING = auto(function=\"do_it_do_it\")\n\n\nDisclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.... | [
0
] | [] | [] | [
"enums",
"python"
] | stackoverflow_0074183493_enums_python.txt |
Q:
Dictionary with list values to store the divisors of all the numbers code doesn't work?
The task says 'Write a program that reads N, then reads N integer numbers. The program should use a dictionary with list values to store the divisors of all the numbers. The list of divisors will be printed for each number, in ... | Dictionary with list values to store the divisors of all the numbers code doesn't work? | The task says 'Write a program that reads N, then reads N integer numbers. The program should use a dictionary with list values to store the divisors of all the numbers. The list of divisors will be printed for each number, in ascending order of the numbers. If the number does not have divisors it should not appear in... | [
"\nI think the issue is that it takes only the first input which is 3 runs the code and it outputs\n\nYes, you are correct. You're almost there!\nThat is how input() works: It will stop reading the input when you press \"enter\" on your keyboard. More info on the docs or on this GeeksForGeeks article.\nI'm pretty s... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074181077_python_python_3.x.txt |
Q:
How do I write to a wave file with an array of frequencies? Python
I have 3 different waves. One of 50 one of 100 and one of 150 hz. The code below is how I am getting my data.
frequency3 = 150
num_samples = 48000
sampling_rate = 48000.0
amplitude = 16000
file = "wave3.wav"
noise_wave = [np.sin(2 * np.pi * frequen... | How do I write to a wave file with an array of frequencies? Python | I have 3 different waves. One of 50 one of 100 and one of 150 hz. The code below is how I am getting my data.
frequency3 = 150
num_samples = 48000
sampling_rate = 48000.0
amplitude = 16000
file = "wave3.wav"
noise_wave = [np.sin(2 * np.pi * frequency3 * x/sampling_rate) for x in range(num_samples)]
nframes=num_samples
... | [] | [] | [
"\nYou can't use array in sin\nYour sample duration now only 1 sec\n\ntry this:\nimport wave\nimport struct\nimport numpy as np\n\nnum_samples = 48000\nfrequency = 440 # [440, 330, 220, 110, 528, 756]\nsampling_rate = 48000.0\namplitude = 16000\nfile = \"segment.wav\"\nsine_wave = [0.5 * np.sin(2 * np.pi * x * freq... | [
-1
] | [
"frequency",
"python",
"wave"
] | stackoverflow_0074183579_frequency_python_wave.txt |
Q:
optuna lightgbm integration runs endlessly
I'm using optuna.integration.lightgbm.train and adapting this example with my data, which has about 1M rows in the training set and 700K in the validation set.
But I have been waiting for more than 20 hours and the process does not finish after a while, I notice It has st... | optuna lightgbm integration runs endlessly | I'm using optuna.integration.lightgbm.train and adapting this example with my data, which has about 1M rows in the training set and 700K in the validation set.
But I have been waiting for more than 20 hours and the process does not finish after a while, I notice It has started to overfit since the validation metric (RO... | [
"I'm having trouble too. Some suggestions: 1) add a pruner to callbacks something like:\npruning_callback = optuna.integration.LightGBMPruningCallback( trial, metric = \"binary_logloss\", valid_name = \"valid_0\" )\nlgb.train( \n, callbacks = [ pruning_callback, early_stopping(100), log_evaluation(100 )]\n)\n\n\nd... | [
0
] | [] | [] | [
"lightgbm",
"machine_learning",
"optuna",
"python"
] | stackoverflow_0073882745_lightgbm_machine_learning_optuna_python.txt |
Q:
Update Parameters method gives the same initial and updated values - MLP ANN
I have written an MLP ANN code for a binary classification dataset and am getting 0.88 (88%) Accuracy for my training dataset. My Testing dataset gives me 0.37 - 0.55 Accuracy.
I noticed this was due to my parameters not being updated aft... | Update Parameters method gives the same initial and updated values - MLP ANN | I have written an MLP ANN code for a binary classification dataset and am getting 0.88 (88%) Accuracy for my training dataset. My Testing dataset gives me 0.37 - 0.55 Accuracy.
I noticed this was due to my parameters not being updated after the UpdateParameters method as shown below:
def update_parameters(parameters, g... | [
"Oh yeah, here’s why it’s returning True. First you’re assigning param1 to parameters. Then you’re updating parameters. But since param1 is pointing to parameters, even after updating parameters, param1 still points to the same memory location of parameters. In python everything is treated as an object. Try printin... | [
0
] | [] | [] | [
"jupyter_notebook",
"mlp",
"python"
] | stackoverflow_0074184139_jupyter_notebook_mlp_python.txt |
Q:
Pandas Dataframe add row to new df on x condition in series then delete row in
I need help doing the following and I am confident there is a simpler way to do it with Pandas than how I have tried.
If a specific "cell" in a series meets a condition I want to a) add the entire row to a separate Dataframe, then b) de... | Pandas Dataframe add row to new df on x condition in series then delete row in | I need help doing the following and I am confident there is a simpler way to do it with Pandas than how I have tried.
If a specific "cell" in a series meets a condition I want to a) add the entire row to a separate Dataframe, then b) delete the row from the first Dataframe.
Is there a concise way to do this?
I have bee... | [
"# Create a mask that meets your condition.\nmask = df['column_name'].eq('hello world')\n\n# Make a new DataFrame using this mask.\nnew_df = df.loc[mask]\n\n# Remove these rows from the original DataFrame.\ndf = df.loc[~mask]\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074184253_pandas_python.txt |
Q:
Anaconda Uninstall and .anaconda_backup
I have followed the steps here (https://docs.anaconda.com/anaconda/install/uninstall/) to do a full uninstall of Anaconda.
I didn't, however, delete the .anaconda_backup folder produced in the clean step before doing a simple uninstall. But can't find it if I search in my MA... | Anaconda Uninstall and .anaconda_backup | I have followed the steps here (https://docs.anaconda.com/anaconda/install/uninstall/) to do a full uninstall of Anaconda.
I didn't, however, delete the .anaconda_backup folder produced in the clean step before doing a simple uninstall. But can't find it if I search in my MAC finder. Does the simple remove this, or sho... | [
"I uninstalled and reinstalled the Anaconda Distribution software 3 or 4 times while intentionally leaving a few files behind (such as the .anaconda_backup folder you mentioned) and it didn't cause me any problems when I reinstalled it.\nWhen I went back through my install directory for anaconda3 files, I could not... | [
0
] | [] | [] | [
"anaconda",
"python",
"uninstallation"
] | stackoverflow_0074183746_anaconda_python_uninstallation.txt |
Q:
open() gives FileNotFoundError/IOError: Errno 2 No such file or directory
For some reason my code is having trouble opening a simple file:
This is the code:
file1 = open('recentlyUpdated.yaml')
And the error is:
IOError: [Errno 2] No such file or directory: 'recentlyUpdated.yaml'
Naturally I checked that this is... | open() gives FileNotFoundError/IOError: Errno 2 No such file or directory | For some reason my code is having trouble opening a simple file:
This is the code:
file1 = open('recentlyUpdated.yaml')
And the error is:
IOError: [Errno 2] No such file or directory: 'recentlyUpdated.yaml'
Naturally I checked that this is the correct name of the file.
I have tried moving around the file, giving ope... | [
"\nMake sure the file exists: use os.listdir() to see the list of files in the current working directory\nMake sure you're in the directory you think you're in with os.getcwd() (if you launch your code from an IDE, you may well be in a different directory)\nYou can then either:\n\nCall os.chdir(dir), dir being the ... | [
150,
32,
7,
3,
2,
2,
0,
0
] | [] | [] | [
"file",
"file_io",
"file_not_found",
"path",
"python"
] | stackoverflow_0012201928_file_file_io_file_not_found_path_python.txt |
Q:
How can I sort a 2d array according to its integer value?
I would like to sort each integer value in ascending order and have each P value move along with it.
Input:
[['P1', 168], ['P2', 146], ['P3', 116], ['P4', 113], ['P5', 113], ['P6', 90], ['P7', 28]]
Output:
[['P7', 28],['P6', 90],['P4', 113], ['P5', 113],['... | How can I sort a 2d array according to its integer value? | I would like to sort each integer value in ascending order and have each P value move along with it.
Input:
[['P1', 168], ['P2', 146], ['P3', 116], ['P4', 113], ['P5', 113], ['P6', 90], ['P7', 28]]
Output:
[['P7', 28],['P6', 90],['P4', 113], ['P5', 113],['P3', 116], ['P2', 146], ['P1', 168]]
| [
"For\na=[['P1', 168], ['P2', 146], ['P3', 116], ['P4', 113], ['P5', 113], ['P6', 90], ['P7', 28]]\n\nOne solution could be:\nimport numpy as np\n\na1 = np.sort(a, axis=-1, kind=None, order=None)\na1[:,[0,1]] = a1[:,[1,0]][::-1] <=========== [::-1] to reverse the order\na1\n\nOutput:\n\n"
] | [
0
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0074184425_python_sorting.txt |
Q:
Why Prevent_initial_call does not stop the initial call?
I have the written code below. I have two dropdown menus that work based on chained callbacks. the first dropdown menu gets the datasets and reads the columns' names and updates the options in the second dropdown menu. Then, the parameters can be plotted on ... | Why Prevent_initial_call does not stop the initial call? | I have the written code below. I have two dropdown menus that work based on chained callbacks. the first dropdown menu gets the datasets and reads the columns' names and updates the options in the second dropdown menu. Then, the parameters can be plotted on the chart.
my dataframes look like this:
df={'col1':[12,15,25,... | [
"You can fix it by modifying your code to the following:\n@app.callback(\n Output({'type': 'dynamic-graph', 'index': MATCH}, 'figure'),\n [Input({'type': 'dataset-choice', 'index': MATCH}, 'value'),\n Input({'type': 'feature-choice', 'index': MATCH}, 'value')],\n prevent_initial_call=True\n)\ndef updat... | [
1
] | [] | [] | [
"callback",
"plotly_dash",
"python"
] | stackoverflow_0074182245_callback_plotly_dash_python.txt |
Q:
How can I configure a line chart using pivot_ui?
I would like to create a dynamic line chart in Voila. How can I manipulate the below code to show a standard line graph where the x axis equals column "a" and the y axis equals column "b"? Potentially the user can then dynamically update the output to make the y axi... | How can I configure a line chart using pivot_ui? | I would like to create a dynamic line chart in Voila. How can I manipulate the below code to show a standard line graph where the x axis equals column "a" and the y axis equals column "b"? Potentially the user can then dynamically update the output to make the y axis equal to column "c" by drag and drop etc.
from pivot... | [
"This should be a comment but I cannot post code with comments easily.\nPlease always test your code, preferably in a new notebook so it is fresh kerenl, before you post it.\nYour dataframe assignment won't work. Should it be something like below?\nThat display code won't work in Jupyter notebook classic or Jupyter... | [
0
] | [] | [] | [
"linegraph",
"pivot_table",
"pivottable.js",
"python",
"voila"
] | stackoverflow_0074166663_linegraph_pivot_table_pivottable.js_python_voila.txt |
Q:
Calculate a failure rate based on row values in other columns
I have a DataFrame where a row is the instance of an item that passes or fails (Result column). The instance is associated with a Device (A, B, or C) and also a Batch (1-50). I'd like to be able to calculate the rate of failure (fails/total) in each Bat... | Calculate a failure rate based on row values in other columns | I have a DataFrame where a row is the instance of an item that passes or fails (Result column). The instance is associated with a Device (A, B, or C) and also a Batch (1-50). I'd like to be able to calculate the rate of failure (fails/total) in each Batch per Device.
Device
Batch
Result
A
1
Fail
A
1
Pass
A
... | [
"Try:\nout = df.groupby([\"Device\", \"Batch\"]).agg(lambda x: x.eq(\"Fail\").sum() / len(x))\nprint(out)\n\nPrints:\n Result\nDevice Batch \n1 1 0.50\n 2 0.75\n2 1 0.50\n\n"
] | [
0
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074184469_group_by_pandas_python.txt |
Q:
gtts module not found even though 'Requirement already satisfied'
Im using vs code to try and make my own little virtual assistant. I've installed playsound and gtts along with others but it doesn't seem to work. I've tried installing it again but it just keeps saying that the requirement is already satisfied. I'v... | gtts module not found even though 'Requirement already satisfied' | Im using vs code to try and make my own little virtual assistant. I've installed playsound and gtts along with others but it doesn't seem to work. I've tried installing it again but it just keeps saying that the requirement is already satisfied. I've tried using pip and pip3 but the same thing happens. When i do pip li... | [
"I had the same issue, so I made it like below\n\ninstall python 3.10.8 64-bit\nClick python version around bottom right on the blue status bar in VS code\nIf you have a couple of python version, switch to python 64-bit from 32-bit.\n\nor\npip uninstall gTTS and then pip install gTTS again.\nI hope my suggestion wi... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0066731455_python.txt |
Q:
Character formatting/styling in cells' substrings using python in excel files
I am searching for a quite a long time to achieve formatting for characters in text except using vba...
like this:
ADSGPINDTDANPR
RGTELDDGIQADSGPINDTDANPRY VPGYY ESQSDDPHFHEK
but I am using mac and can't go with some answers I have found... | Character formatting/styling in cells' substrings using python in excel files | I am searching for a quite a long time to achieve formatting for characters in text except using vba...
like this:
ADSGPINDTDANPR
RGTELDDGIQADSGPINDTDANPRY VPGYY ESQSDDPHFHEK
but I am using mac and can't go with some answers I have found like
this
Answer if you know how to do this on a Mac.
| [
"I tried to use range.characters.font as described in this documentation, and it also worked on my mac...\nI tried to make characters' font bold, italic and it worked like it should.\nAlso changing font colors also works using RGB code.\nBut what didn't work was changing the font size of individual characters.\nbel... | [
0
] | [] | [] | [
"excel",
"openpyxl",
"python",
"python_3.x",
"xlwings"
] | stackoverflow_0074172990_excel_openpyxl_python_python_3.x_xlwings.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.