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:
Is there a package that converts xmltodict dictionaries to lxml trees?
The problem I have is this. I've started the XML creation using the dictionary structure used by xmltodict Python package so I can use the unparse method to create the XML. But I think I reached a point where xmltodict can't help me. I have act... | Is there a package that converts xmltodict dictionaries to lxml trees? | The problem I have is this. I've started the XML creation using the dictionary structure used by xmltodict Python package so I can use the unparse method to create the XML. But I think I reached a point where xmltodict can't help me. I have actions in this dictionary format, highly nested each, something like this, jus... | [
"It seems that no such package. So far I have this solution. I doesn't handle #text keys and there can be problems with namespaces.\n\"\"\"\nConverts the dictionary used by xmltodict package to represent XMLs\nto lxml.\n\"\"\"\nfrom typing import Dict, Any\n\nfrom lxml import etree\n\nXmlDictType = Dict[str, Any]\n... | [
0
] | [] | [] | [
"lxml",
"python",
"xmltodict"
] | stackoverflow_0074141908_lxml_python_xmltodict.txt |
Q:
Transpose horizontally stored data to multiple rows
I have a sheet I need to transform from data being stored horizontally to vertically, i.e. from:
Company ID
DoB
Name
DoB
Name
DoB
Name
ID 1
DoB 1
Name 1
DoB 2
Name 2
DoB 3
Name 3
ID 2
DoB 4
Name 4
DoB 5
Name 5
To:
Company ID
DoB
Name
ID 1
DoB 1
Name 1
ID 1... | Transpose horizontally stored data to multiple rows | I have a sheet I need to transform from data being stored horizontally to vertically, i.e. from:
Company ID
DoB
Name
DoB
Name
DoB
Name
ID 1
DoB 1
Name 1
DoB 2
Name 2
DoB 3
Name 3
ID 2
DoB 4
Name 4
DoB 5
Name 5
To:
Company ID
DoB
Name
ID 1
DoB 1
Name 1
ID 1
DoB 2
Name 2
ID 1
DoB 3
Name 3
ID... | [
"You can use:\nout = (df\n .set_index('Company ID')\n .pipe(lambda d: d.set_axis(\n pd.MultiIndex\n .from_arrays([d.columns,\n d.groupby(level=0, axis=1).cumcount().add(1)]),\n axis=1)\n )\n .stack()\n .reset_index().drop(colum... | [
1,
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074179594_dataframe_pandas_python.txt |
Q:
python flask single page search and result with pagination
I have a small flask app, a single table with several columns and what I try to do seems also simple: A single webpage showing the form based query and the results afterwards. It works fine. Next step was including pagination (due to the amount), but than ... | python flask single page search and result with pagination | I have a small flask app, a single table with several columns and what I try to do seems also simple: A single webpage showing the form based query and the results afterwards. It works fine. Next step was including pagination (due to the amount), but than I run in a issue:
@archive.route('/searchEvents/', methods=['GET... | [
"I can see that the href of the next page is a static string, you have to concat into that string a variable that holds the new number.\nSecond of all you have to make sure that when the user clicks the next link, when rendering the HTML template you have to send it the next number so that its updated for the next ... | [
1
] | [] | [] | [
"flask",
"flask_sqlalchemy",
"python"
] | stackoverflow_0074180410_flask_flask_sqlalchemy_python.txt |
Q:
Finding third largest element in the list without using len() and sort()
Here is the code which I used to find the third largest element in the list without using any built in functions like max,sort,len.
list = [12, 45, 2, 41, 31, 10, 8, 6, 4]
#list = [35,10,45,9,8,5]
largest_1 = list[0]
largest_2 = list[0]
large... | Finding third largest element in the list without using len() and sort() | Here is the code which I used to find the third largest element in the list without using any built in functions like max,sort,len.
list = [12, 45, 2, 41, 31, 10, 8, 6, 4]
#list = [35,10,45,9,8,5]
largest_1 = list[0]
largest_2 = list[0]
largest_3 = list[0]
print (largest_1)
print (largest_2)
print (largest_3)
for each ... | [
"@venkat: Here another proposal to get the third largest number out of your list without using len() and sort().\ndef find_largest(alist):\n \"\"\"\n Find the largest number in a list.\n\n Return the largest number found and it index\n \"\"\"\n largest = alist[0]\n for item in alist[1:]:\n ... | [
3,
2,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0053464722_list_python.txt |
Q:
How to send a numpy array to armadillo (C++) and return a numpy array from armadillo
I want to send a numpy array to a Armadillo (C++) and output a numpy array from the C++ program. I didn't find any tutorials online for this. Can someone give me pointers on how to do this ?
A:
You can rely on cython and the nu... | How to send a numpy array to armadillo (C++) and return a numpy array from armadillo | I want to send a numpy array to a Armadillo (C++) and output a numpy array from the C++ program. I didn't find any tutorials online for this. Can someone give me pointers on how to do this ?
| [
"You can rely on cython and the numpy c interface for the data conversion. There are different projects that implement this including armanpy, a library for conversion between numpy and armadillo, or mlpack, a machine learning library that uses armadillo as its data and linear algebra backend. The easiest method th... | [
2
] | [
"first convert numpy array to c++ array and enter to armadillo and from outpu\n"
] | [
-2
] | [
"armadillo",
"c++",
"numpy",
"python"
] | stackoverflow_0054042246_armadillo_c++_numpy_python.txt |
Q:
Selecting categorical/discrete features and numerical features of sklearn dataset using Pandas
I am unable to spot feature(s) that are 'categorical/discrete'. I want to do this to then compute the frequency of
each value of the categorical feature(s). And similarly, I want to eventually spot and use all numerical ... | Selecting categorical/discrete features and numerical features of sklearn dataset using Pandas | I am unable to spot feature(s) that are 'categorical/discrete'. I want to do this to then compute the frequency of
each value of the categorical feature(s). And similarly, I want to eventually spot and use all numerical features.
In this dataset from sklearn, which feature(s) are categorical/discrete? And is there a wa... | [
"The question is subjective. Obviously integers are discrete, so you can get non-float values by rounding to integer and checking which columns only have integer values:\ndf.eq(df.astype(int)).all()\n\noutput:\nalcohol False\nmalic_acid False\nash ... | [
2
] | [] | [] | [
"data_mining",
"numpy",
"pandas",
"python",
"scikit_learn"
] | stackoverflow_0074180660_data_mining_numpy_pandas_python_scikit_learn.txt |
Q:
Output is just long and not the normal 2D array
I'm new to python and trying to understand 2D arrays. I'm trying to write a code in which someone inputs and stores the employee ID, department, and salary for 10 employees. Which is then stored using a 2D array The following will be outputted:
All the information w... | Output is just long and not the normal 2D array | I'm new to python and trying to understand 2D arrays. I'm trying to write a code in which someone inputs and stores the employee ID, department, and salary for 10 employees. Which is then stored using a 2D array The following will be outputted:
All the information with the appropriate column title
How many employees a... | [
"this is the input part. (input like: 1,Accunts,1000 ). data will be split by comma and then converted to the required data type:\ndata = []\nwhile True:\n if (inp := input()) != '':\n data.append([typ(value.strip()) for typ, value in zip((int, str, int), inp.split(','))])\n else:\n break\n\nthi... | [
0
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0074179838_arrays_python.txt |
Q:
Pandas - How to create new columns and merge back to the existing dataframe
I have dataframe as below
df = pd.DataFrame([[1,5,'Dog'],[2,6,'Dog'],[3,7,'Cat'],[4,8,'Cat']],columns=['A','B','Type'])
Index
A
B
Type
0
1
5
Dog
1
2
6
Dog
2
3
7
Cat
3
4
8
Cat
Based on the 'Type' column value, I need to apply its own ... | Pandas - How to create new columns and merge back to the existing dataframe | I have dataframe as below
df = pd.DataFrame([[1,5,'Dog'],[2,6,'Dog'],[3,7,'Cat'],[4,8,'Cat']],columns=['A','B','Type'])
Index
A
B
Type
0
1
5
Dog
1
2
6
Dog
2
3
7
Cat
3
4
8
Cat
Based on the 'Type' column value, I need to apply its own function(for example for Dog rows, call its Dog function and get the ... | [
"You don't have to split and then re-merge the dataframes, you can use .loc:\ndf.loc[df['Type'] == 'Dog', 'C'] = 'Dog1 Value'\ndf.loc[df['Type'] == 'Cat', 'C'] = 'Cat1 Value'\n\ndf.loc[df['Type'] == 'Dog', 'D'] = 'Dog2 Value'\ndf.loc[df['Type'] == 'Cat', 'D'] = 'Cat2 Value'\n\nSorry for the values, I don't know whi... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074180727_pandas_python.txt |
Q:
How can I create Pulsar stream from Python?
How can I create a Kafka stream directly from Python? I know that I need to use GQLAlchemy but I don't know the exact commands.
A:
GQLAlchemy is a fully open-source Python library and Object Graph Mapper (OGM) - a link between graph database objects and Python objects.... | How can I create Pulsar stream from Python? | How can I create a Kafka stream directly from Python? I know that I need to use GQLAlchemy but I don't know the exact commands.
| [
"GQLAlchemy is a fully open-source Python library and Object Graph Mapper (OGM) - a link between graph database objects and Python objects.\nAn Object Graph Mapper or OGM provides a developer-friendly workflow that allows for writing object-oriented notation to communicate with graph databases. This means that inst... | [
0
] | [] | [] | [
"apache_pulsar",
"memgraphdb",
"python"
] | stackoverflow_0074180803_apache_pulsar_memgraphdb_python.txt |
Q:
How can I create Kafka stream from Python?
How can I create a Kafka stream directly from Python? I know that I need to use GQLAlchemy but I don't know the exact commands.
A:
GQLAlchemy is a fully open-source Python library and Object Graph Mapper (OGM) - a link between graph database objects and Python objects.
... | How can I create Kafka stream from Python? | How can I create a Kafka stream directly from Python? I know that I need to use GQLAlchemy but I don't know the exact commands.
| [
"GQLAlchemy is a fully open-source Python library and Object Graph Mapper (OGM) - a link between graph database objects and Python objects.\nAn Object Graph Mapper or OGM provides a developer-friendly workflow that allows for writing object-oriented notation to communicate with graph databases. This means that inst... | [
0
] | [] | [] | [
"apache_kafka",
"memgraphdb",
"python"
] | stackoverflow_0074180765_apache_kafka_memgraphdb_python.txt |
Q:
how can I convert date(YYYY, MM, DD) format to YYYY/MM/DD with python?
I have a JSON that returns a date in the following date format:
datetime(2015, 12, 1)
So the key value from JSON is
'CreateDate': datetime(2015, 1, 1)
In order to be able to subtract two dates, I need to convert above to date format:
YYYY/MM... | how can I convert date(YYYY, MM, DD) format to YYYY/MM/DD with python? | I have a JSON that returns a date in the following date format:
datetime(2015, 12, 1)
So the key value from JSON is
'CreateDate': datetime(2015, 1, 1)
In order to be able to subtract two dates, I need to convert above to date format:
YYYY/MM/DD
so in above case that would become: 2015/12/01
Is there a smart way to ... | [
"datetime(2015,12,1).strftime(\"%Y/%m/%d\")\n\nwill do the trick for you. A complete python program would look like this.\n# import the datetime and date classes from the datetime module \n from datetime import datetime, date \n\n# create your datetime(..) instance from your JSON somehow\n# The included Python JS... | [
2,
1
] | [] | [] | [
"date",
"datetime",
"python"
] | stackoverflow_0074180708_date_datetime_python.txt |
Q:
Python - Pulling data from API (Not limiting to the default 100 rows of data that get returned)
I am trying to pull data of a API and it looks like it only returns back the first 100 rows. I am trying to see how can we alter the value from the default 100 to say 1000 or so.
url = "https://api.keka.com/v1/employees... | Python - Pulling data from API (Not limiting to the default 100 rows of data that get returned) | I am trying to pull data of a API and it looks like it only returns back the first 100 rows. I am trying to see how can we alter the value from the default 100 to say 1000 or so.
url = "https://api.keka.com/v1/employees"
payload={}
headers = {
'Authorization': 'Authorization',
'Content-Type': 'application/json'
}
res... | [
"From the docs:\n\nYou can add those parameters to payload:\npayload={\"pageindex\":2, \"pagesize\":100}\nheaders = {\n'Authorization': 'Authorization',\n'Content-Type': 'application/json'\n}\n\nresponse = requests.request(\"GET\", url, headers=headers, data=payload)\n\nI haven't interacted with the api, but that i... | [
0,
0
] | [] | [] | [
"api",
"python"
] | stackoverflow_0068018554_api_python.txt |
Q:
Python - How to handle Cognito client exceptions in Boto3?
How am I supposed to handle AWS Cognito exceptions? I have this code below for handling an exception, but this feels weird, because if client initialization fails then I'm not sure what happens.
function.py
def post(self, request):
try:
client ... | Python - How to handle Cognito client exceptions in Boto3? | How am I supposed to handle AWS Cognito exceptions? I have this code below for handling an exception, but this feels weird, because if client initialization fails then I'm not sure what happens.
function.py
def post(self, request):
try:
client = boto3.client("cognito-idp", region_name=settings.COGNITO_AWS_R... | [
"I think the way you're handling it is the correct way. Rather than the generic except Exception as e, a better option is to catch the ClientError (from botocore.exceptions import ClientError) and parse the error code. Your exception handling though is more specific so I would stick with that. It also seems that's ... | [
0
] | [] | [] | [
"amazon_cognito",
"amazon_web_services",
"python"
] | stackoverflow_0069319915_amazon_cognito_amazon_web_services_python.txt |
Q:
How do I split a Pandas dataframe after a row using string conditions and then make the strings a variable?
I have XY datasets that have been concatenated together along with labels and are in one column. I want to split the dataset after the string labels, split the numerical data then then insert a third column ... | How do I split a Pandas dataframe after a row using string conditions and then make the strings a variable? | I have XY datasets that have been concatenated together along with labels and are in one column. I want to split the dataset after the string labels, split the numerical data then then insert a third column of the label. So it goes from this:
import pandas as pd
df = pd.DataFrame.from_dict({'XYZ':
['Monday', '120 1... | [
"You can use a regex to extract your 3 values (see the regex demo), then rework the rows with ffill and dropna:\ndf2 = (df['XYZ']\n # extract Z or X and Y\n .str.extract(r'(^\\S+$)|(\\d+)\\s+(\\d+)')\n .set_axis(['Z', 'X', 'Y'], axis=1)\n # ffill Z and remove the original header\n .assign(Z=lambda d: d['Z'].ffill()... | [
2,
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074180740_dataframe_pandas_python.txt |
Q:
What is the syntax in python to write strings and numbers to file?
I trying to do the following:
f = open("file", "w")
index = 1
f.write("my_index is: %d\n", index)
but I get the following error:
f.write("my_index is: %d\n", index)
TypeError: write() takes exactly one argument (2 given)
How can I fix it? I tried... | What is the syntax in python to write strings and numbers to file? | I trying to do the following:
f = open("file", "w")
index = 1
f.write("my_index is: %d\n", index)
but I get the following error:
f.write("my_index is: %d\n", index)
TypeError: write() takes exactly one argument (2 given)
How can I fix it? I tried the syntax of c..
| [
"You could concatenate it like\nf = open(\"file.txt\", \"w\")\nindex = 1\nf.write(\"my_index is:\\n\"+ str(index))\n\nor use an f string\nf = open(\"file.txt\", \"w\")\nindex = 2\nf.write(f\"my_index is:\\n{index}\")\n\n"
] | [
0
] | [] | [] | [
"file",
"python",
"python_3.x"
] | stackoverflow_0074180691_file_python_python_3.x.txt |
Q:
Matplotlib pyplot axes formatter
I have an image:
Here in the y-axis I would like to get 5x10^-5 4x10^-5 and so on instead of 0.00005 0.00004.
What I have tried so far is:
fig = plt.figure()
ax = fig.add_subplot(111)
y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=True)
ax.yaxis.set_major_formatter(y... | Matplotlib pyplot axes formatter | I have an image:
Here in the y-axis I would like to get 5x10^-5 4x10^-5 and so on instead of 0.00005 0.00004.
What I have tried so far is:
fig = plt.figure()
ax = fig.add_subplot(111)
y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=True)
ax.yaxis.set_major_formatter(y_formatter)
ax.plot(m_plot,densities1... | [
"You can use matplotlib.ticker.FuncFormatter to choose the format of your ticks with a function as shown in the example code below. Effectively all the function is doing is converting the input (a float) into exponential notation and then replacing the 'e' with 'x10^' so you get the format that you want.\nimport ma... | [
20,
0
] | [] | [] | [
"axes",
"matplotlib",
"python",
"ticker"
] | stackoverflow_0025119193_axes_matplotlib_python_ticker.txt |
Q:
replacing strings within a pandas data frame column
I have a pandas data frame with a column named "content" that contains text. I want to remove some words from each text within this column. I thought of replacing each string by empty string, but when I print the result of my function I see that the words have no... | replacing strings within a pandas data frame column | I have a pandas data frame with a column named "content" that contains text. I want to remove some words from each text within this column. I thought of replacing each string by empty string, but when I print the result of my function I see that the words have not been removed. My code is below:
def replace_words(t):
... | [
"Two problems:\n\nIf you split using for i in t: each i is a letter, not a word.\nt.replace does not work inplace\n\nUse this:\ndef replace_words(t):\n words = ['Livre', 'Chapitre', 'Titre', 'Chapter', 'Article' ]\n for i in t.split(' '):\n # print(i) # remove to see problem 1\n if i in words:\n... | [
1,
1
] | [] | [] | [
"function",
"pandas",
"python",
"replace"
] | stackoverflow_0074180734_function_pandas_python_replace.txt |
Q:
How to get array containing n elements with equal step between them using numpy?
Given [a, b] and n. My goal is to get array [x_1, x_2, ..., x_n] which contains n elements with equal step between them. How can I do it using numpy?
A:
You are probably looking for np.linspace
np.linspace(a,b,n)
| How to get array containing n elements with equal step between them using numpy? | Given [a, b] and n. My goal is to get array [x_1, x_2, ..., x_n] which contains n elements with equal step between them. How can I do it using numpy?
| [
"You are probably looking for np.linspace\nnp.linspace(a,b,n)\n\n"
] | [
3
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074180872_arrays_numpy_python.txt |
Q:
How do I stop Selenium from closing the driver during execution?
I am trying to learn Selenium to scrape some Javascript heavy websites. I can locate and extract information just fine. However, I find that for some sites I need to switch my user agent. I did it the following way to test it:
from selenium import we... | How do I stop Selenium from closing the driver during execution? | I am trying to learn Selenium to scrape some Javascript heavy websites. I can locate and extract information just fine. However, I find that for some sites I need to switch my user agent. I did it the following way to test it:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from fak... | [
"I am not sure if it is possible that the problem is related to the webdriver version you are using or not but when I tried to add time.sleep(n) to your code while using webdriver_manager library to download most recent version of ChromeWebDriver I had the chance to look at the website and the browser didn't close ... | [
1,
1
] | [] | [] | [
"python",
"selenium",
"selenium_chromedriver",
"selenium_webdriver",
"web_scraping"
] | stackoverflow_0070639403_python_selenium_selenium_chromedriver_selenium_webdriver_web_scraping.txt |
Q:
Сompare columns in dataframes and update them
I have two DataFrames:
a = [{'name': 'AAA'}, {'name': 'BBB'}, {'name': 'BBB'}, {'name': 'CCC'}, {'name': 'DDD'}, {'name': 'EEE'}]
df = pd.DataFrame(a)
b = [{'name': 'AAA='}, {'name': 'BBB='}, {'name': 'DDD='}]
df = pd.DataFrame(a)
df1 = pd.DataFrame(b)
print(df)
print(... | Сompare columns in dataframes and update them | I have two DataFrames:
a = [{'name': 'AAA'}, {'name': 'BBB'}, {'name': 'BBB'}, {'name': 'CCC'}, {'name': 'DDD'}, {'name': 'EEE'}]
df = pd.DataFrame(a)
b = [{'name': 'AAA='}, {'name': 'BBB='}, {'name': 'DDD='}]
df = pd.DataFrame(a)
df1 = pd.DataFrame(b)
print(df)
print()
print(df1)
I need to compare values in datafram... | [
"If the = is always in the end, a simple method could be:\n# which values of df['name'] are also in df1['name']?\nm = df['name'].isin(df1['name'].str.rstrip('='))\n\n# select those and add a \"=\"\ndf.loc[m, 'name'] += '='\n\nAnother approach that works with any position of the =:\ns = df1['name'].set_axis(df1['nam... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074180972_dataframe_pandas_python.txt |
Q:
Trouble execute project python in bash
i'm trying execute project python in terminal but appear this error:
(base) hopu@docker-manager1:~/bentoml-airquality$ python src/main.py
Traceback (most recent call last):
File "src/main.py", line 7, in <module>
from src import VERSION, SERVICE, DOCKER_IMAGE_NAME
Modu... | Trouble execute project python in bash | i'm trying execute project python in terminal but appear this error:
(base) hopu@docker-manager1:~/bentoml-airquality$ python src/main.py
Traceback (most recent call last):
File "src/main.py", line 7, in <module>
from src import VERSION, SERVICE, DOCKER_IMAGE_NAME
ModuleNotFoundError: No module named 'src'
The ... | [
"Your PYTHONPATH is determined by the directory your python executable is located, not from where you're executing it. For this reason, you should be able to import the files directly, and not from source. You're trying to import from /src, but your path is already in there. Maybe something like this might work:\nf... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0074180540_python.txt |
Q:
Snakemake: specify cluster per rule
I am running a large workflow in snakemake, that employs cluster execution (--cluster qsub) and a custom profile (--profile custom) for execution in a user-specific computing environment. How can I specify which computing environment (cluster, profile or local) to use for every ... | Snakemake: specify cluster per rule | I am running a large workflow in snakemake, that employs cluster execution (--cluster qsub) and a custom profile (--profile custom) for execution in a user-specific computing environment. How can I specify which computing environment (cluster, profile or local) to use for every rule?
Otherwise, would it be possible to ... | [
"Specifying rules for local execution can be done via localrules:\n\nThe keyword localrules allows to mark a rule as local, so that it is not submitted to the cluster and instead executed on the host node\n\nSee docs.\nlocalrules: all, foo\n\nrule all:\n input: ...\n\nrule foo:\n ...\n\nrule bar:\n ...\n\n... | [
1
] | [] | [] | [
"python",
"snakemake"
] | stackoverflow_0074178823_python_snakemake.txt |
Q:
Tkinter - Configure a grid properly: why some widgets don't appear?
I'm trying to design an interface in Python using Tkinter. The interface should be divided into five rows. In each of these row, a button or a frame/label frame shold be accomodate. In the case of a frame/label frame row, other widgets will be hos... | Tkinter - Configure a grid properly: why some widgets don't appear? | I'm trying to design an interface in Python using Tkinter. The interface should be divided into five rows. In each of these row, a button or a frame/label frame shold be accomodate. In the case of a frame/label frame row, other widgets will be hosted. So I decided to define a frame that will act as a container of butto... | [
"I just added some modifications to your code, I added the height and width attributes for the LabelFrame object. Not sure why but without those attributes the LabelFrame is not being shown.\nLine modified:\nLabelframe_ResultsFolderLocation = tk.LabelFrame(ExtFrame, height=40,width=150)\n\nFull Code:\nimport sys\ni... | [
2,
1
] | [] | [] | [
"frame",
"python",
"tkinter",
"user_interface",
"widget"
] | stackoverflow_0074180224_frame_python_tkinter_user_interface_widget.txt |
Q:
Switch to another database in Django
I have a django project that was created on an Oracle database and I want to switch to ANOTHER Oracle database. I have followed this tutorial https://pythonfusion.com/switch-database-django/, but there is a problem that not all models are created initially in Django, some are c... | Switch to another database in Django | I have a django project that was created on an Oracle database and I want to switch to ANOTHER Oracle database. I have followed this tutorial https://pythonfusion.com/switch-database-django/, but there is a problem that not all models are created initially in Django, some are created using inspectdb on existing tables ... | [
"I think you have to take a look at the managed attribute of each model meta class.\nIf managed is true then django will change the model in the database.\nUnmanaged model :\nclass MyModel(models.Model):\n ...\n\n class Meta:\n managed = False # This means django will ignore MyModel when migrating\n\nM... | [
1,
1,
0
] | [] | [] | [
"django",
"oracle",
"python",
"sql"
] | stackoverflow_0074180466_django_oracle_python_sql.txt |
Q:
pythonic way to vectorize ifelse over list
What is the most pythonic way to reverse the elements of one list based on another equally-sized list?
lista = [1,2,4]
listb = ['yes', 'no', 'yep']
# expecting [-1, 2,-4]
[[-x if y in ['yes','yep'] else x for x in lista] for y in listb]
# yields [[-1, -2, -4], [1, 2, 4]... | pythonic way to vectorize ifelse over list | What is the most pythonic way to reverse the elements of one list based on another equally-sized list?
lista = [1,2,4]
listb = ['yes', 'no', 'yep']
# expecting [-1, 2,-4]
[[-x if y in ['yes','yep'] else x for x in lista] for y in listb]
# yields [[-1, -2, -4], [1, 2, 4], [-1, -2, -4]]
if listb[i] is yes or yep, resu... | [
"using zip?\n>>> [-a if b in ('yes','yep') else a for a,b in zip(lista, listb)]\n[-1, 2, -4]\n\n",
"Alternatively, using tuple indices with zip:\n[(x,-x)[y in ('yes','yep')] for x,y in zip(lista,listb)] \n# [-1, 2, -4]\n\n",
"Another interesting solution is using itertools.starmap and zip:\nimport itertools as ... | [
3,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0074180341_python.txt |
Q:
Django ORM Get users who have NOT updated their salary information in the last 1 year (Simlpe History )
I want to bring users who have not updated their salary information in the last 1 year. BUT WITH ORM not For Loop.
from simple_history.models import HistoricalRecords
class User(AbstractUser):
...
salar... | Django ORM Get users who have NOT updated their salary information in the last 1 year (Simlpe History ) | I want to bring users who have not updated their salary information in the last 1 year. BUT WITH ORM not For Loop.
from simple_history.models import HistoricalRecords
class User(AbstractUser):
...
salary_expectation = models.IntegerField()
history = HistoricalRecords(cascade_delete_history=True)
##... | [
"I can see that this is a package which has its documentation in querying its entries, see below:\nhttps://django-simple-history.readthedocs.io/en/latest/querying_history.html\nnevertheless you can do that intuitively following Django's normal behavior and a couple of SQL knowledge, I'd expect that history field's ... | [
2,
0
] | [] | [] | [
"django",
"django_models",
"django_simple_history",
"django_views",
"python"
] | stackoverflow_0074180074_django_django_models_django_simple_history_django_views_python.txt |
Q:
Can't check what button is pressed in pynput
I have problem with Keys in pynput
on_press function should check if button pressed i 'h' but it gives error
from pynput.keyboard import Key, Listener
def on_press(key):
print(key)
if key == Key.h:
print('done')
def on_release(key):
print('{0} rele... | Can't check what button is pressed in pynput | I have problem with Keys in pynput
on_press function should check if button pressed i 'h' but it gives error
from pynput.keyboard import Key, Listener
def on_press(key):
print(key)
if key == Key.h:
print('done')
def on_release(key):
print('{0} release'.format(key))
if key == Key.esc:
... | [
"the error is created by the if key == Key.h: statement inside the on_press function. When i comment this out, it works without error.\nSo this works:\nfrom pynput.keyboard import Key, Listener\n\n\ndef on_press(key):\n print(key)\n # if key == Key.h: # <-- cause the error\n # print('done') # <-- c... | [
1,
0
] | [] | [] | [
"key",
"pynput",
"python"
] | stackoverflow_0074180672_key_pynput_python.txt |
Q:
How is a Python class object instance passed to a function? Are class instances in Python pass by reference or pass by value
I don't see any questions on SO regarding this, so I would like to ask how a Python class object instance is passed into a function and how it behaves within the function. I have some suspic... | How is a Python class object instance passed to a function? Are class instances in Python pass by reference or pass by value | I don't see any questions on SO regarding this, so I would like to ask how a Python class object instance is passed into a function and how it behaves within the function. I have some suspicions from the behaviour I got from running this snippet:
(Note: I understand there are better ways to achieve the same behaviour f... | [
"In python you need to return the value. When calling the function python is making a copy of your animal_1 object and destroying it after the function ends. If you want to change animal_1 you need to return it as the function result.\nclass Animal:\n def __init__(self, name, sound):\n self.name = name\n ... | [
0,
0
] | [] | [] | [
"object",
"oop",
"python",
"python_3.x",
"reference"
] | stackoverflow_0074180644_object_oop_python_python_3.x_reference.txt |
Q:
is there a simple way to test if any variable is " "?
I am learning python and I am almost done with making tick tack toe but the code for checking if the game is a tie seems more complicated then it needs to be. is there a way of simplifying this?
if a1 != " " and a2 != " " and a3 != " " and b1 != " " and b2 ... | is there a simple way to test if any variable is " "? | I am learning python and I am almost done with making tick tack toe but the code for checking if the game is a tie seems more complicated then it needs to be. is there a way of simplifying this?
if a1 != " " and a2 != " " and a3 != " " and b1 != " " and b2 != " " and b3 != " " and c1 != " " and c2 != " " and c3 != ... | [
"Instead of saving every single table field as it's own variable, I'd recommend saving them together under the same structure. My preference would be an array, but you could also use a dict. Here are two examples of how you would then check to see if all of the items are empty:\n# list approach\ntable = [\n \" \... | [
0,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074180904_python.txt |
Q:
Regex (in Python) for matching whitespace that is preceeded by a even number of quotation marks
I need match the whitespace (for re.split) but only when it is outside of quotation marks.
The method I'm trying is so long as there are an even number of quotations before the whitespace.
"(?<=\".*?\")\s+"
This doesn'... | Regex (in Python) for matching whitespace that is preceeded by a even number of quotation marks | I need match the whitespace (for re.split) but only when it is outside of quotation marks.
The method I'm trying is so long as there are an even number of quotations before the whitespace.
"(?<=\".*?\")\s+"
This doesn't work as look-behinds have to be constant size.
EDIT: Turns out look-around is immediate, while I wa... | [
"What about ^[^\\\"]*(\\\"[^\\\"]*\\\"[^\\\"]*)*(\\s+)?\nThis is using [^\\\"]* for \"any number of characters that are not quotation marks\" to prevent a \"great\" 42\" monitor from being matched in three possible ways (first to second quotation mark, first to third, or second to third).\nSo basically it says:\n\n... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074180827_python_regex.txt |
Q:
get the number of involved singer in a phase
I have a dataset like this
import pandas as pd
df = pd.read_csv("music.csv")
df
name
date
singer
language
phase
1
Yes or No
02.01.20
Benjamin Smith
en
1
2
Parabens
01.06.21
Rafael Galvao;Simon Murphy
pt;en
2
3
Love
12.11.20
Michaela Condell
en
1
4
Paz
11.07.19
An... | get the number of involved singer in a phase | I have a dataset like this
import pandas as pd
df = pd.read_csv("music.csv")
df
name
date
singer
language
phase
1
Yes or No
02.01.20
Benjamin Smith
en
1
2
Parabens
01.06.21
Rafael Galvao;Simon Murphy
pt;en
2
3
Love
12.11.20
Michaela Condell
en
1
4
Paz
11.07.19
Ana Perez; Eduarda Pinto
es;pt
3
5
Stop... | [
"You do not need to split/explode, you can directly count the number of ; per row and add 1:\ndf['singer'].str.count(';').add(1).groupby(df['phase']).sum()\n\nIf you want the classical split/explode:\n(df.assign(singer=df['singer'].str.split(';'))\n .explode('singer')\n .groupby('phase')['singer'].count()\n)\n\... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074181164_python.txt |
Q:
I want to find the count for each product id and to create a dictionary with the product_id as the key and the number of times the product was ordered
orders = {'U123':{'name':'Sumit Shukla', 'email':'ss@gmail.com', 'phone':8608538199, 'product':['p1', 'p2', 'p5']},
'U121':{'name':'Ajay', 'email':'aj@gma... | I want to find the count for each product id and to create a dictionary with the product_id as the key and the number of times the product was ordered | orders = {'U123':{'name':'Sumit Shukla', 'email':'ss@gmail.com', 'phone':8608538199, 'product':['p1', 'p2', 'p5']},
'U121':{'name':'Ajay', 'email':'aj@gmail.com', 'phone':7708538199, 'product':['p5', 'p2', 'p5']},
'U124':{'name':'Vijay', 'email':'vj@gmail.com', 'phone':870853819, 'product':['p1', 'p... | [
"assuming product_id is p1, p2 etc:\nproductsBought = {}\n\nfor productId in orders:\n \n order = orders[productId][\"product\"]\n\n for product in order:\n \n try:\n \n productsBought[product] += 1 #try to increment the amount of products with that id bou... | [
0,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074171477_dictionary_list_python.txt |
Q:
Python cant find database if script is run from other file
Solved in comment
I have this struggle with a dataheavy project. I can run a file that uses a query file -- Al the query's and converters are in here -- without problems, but when I run a file that runs that file again, I get an error that the db cant be f... | Python cant find database if script is run from other file | Solved in comment
I have this struggle with a dataheavy project. I can run a file that uses a query file -- Al the query's and converters are in here -- without problems, but when I run a file that runs that file again, I get an error that the db cant be found.
so:
Queryfile() : No problem,
Queryfile() -> Actionfile()... | [
"The solution was related to the path of the SQLite database:\nEverylayer in the project has his own path to connect with the database.\nExample:\nwithin two nested folders to reach the db would need the path: sqlite:///../../core_data/SQLITEdatabase_db.db\nwhile the main route only needed: sqlite:///core_data/SQLI... | [
0
] | [] | [] | [
"data_science",
"python",
"sqlite"
] | stackoverflow_0072141358_data_science_python_sqlite.txt |
Q:
How to create a DataFrame from existing DataFrame with count of a few columns as a new column
I am trying to create a new data frame from an existing data frame with the count of existing columns in the data frame.
Let's assume I have following DataFrame
cus_Type
ID
ID_type
R
100
X
S
100
Y
R
101
X
S
102
Y
P
... | How to create a DataFrame from existing DataFrame with count of a few columns as a new column | I am trying to create a new data frame from an existing data frame with the count of existing columns in the data frame.
Let's assume I have following DataFrame
cus_Type
ID
ID_type
R
100
X
S
100
Y
R
101
X
S
102
Y
P
103
X
B
104
Y
P
105
X
B
106
Y
K
108
D
I would like to create a new data Frame... | [
"Some options:\ndf.value_counts(['cus_Type', 'ID_type'], sort=False).reset_index(name='count')\n\nOr:\ndf.groupby(['cus_Type', 'ID_type'], sort=False, as_index=False).agg(count=('ID', 'count'))\n\nOr:\ndf.groupby(['cus_Type', 'ID_type'], sort=False)['ID'].count().reset_index(name='count')\n\noutput:\n cus_Type ID_... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074181193_dataframe_pandas_python.txt |
Q:
What's the alternative to subprocess.CREATE_NEW_CONSOLE in Linux?
I have a Python 3.9 script that starts another process in a new console. The 'other process' keeps running even after the original one has completed.
This is what I have on Windows:
# startup.py script
# =================
import sys, subprocess
if... | What's the alternative to subprocess.CREATE_NEW_CONSOLE in Linux? | I have a Python 3.9 script that starts another process in a new console. The 'other process' keeps running even after the original one has completed.
This is what I have on Windows:
# startup.py script
# =================
import sys, subprocess
if __name__ == '__main__':
print('start startup.py script')
argum... | [
"Unix doesn’t provide this option/service, but you can run a terminal emulator:\nsubprocess.Popen([\"gnome-terminal\",\"--\"]+arguments)\n\nThere isn’t a standard means of finding which terminal emulator to use (or even which are available), unfortunately. Checking shutil.which for a few common ones might be the r... | [
0
] | [] | [] | [
"console",
"linux",
"python",
"python_3.9",
"subprocess"
] | stackoverflow_0074180321_console_linux_python_python_3.9_subprocess.txt |
Q:
I want the program to immediately end the current iteration of the loop and start a new one if I enter a negative number
num=int(input('Enter a number:'))
while num !=0:
if num>0:
if num%2==0 and num%7==0:
print('The number is a multiple of two and seven.' )
num=int(input('Ente... | I want the program to immediately end the current iteration of the loop and start a new one if I enter a negative number | num=int(input('Enter a number:'))
while num !=0:
if num>0:
if num%2==0 and num%7==0:
print('The number is a multiple of two and seven.' )
num=int(input('Enter a number:'))
elif num%2==0:
print('The number is a multiple of two.' )
num=int(input('Enter... | [
"The question is not very clear but I think I understand what you'd like to achieve.\nYour solution is partially correct, but the \"continue\" inside the else is not followed by a new insertion of \"num\". So the input \"num\" is never changed when you insert a negative number.\nAlso the While-else clause has no se... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074181194_python.txt |
Q:
How do I split a string in a pandas dataframe and convert the remaining to datetime format?
I have a column in my pandas dataframe which has rows containing the below:
2021-01-04T23:00:00.000+00:00
I would like to split it and keep only the date element and convert the string to a date format:
04/01/2021
I have tr... | How do I split a string in a pandas dataframe and convert the remaining to datetime format? | I have a column in my pandas dataframe which has rows containing the below:
2021-01-04T23:00:00.000+00:00
I would like to split it and keep only the date element and convert the string to a date format:
04/01/2021
I have tried to use split string but I am unable to get to the final stage of then converting to a date fo... | [
"convert the date using pd.datatime and then format the date\npd.to_datetime(df['date']).dt.strftime('%d/%m/%Y')\n\n",
"Don't, split. Convert to_datetime and export to the desired format directly with strftime:\ndf['new'] = pd.to_datetime(df['col']).dt.strftime('%d/%m/%Y')\n\noutput:\n ... | [
1,
1
] | [] | [] | [
"dataframe",
"jupyter_notebook",
"pandas",
"python"
] | stackoverflow_0074181277_dataframe_jupyter_notebook_pandas_python.txt |
Q:
Multi-value insert into postgresql with python
I want to build a multi-value insert for postgresql like:
INSERT INTO mytable
VALUES
(<value a>, <value b>, …, <value x>),
(<value 1>, <value 2>, …, <value n>),
(<value A>, <value B>, …, <value Z>)
I've a dictionary with tuples.
foo = [(1, 2, 3), (4, 5,... | Multi-value insert into postgresql with python | I want to build a multi-value insert for postgresql like:
INSERT INTO mytable
VALUES
(<value a>, <value b>, …, <value x>),
(<value 1>, <value 2>, …, <value n>),
(<value A>, <value B>, …, <value Z>)
I've a dictionary with tuples.
foo = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
How can I build the "correct" insert... | [
"Use one of the fast execution helpers, which are faster than executemany.\nexecute_values:\nimport psycopg2\nfrom psycopg2.extras import execute_values\n\nwith psycopg2.connect(database='test') as conn: \n with conn.cursor() as cur: \n execute_values(cur, \"\"\"INSERT INTO t74179514 (a, b, c)... | [
0
] | [] | [] | [
"postgresql",
"python"
] | stackoverflow_0074179514_postgresql_python.txt |
Q:
How to adjust the pairplot y-axis tick format
I want the y-axis to be able to display the actual price instead of values with decimals going only up to one.
sns.pairplot(train,
x_vars=['distance_travelled(kms)', 'car_age', 'year', 'brand_rank'],
y_vars='price',
height=5,
... | How to adjust the pairplot y-axis tick format | I want the y-axis to be able to display the actual price instead of values with decimals going only up to one.
sns.pairplot(train,
x_vars=['distance_travelled(kms)', 'car_age', 'year', 'brand_rank'],
y_vars='price',
height=5,
aspect=0.7);
train is the name of the df.... | [
"I got this working by doing this\ng = sns.pairplot(train, x_vars=['distance_travelled(kms)','car_age', 'year','brand_rank'], y_vars= 'price', height= 5, aspect= 0.7);\nfor ax in g.axes.flatten():\n ax.yaxis.get_major_formatter().set_scientific(False)\n ax.yaxis.get_major_formatter().set_useOffset(False)\nplt.sho... | [
0
] | [] | [] | [
"pairplot",
"python",
"seaborn"
] | stackoverflow_0074179140_pairplot_python_seaborn.txt |
Q:
Properly iterating values inside of a for loop
I have a function that generates an appended string in a for loop from values I have saved in the variable batch_values, which is a list with ~80 string values. I then use the appended string to execute the code that is saved in the final appended string.
Like so:
par... | Properly iterating values inside of a for loop | I have a function that generates an appended string in a for loop from values I have saved in the variable batch_values, which is a list with ~80 string values. I then use the appended string to execute the code that is saved in the final appended string.
Like so:
part_to_append_1 = ''
for i in batch_values:
part_n... | [
"This won't work as written because i isn't an int, it's a value from batch_values\nThis should give you the output you were trying to get:\nnext_batch = ''\nfor i, value in enumerate(batch_values, start=1):\n part_name = value.split(\"x\")[0]\n part_value = value.split(\"y\")[1]\n part = f\"({part_name} =... | [
3,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0074181089_python.txt |
Q:
TypeError when fitting Statsmodels OLS with standard errors clustered 2 ways
Context
Building on top of How to run Panel OLS regressions with 3+ fixed-effect and errors clustering? and notably Josef's third comment, I am trying to adapt the OLS Coefficients and Standard Errors Clustered by Firm and Year section of... | TypeError when fitting Statsmodels OLS with standard errors clustered 2 ways | Context
Building on top of How to run Panel OLS regressions with 3+ fixed-effect and errors clustering? and notably Josef's third comment, I am trying to adapt the OLS Coefficients and Standard Errors Clustered by Firm and Year section of this example notebook below:
cluster_2ways_ols = sm.ols(formula='y ~ x', data=df)... | [
"I have realized that the groups must be an array of integers rather than of objects/strings.\nThus, label encoding the string column as follows:\ndf[\"country\"] = df[\"country\"].astype(\"category\")\ndf[\"country_id\"] = df.country.cat.codes\n\nand using country_id to cluster the standard errors solves the issue... | [
1
] | [] | [] | [
"linear_regression",
"panel_data",
"python",
"statsmodels"
] | stackoverflow_0074180317_linear_regression_panel_data_python_statsmodels.txt |
Q:
tkinter Username + Password in centre of the screen
Password needs to packed below username and this should be able to be done with any number of widgets
from tkinter import *
Master = Tk()
Master.attributes("-fullscreen", True)
Frame = Frame(Master)
Frame.place(relx = 0.5, rely = 0.5, anchor = "center")
Userna... | tkinter Username + Password in centre of the screen | Password needs to packed below username and this should be able to be done with any number of widgets
from tkinter import *
Master = Tk()
Master.attributes("-fullscreen", True)
Frame = Frame(Master)
Frame.place(relx = 0.5, rely = 0.5, anchor = "center")
UsernameLabel = Label(Frame, text = "Username").pack(side = "le... | [
"Is this is what you want?\nfrom tkinter import *\n\nMaster = Tk()\n#Master.attributes(\"-fullscreen\", True)\n\nFrame = Frame(Master)\nFrame.place(relx = 0.5, rely = 0.5, anchor = \"center\")\n\nemail_label = Label(Frame, text=\"Username:\")\nemail_label.pack(fill='x', expand=True)\n\nemail_entry = Entry(Frame)\ne... | [
2,
0
] | [] | [] | [
"centering",
"python",
"tkinter"
] | stackoverflow_0074089851_centering_python_tkinter.txt |
Q:
Python function sublist from input with while loop
My problem is this: Write a function, sublist, that takes in a list of numbers as the parameter. In the function, use a while loop to return a sublist of the input list. The sublist should contain the same values of the original list up until it reaches the numbe... | Python function sublist from input with while loop | My problem is this: Write a function, sublist, that takes in a list of numbers as the parameter. In the function, use a while loop to return a sublist of the input list. The sublist should contain the same values of the original list up until it reaches the number 5 (it should not contain the number 5).
I tinker wit... | [
"Try:\nimport itertools\n\ndef sublist(x):\n return list(itertools.takewhile(lambda n: n != 5, x))\n\nUpdate: If this is a homework question, my answer won't work for you - but nor should we just give you an answer, so, look at while and break. Think about creating an empty list to start with, adding things to i... | [
3,
3,
1,
0,
0,
0,
0,
0,
0
] | [
"\nnum = [1, 2, 3, 17, 1, 3, 5, 4, 3, 7, 5, 6, 9]\nnew = []\ndef check_nums(x):\n idx = 0\n while idx < len(x) and x[idx] != 7:\n print(idx)\n new.append(x[idx])\n idx += 1\n print(idx)\n return new\nprint(check_nums(num))\n\n\n",
"def sublist(a):\n i=0;\n lst=[];\n while... | [
-1,
-1
] | [
"python"
] | stackoverflow_0055889090_python.txt |
Q:
Problem with random variable elements for Web Scrapping
I'd like to create a relative function to access every game report available in this table: https://fbref.com/fr/comps/13/calendrier/Scores-et-tableaux-Ligue-1
I started making a relative URL, but there is an element in the URL that I believe to be random.
He... | Problem with random variable elements for Web Scrapping | I'd like to create a relative function to access every game report available in this table: https://fbref.com/fr/comps/13/calendrier/Scores-et-tableaux-Ligue-1
I started making a relative URL, but there is an element in the URL that I believe to be random.
Here is what I refer to:
cbdc95fe for: https://fbref.com/fr/ma... | [
"using the requests and lxml libraries (lxml for xpath) this becomes a fairly straightforward task:\n 1 import requests\n 2 from lxml import etree\n 3 \n 4 s = requests.session()\n 5 r = s.get(\"https://fbref.com/fr/comps/13/calendrier/Scores-et-tableaux-Ligue-1\")\n 6 tree = etree.HTML(r.content)\n 7 matchr... | [
0
] | [] | [] | [
"pandas",
"python",
"web_scraping"
] | stackoverflow_0074180964_pandas_python_web_scraping.txt |
Q:
Need to display city from IP address by using python
I've dataframe with name loaddata1 with column "IP_Adress" containing IP's in it and I want another column with name "city" which will display corresponding city based on Ip_adress.
Can some suggest proper code. I've used below code but its not working. Also "IP... | Need to display city from IP address by using python | I've dataframe with name loaddata1 with column "IP_Adress" containing IP's in it and I want another column with name "city" which will display corresponding city based on Ip_adress.
Can some suggest proper code. I've used below code but its not working. Also "IP_Adress" column is blank for some of record.
loaddata1 = ... | [
"You can use:\nimport geocoder\n\ndf = pd.DataFrame({'ip': ['151.101.1.69', '151.101.1.69']})\n\ndf['city'] = df['ip'].apply(lambda x: geocoder.ip(x).city)\n\nFor a faster run, you can combine it with pandarallel:\nfrom pandarallel import pandarallel\nimport geocoder\n\npandarallel.initialize()\n\ndf = pd.DataFrame... | [
0
] | [] | [] | [
"geocoder",
"pandas",
"python"
] | stackoverflow_0074181432_geocoder_pandas_python.txt |
Q:
No python at '\python.exe'
No Python at 'C:\Users\~~~~\python.exe' error keeps coming out..
Even if I deleted my previous python and path, the file location is where I installed my previous python...
I want to use python in VS code and cmd on windows 10.
What I tried to fix it
deleted python 3.7 version and reins... | No python at '\python.exe' | No Python at 'C:\Users\~~~~\python.exe' error keeps coming out..
Even if I deleted my previous python and path, the file location is where I installed my previous python...
I want to use python in VS code and cmd on windows 10.
What I tried to fix it
deleted python 3.7 version and reinstalled python 3.6 version.
remov... | [
"If you use venv, then look in that file:\npyvenv.cfg\n",
"The reason this happened to me was because I updated my python version. Therefore, the existing venv config was looking for an older python version. What I did was simply delete the existing virtual environment folder and created a new one.\nTo save all d... | [
18,
2,
0,
0
] | [
"Okay this should cover your issue. Firstly check whether it is installed \n $ $(npm config get python)\n\nor \n npm --add-python-to-path='true' --debug install --global windows-build-tool\n\nMoreover, do not forget to run your client interface as administrator.\nMore on this topic https://github.com/felixrieseberg... | [
-2
] | [
"environment_variables",
"path",
"python",
"reinstall",
"visual_studio_code"
] | stackoverflow_0056731615_environment_variables_path_python_reinstall_visual_studio_code.txt |
Q:
Get name and count of unique elements based on other column unique element
Given the following sample dataframe:
df =
Car Country
BMW Germany
Tesla USA
BMW Germany
Mercedes France
Tesla USA
Based on unique values of column Country I want to get count and naming of column Car. Desir... | Get name and count of unique elements based on other column unique element | Given the following sample dataframe:
df =
Car Country
BMW Germany
Tesla USA
BMW Germany
Mercedes France
Tesla USA
Based on unique values of column Country I want to get count and naming of column Car. Desired output:
Germany:
BMW - 2
USA:
Telsa - 2
France:
Mercedes - 1
I have tried... | [
"A classic use for groupby:\ndf.groupby([\"Country\", \"Car\"]).size()\n\n"
] | [
1
] | [] | [] | [
"pandas",
"pivot",
"pivot_table",
"python"
] | stackoverflow_0074181511_pandas_pivot_pivot_table_python.txt |
Q:
Change graph visualization with networkx
I need a clarification with the plot. Using the code below I can see my graph:
fig, ax = plt.subplots(figsize=(10, 10))
position = nx.spring_layout(DG, seed=7)
# Add nodes
nx.draw_networkx_nodes(DG, position, node_size=250, node_color='blue')
nx.draw_networkx_labels(DG, p... | Change graph visualization with networkx | I need a clarification with the plot. Using the code below I can see my graph:
fig, ax = plt.subplots(figsize=(10, 10))
position = nx.spring_layout(DG, seed=7)
# Add nodes
nx.draw_networkx_nodes(DG, position, node_size=250, node_color='blue')
nx.draw_networkx_labels(DG, position, font_size=10, font_family="sans-seri... | [
"The problem is that you are drawing the network twice, because nx.draw_circular() draws the entire network as a side effect. (That function can take a lot of arguments to control how edges, vertices, etc, are drawn, but you already have that code laid out so it's probably not the best approach.)\nInstead, you shou... | [
1
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0074170491_networkx_python.txt |
Q:
How to split column values on multiple columns with values with different lenght?
how do i split the values in the column COD into 3 columns with different length? in particular as you can see below i need one number on the first column, 2 numbers on the second and 3 on the third. Any idea?
COD CODA CODB CODC... | How to split column values on multiple columns with values with different lenght? | how do i split the values in the column COD into 3 columns with different length? in particular as you can see below i need one number on the first column, 2 numbers on the second and 3 on the third. Any idea?
COD CODA CODB CODC
140022 1 40 022
140031 1 40 031
140032 1 40 032
140033 1 40 ... | [
"As you want to keep leading zeros, you have to handle everything as strings.\nYou can use str.extract:\ndf[['CODA', 'CODB', 'CODC']] = df['COD'].astype(str).str.extract('(.)(..)(...)')\n\nIf for some reason you're not sure that the input has 6 digits (this would fill preferentially from the right):\ndf[['CODA', 'C... | [
5,
0
] | [] | [] | [
"multiple_columns",
"pandas",
"python",
"split"
] | stackoverflow_0074181351_multiple_columns_pandas_python_split.txt |
Q:
Initializing Firebase Admin via Environment Variables without storing serviceAccount.json
I am trying to initialize firebase-admin on my Flask API. Based off the documentation, the method initialize_app can take a dictionary as an input as seen here:
https://github.com/firebase/firebase-admin-python/blob/6d826fd15... | Initializing Firebase Admin via Environment Variables without storing serviceAccount.json | I am trying to initialize firebase-admin on my Flask API. Based off the documentation, the method initialize_app can take a dictionary as an input as seen here:
https://github.com/firebase/firebase-admin-python/blob/6d826fd15c87db62f7501f569b6e0a762d17a05e/firebase_admin/credentials.py#L85
That said, I structured my co... | [
"Thanks to, smac89, for pointing me in the right direction.\nThe change is very minor to make it work:\nfirebase_admin.initialize_app({ \\\n credential=credentials.Certificate({ \\ # <------- This change\n \"type\": \"service_account\", \\\n \"project_id\": os.environ.get('FIREBASE_PROJECT_ID'), \... | [
3,
0,
0
] | [] | [] | [
"firebase",
"firebase_admin",
"python"
] | stackoverflow_0071878229_firebase_firebase_admin_python.txt |
Q:
How to use phonenumbers Python library on a pandas dataframe testing phone field before?
I would to parse a phone field in a pandas dataframe. My phone field is named Phone and my country code field CountryCode.
It works but only when all the phones are filled:
df['Test phone'] = df.apply(lambda x:phonenumbers.par... | How to use phonenumbers Python library on a pandas dataframe testing phone field before? | I would to parse a phone field in a pandas dataframe. My phone field is named Phone and my country code field CountryCode.
It works but only when all the phones are filled:
df['Test phone'] = df.apply(lambda x:phonenumbers.parse(str(x['Phone']), str(x['CountryCode'])), axis='columns')
OK, but how to do it only if the ... | [
"Just use an if and else statement within your lambda and test with row.notnull().all() if all row entries are not null.\nI added an example from the phonenumbers project.\n\nimport numpy as np\nimport pandas as pd\nimport phonenumbers\n\ndf = pd.DataFrame(\n [\n [\n np.nan,\n \"020 ... | [
1,
0
] | [] | [] | [
"pandas",
"python",
"python_phonenumber"
] | stackoverflow_0074173462_pandas_python_python_phonenumber.txt |
Q:
Python Selenium 'WebDriver' object has no attribute 'switch_to_window'
My Code do what it should do until it reach the point when a button is clicked and a second PDF window opens. I try to switch to the PDF window to close it but it does not work, my Code after the button is clicked looks like:
while len(browser.... | Python Selenium 'WebDriver' object has no attribute 'switch_to_window' | My Code do what it should do until it reach the point when a button is clicked and a second PDF window opens. I try to switch to the PDF window to close it but it does not work, my Code after the button is clicked looks like:
while len(browser.window_handles) < 2:
sleep(1)
browser.switch_to_window(browser.window_h... | [
"Selenium 4 no more supports switch_to_window method.\nswitch_to.window should be used instead, as following:\nbrowser.switch_to.window(browser.window_handles[0])\n\n"
] | [
1
] | [] | [] | [
"python",
"selenium",
"selenium4",
"selenium_webdriver"
] | stackoverflow_0074181575_python_selenium_selenium4_selenium_webdriver.txt |
Q:
Error while trying to generate xml file with specific name
I tried to generate a file named, for example, 23-10-2022|21-03-11.xml or if the user enters his own name userGeneratedName23-10-2022-21-03-11.xml. I don't know why when I tried to specify a particular folder where the generated file should be saved the pr... | Error while trying to generate xml file with specific name | I tried to generate a file named, for example, 23-10-2022|21-03-11.xml or if the user enters his own name userGeneratedName23-10-2022-21-03-11.xml. I don't know why when I tried to specify a particular folder where the generated file should be saved the program throws me an Invalid argument error. I suspect that I am u... | [
"I can not use \"|\" also I had to convert filename to str.\n if not os.path.exists(\"Generated XMLs\"):\n os.makedirs(\"Generated XMLs\")\n #open file\n today = date.today()\n now = datetime.now()\n #if filename is not specified, create file with today's date and time of creation\n if file... | [
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0074177900_python_xml.txt |
Q:
TypeError: argument should be a bytes-like object or ASCII string, not 'BufferedReader'
I am trying to make a password storage system, but am currently struggling with an error from a python module ( cryptography.fernet) . I have tried googling but have come to no avail and am asking here. Does anybody know how to... | TypeError: argument should be a bytes-like object or ASCII string, not 'BufferedReader' | I am trying to make a password storage system, but am currently struggling with an error from a python module ( cryptography.fernet) . I have tried googling but have come to no avail and am asking here. Does anybody know how to fix this? ( code below )
import PGL
from cryptography.fernet import Fernet as Fn
class APM()... | [
"By the looks of it, you might want something like this. (You should maybe brush up on how classes and instance methods work.)\nfrom cryptography.fernet import Fernet\n\n\nclass APMDatabase:\n def __init__(self, keyfile_path, database_path):\n self.keyfile_path = keyfile_path\n self.database_path =... | [
1
] | [] | [] | [
"encryption",
"python",
"python_3.x"
] | stackoverflow_0074181540_encryption_python_python_3.x.txt |
Q:
Replace dot with comma using pandas on dataframe
I have a large dataframe which combines data from multiple excel (xlsx) files. The problem is every column with decimal values is seperated with a dot.I need to replace every dot with a comma. I have already tried using the replace function, but the issue some colum... | Replace dot with comma using pandas on dataframe | I have a large dataframe which combines data from multiple excel (xlsx) files. The problem is every column with decimal values is seperated with a dot.I need to replace every dot with a comma. I have already tried using the replace function, but the issue some columns also contains string values. So my question is, how... | [
"You can just use the decimal parameter of pandas. As described in the manual: pandas.read_excel\n",
"This is probably your default language setting for Office tool is US or UK where . is used a decimal denoter where as in languages like German it is a ,. If you are using Libre Office, you can go to Tools -> Lan... | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074181374_pandas_python.txt |
Q:
How to edit tensorflow dataset?
I imported CIFAR10 dataset via tensorflow_dataset.load().
This gives me <PrefetchDataset element_spec={'id': TensorSpec(shape=(), dtype=tf.string, name=None), 'image': TensorSpec(shape=(32, 32, 3), dtype=tf.uint8, name=None), 'label': TensorSpec(shape=(), dtype=tf.int64, name=None)}... | How to edit tensorflow dataset? | I imported CIFAR10 dataset via tensorflow_dataset.load().
This gives me <PrefetchDataset element_spec={'id': TensorSpec(shape=(), dtype=tf.string, name=None), 'image': TensorSpec(shape=(32, 32, 3), dtype=tf.uint8, name=None), 'label': TensorSpec(shape=(), dtype=tf.int64, name=None)}>
This dataset has an id column. I wa... | [
"Try this:\nresult = ds.map(lambda x: {\n 'image': x['image'],\n 'label': x['label']\n})\n\nresult.element_spec\n>>> <MapDataset element_spec={'image': TensorSpec(shape=(32, 32, 3), dtype=tf.uint8, name=None), 'label': TensorSpec(shape=(), dtype=tf.int64, name=None)}>\n\n",
"If you use tfds.as_numpy you can... | [
0,
0
] | [] | [] | [
"dataset",
"jax",
"python",
"tensorflow",
"tensorflow_datasets"
] | stackoverflow_0074178965_dataset_jax_python_tensorflow_tensorflow_datasets.txt |
Q:
How to handle duplicate Pandas DataFrame columns when also specifying dtype?
I am parsing some data with predefined columns, and sometimes these columns are duplicated e.g.:
df = pd.DataFrame([['A','B']], columns=['A','A'])
The above works just fine, but I want to also specify the dtype for the column e.g.
df = p... | How to handle duplicate Pandas DataFrame columns when also specifying dtype? | I am parsing some data with predefined columns, and sometimes these columns are duplicated e.g.:
df = pd.DataFrame([['A','B']], columns=['A','A'])
The above works just fine, but I want to also specify the dtype for the column e.g.
df = pd.DataFrame([['A','B']], columns=['A','A'],dtype={'A':str})
However, the above er... | [
"Your syntax is invalid, irrespective of the duplicated columns, the dtype parameter expects a single dtype.\n\ndtype dtype, default None\nData type to force. Only a single dtype is allowed. If None, infer.\n\nYou can use:\ndf = pd.DataFrame([['A','B']], columns=['A','A']).astype({'A':str})\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074181786_dataframe_pandas_python.txt |
Q:
how to verify all but selected functions from the same module were not called?
I have a simple module (no classes, just utility functions) where a function foo() calls a number of functions from the same module, like this:
def get_config(args):
...
return config_dictionary
def get_objs(args):
...
... | how to verify all but selected functions from the same module were not called? | I have a simple module (no classes, just utility functions) where a function foo() calls a number of functions from the same module, like this:
def get_config(args):
...
return config_dictionary
def get_objs(args):
...
return list_of_objects
def foo(no_run=False):
config = get_config(...)
... | [
"That's not your real code, and then it is often not describing the real problem you have here. If for example you don't expect a function is called at all, like get_objects in your case, then why begin with spy2 in the first place. expect(<module>, times=0).<fn>(...) reads better in that case, and a subsequent v... | [
0
] | [] | [] | [
"mockito",
"python"
] | stackoverflow_0074126068_mockito_python.txt |
Q:
Flask-SQLAlchemy - Grouping "one to many" Relationship results
Well i'm having a hard time figuring out how i'm going to group the relationship rows with a sum to print out as "total" on my template, perhaps i'm searching with the wrong terms.
here is my models
class Venda(db.Model):
id = db.Column(db.Integer,... | Flask-SQLAlchemy - Grouping "one to many" Relationship results | Well i'm having a hard time figuring out how i'm going to group the relationship rows with a sum to print out as "total" on my template, perhaps i'm searching with the wrong terms.
here is my models
class Venda(db.Model):
id = db.Column(db.Integer, primary_key=True)
firma = db.Column(db.Integer, db.ForeignKey('... | [
"The SQLAlchemy ORM interface has a group_by function which should cover what you need. I think the term you need to search for is ORM or object relational mapping to find these kind of solutions.\nHere's a similar answer that covers using group by.\n"
] | [
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0074181578_python_sqlalchemy.txt |
Q:
Python: Force each instance of a class to have a certain property set to the same value
I have a number of objects that share a particular property. Let's call this property "Application". At the beginning of my program, I do not know the value of Application. At startup, I will run a routine that reveals the v... | Python: Force each instance of a class to have a certain property set to the same value | I have a number of objects that share a particular property. Let's call this property "Application". At the beginning of my program, I do not know the value of Application. At startup, I will run a routine that reveals the value of Application. After this point, the value of Application will never change. It is co... | [
"You can just do this:\nclass Foo:\n application = \"\"\n\n def __init__(self):\n pass\n\n\nif __name__ == \"__main__\":\n Foo.application = \"whatever\"\n foo = Foo()\n print(foo.application) # whatever\n\nAnd if you want the inheriting classes to know application, too, you get that for free... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074181745_python.txt |
Q:
using python phonenumbers library to validate column of phone numbers
I have a list of over 100k phone numbers in an excel sheet column. I've converted them all to strings and added a '+' in front of them. If there's a missing value in a row in the phone number column, I just added '+12345678901' in that row as a ... | using python phonenumbers library to validate column of phone numbers | I have a list of over 100k phone numbers in an excel sheet column. I've converted them all to strings and added a '+' in front of them. If there's a missing value in a row in the phone number column, I just added '+12345678901' in that row as a place holder. My column is called 'Phone'.
I've imported the phonenumbers (... | [
"According to their docs:\n\nThe parse function will also fail completely (with a\nNumberParseException) on inputs that cannot be uniquely parsed, or\nthat can't possibly be phone numbers.\n\nIf you are sure that your phone numbers are correct the problem may be that you didn't specify the second argument regarding... | [
0
] | [] | [] | [
"libphonenumber",
"pandas",
"python"
] | stackoverflow_0074181704_libphonenumber_pandas_python.txt |
Q:
How to reach a specific item in the array object in python
I have npy file which seems it is a numpy.ndarray, (array of object), I want to reach the values for a specific item. How can I do it?
This picture shows a part of npy file content and for example I have to reach values for avgmotion:
data sample
A:
it s... | How to reach a specific item in the array object in python | I have npy file which seems it is a numpy.ndarray, (array of object), I want to reach the values for a specific item. How can I do it?
This picture shows a part of npy file content and for example I have to reach values for avgmotion:
data sample
| [
"it seems that the variable you're using is a dictionary.\nYou have to access to the values of the key : avgmotion by simply putting the information in variable, let's assume your dictionary's variable is name_of_dict.\n avgmotion = name_of_dict[\"avgmotion\"]\n\nAfter that you can check the shape and size of you... | [
1
] | [] | [] | [
"arrays",
"object",
"python"
] | stackoverflow_0074181781_arrays_object_python.txt |
Q:
Can I round a PANDAS dataframe column in the same line that I edit the column?
Using Python 3.9
Using PANDAS, I'm trying to convert a column from feet to meters and then round the answer to three decimals. I currently have this:
df['col_m'] = df[col_f] * 0.3048
df['col_m'] = df['col_m'].round(3)
It gets the job d... | Can I round a PANDAS dataframe column in the same line that I edit the column? | Using Python 3.9
Using PANDAS, I'm trying to convert a column from feet to meters and then round the answer to three decimals. I currently have this:
df['col_m'] = df[col_f] * 0.3048
df['col_m'] = df['col_m'].round(3)
It gets the job done but is there a more efficient way to do this? Is it possible to do both actions ... | [
"To perform it in one step, just chain the operations. Using mul in place of * makes it more convenient as you won't need parentheses (in comparison to (df[col_f] * 0.3048).round(3)):\ndf['col_m'] = df[col_f].mul(0.3048).round(3)\n\n"
] | [
1
] | [] | [] | [
"data_conversion",
"dataframe",
"pandas",
"python",
"rounding"
] | stackoverflow_0074181893_data_conversion_dataframe_pandas_python_rounding.txt |
Q:
How to loop through data-frame columns to obtain statistics
I need a way to do the following:
I want to be able to loop through each column in a data-frame that is of the dtype == object
As I am looping through each desired column, I am obtaining the following summary statistics:
The name of the attribute
The nu... | How to loop through data-frame columns to obtain statistics | I need a way to do the following:
I want to be able to loop through each column in a data-frame that is of the dtype == object
As I am looping through each desired column, I am obtaining the following summary statistics:
The name of the attribute
The number of unique values each attribute has
The most frequently occu... | [
"Try this:\ndata = []\n\n# Loop through columns of dtype `object`\nfor col in df.select_dtypes(\"object\"):\n # Do a count of each unique value in the column\n freq = df[col].value_counts()\n\n data.append({\n \"Attribute\": col,\n # The unique values are the index of the frequency count\n ... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074176134_pandas_python.txt |
Q:
How can I enable CORS in FastAPI?
I'm trying to enable CORS in this very basic FastAPI example, however it doesn't seem to be working.
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=['*']
)
@app.get('/')
de... | How can I enable CORS in FastAPI? | I'm trying to enable CORS in this very basic FastAPI example, however it doesn't seem to be working.
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=['*']
)
@app.get('/')
def read_main():
return {'message': '... | [
"you can find answer from this:fastapi cors\nthen this is a very simple code to achieve it:\n\ncreate a python file and named it main.py.\n\nadd code in this file.\n\n\nfrom fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\n\napp = FastAPI()\n\norigins = [\"*\"]\n\napp.add_middleware(\n ... | [
63,
5,
0
] | [] | [] | [
"fastapi",
"python"
] | stackoverflow_0065635346_fastapi_python.txt |
Q:
Dealing with a string that consists of only space characters
Genre = str(input(prompt))
GenreStripped = Genre.strip()
Length = len(GenreStripped)
while Length > 0:
Im trying to make a function that does not only accept ' ' spaces as an input, what are some other python functions to deal with ' ' as an in... | Dealing with a string that consists of only space characters | Genre = str(input(prompt))
GenreStripped = Genre.strip()
Length = len(GenreStripped)
while Length > 0:
Im trying to make a function that does not only accept ' ' spaces as an input, what are some other python functions to deal with ' ' as an input, because the strip() function does not strip ' '.
| [
".strip() only removes leading and trailing whitespace, not spaces in between characters. you could use .replace(\" \", \"\") instead if you wanted to remove every space\nTry running the following to get a sense of the differences between these methods:\nprint(\" test test test \".replace(\" \", \"\")) # 'testtest... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074181767_python_python_3.x.txt |
Q:
Update dictionary items with a for loop
I would like update a dictionary items in a for loop here is what I have:
>>> d = {}
>>> for i in range(0,5):
... d.update({"result": i})
>>> d
{'result': 4}
But I want d to have following items:
{'result': 0,'result': 1,'result': 2,'result': 3,'result': 4}
A:
As men... | Update dictionary items with a for loop | I would like update a dictionary items in a for loop here is what I have:
>>> d = {}
>>> for i in range(0,5):
... d.update({"result": i})
>>> d
{'result': 4}
But I want d to have following items:
{'result': 0,'result': 1,'result': 2,'result': 3,'result': 4}
| [
"As mentioned, the whole idea of dictionaries is that they have unique keys.\nWhat you can do is have 'result' as the key and a list as the value, then keep appending to the list.\n>>> d = {}\n>>> for i in range(0,5):\n... d.setdefault('result', [])\n... d['result'].append(i)\n>>> d\n{'result': [0, 1, 2, ... | [
7,
3,
1,
1,
0
] | [
">>> d = {\"result\": []}\n>>> for i in range(0,5):\n... d[\"result\"].append(i)\n... \n>>> d\n{'result': [0, 1, 2, 3, 4]}\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0031069955_python.txt |
Q:
Install TA-lib issue
I know there are lots of issues about installing ta-lib. I tried some but not working. Example i tried :
https://www.youtube.com/watch?v=hZIZMMcTQ8c&ab_channel=MartinMayer
https://pypi.org/project/TA-Lib/
For the first, i have this environment :
Python 3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021... | Install TA-lib issue | I know there are lots of issues about installing ta-lib. I tried some but not working. Example i tried :
https://www.youtube.com/watch?v=hZIZMMcTQ8c&ab_channel=MartinMayer
https://pypi.org/project/TA-Lib/
For the first, i have this environment :
Python 3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021, 18:08:50) [MSC v.1929 64... | [
"pip3 install wheel\n\nThen you need to download relevant TA-Lib districution from here https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib, probably TA_Lib‑0.4.24‑cp39‑cp39‑win_amd64.whl,\nthen\npip3 install TA_Lib‑0.4.24‑cp39‑cp39‑win_amd64.whl\n\n",
"Solution for MAC OS\n\nInstall Homebrew from APP STORE\nResta... | [
2,
0
] | [] | [] | [
"python",
"ta_lib"
] | stackoverflow_0070493962_python_ta_lib.txt |
Q:
How to run multiple commands in python os.system?
I tried to run this command by os.system, this command should run a virtual environment first then, it will run the Django server:
import os
os.system('''
.\\match_pyinstaller\match_project\\venv\\Scripts\\activate
python .\match_pyinstaller\match_project\manage.p... | How to run multiple commands in python os.system? | I tried to run this command by os.system, this command should run a virtual environment first then, it will run the Django server:
import os
os.system('''
.\\match_pyinstaller\match_project\\venv\\Scripts\\activate
python .\match_pyinstaller\match_project\manage.py runserver
''')
what is happening is that the comman... | [
"Command:\nos.system('Echo \"Hi There, you can use an && or : (in linux) to perform multiple commands in os.system() method as i did here\" && dir')\nResult:\n\"Hi There, you can use an && or : (in linux) to perform multiple commands in os.system() method as i did here\"\nVolume in drive C has no label.\nVolume Ser... | [
0
] | [] | [] | [
"django",
"os.system",
"python"
] | stackoverflow_0074181934_django_os.system_python.txt |
Q:
Pandas DataFrame: concat instead of append
After a Pandas-update, I get a bunch of warnings for append to be depecated. This is the code to analyze a gpx file:
import pandas as bib_pandas
gpx = mod_gpxpy.parse(open(dir_file)) # read GPX-File
gpx_points = gpx.tracks[0].segments[0].points
data_frame = bib_panda... | Pandas DataFrame: concat instead of append | After a Pandas-update, I get a bunch of warnings for append to be depecated. This is the code to analyze a gpx file:
import pandas as bib_pandas
gpx = mod_gpxpy.parse(open(dir_file)) # read GPX-File
gpx_points = gpx.tracks[0].segments[0].points
data_frame = bib_pandas.DataFrame(columns=["lon", "lat", "elev", "time... | [
"You need neither append nor concat, you can use:\nl = [{\"lon\": point.longitude, \"lat\": point.latitude,\n \"elev\": point.elevation, \"time\": point.time}\n for point in gpx_points]\n\ndata_frame = bib_pandas.DataFrame(l)\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074181992_pandas_python.txt |
Q:
Python class variable weird scope visibility rules
$ cat func.py
a = 'global'
def myfunc():
a = 'myfunc'
class myclass:
print('myclass a =', a)
# a = 'myclass'
myfunc()
$ python3.8 func.py
myclass a = myfunc
$ cat func.py
a = 'global'
def myfunc():
a = 'myfunc'
class myclass:
print('myclass ... | Python class variable weird scope visibility rules | $ cat func.py
a = 'global'
def myfunc():
a = 'myfunc'
class myclass:
print('myclass a =', a)
# a = 'myclass'
myfunc()
$ python3.8 func.py
myclass a = myfunc
$ cat func.py
a = 'global'
def myfunc():
a = 'myfunc'
class myclass:
print('myclass a =', a)
a = 'myclass'
myfunc()
$ python3.8 func.py ... | [
"4.2.2. Resolution of names\n\nClass definition blocks and arguments to exec() and eval() are special\nin the context of name resolution. A class definition is an executable\nstatement that may use and define names. These references follow the\nnormal rules for name resolution with an exception that unbound local\n... | [
0
] | [] | [] | [
"class",
"python",
"scope",
"variables",
"visibility"
] | stackoverflow_0074080131_class_python_scope_variables_visibility.txt |
Q:
How to store CNN extracted features to train a SVM classifier
Using the 2D CNN shown below to extract features from images, how I can store the extracted features in order to train an SVM to classify the features?
Model:
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(3, 150, 150)))
model.add(Activa... | How to store CNN extracted features to train a SVM classifier | Using the 2D CNN shown below to extract features from images, how I can store the extracted features in order to train an SVM to classify the features?
Model:
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(3, 150, 150)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(... | [
"You can try saving and loading them as HDF5 file format. It has several advantages over pickle. It's much faster to save and load (especially for large arrays).\nTo do so, you need to install h5py package. Example codes for saving and loading are as follows:\nFor saving:\nimport h5py\nh5f = h5py.File('your_file_na... | [
1,
0
] | [] | [] | [
"deep_learning",
"keras",
"machine_learning",
"python",
"tensorflow"
] | stackoverflow_0050359055_deep_learning_keras_machine_learning_python_tensorflow.txt |
Q:
new column(s) in a pandas dataframe based on values calculated from rest of the columns
I am struggling with figuring out how to return a conditional value to a column based on values in selected columns on same index row. see the attached picture.
I have a df where "<0" column is supposed to count the number of ... | new column(s) in a pandas dataframe based on values calculated from rest of the columns | I am struggling with figuring out how to return a conditional value to a column based on values in selected columns on same index row. see the attached picture.
I have a df where "<0" column is supposed to count the number of instances in previous 18 columns where valueas are less than 0.
I also need to count the tot... | [
"import pandas as pd\n\ndata = {\n \"1\": [420, -3, 390],\n \"2\": [50, None, 45],\n \"3\": [-2,None,4]\n}\n\n#load data into a DataFrame object:\ndf = pd.DataFrame(data)\n\nfor i in range(len(df.columns)):\n df.loc[i,\"Na_Counter\"] = df.iloc[i].isnull().sum()\n df.loc[i,\"Negative_Counter\"] = (df.... | [
1,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074181826_pandas_python.txt |
Q:
PySpark equivalent to a groupby categories in pandas?
On Pandas, we can group by a categorical series and then when aggregating, it displays all the categories, regardless it contains any records or not.
import pandas as pd
df = pd.DataFrame({"Age": [12, 20, 40, 60, 72]}, dtype=np.float64)
cuts = pd.cut(df.Age, b... | PySpark equivalent to a groupby categories in pandas? | On Pandas, we can group by a categorical series and then when aggregating, it displays all the categories, regardless it contains any records or not.
import pandas as pd
df = pd.DataFrame({"Age": [12, 20, 40, 60, 72]}, dtype=np.float64)
cuts = pd.cut(df.Age, bins=[0, 11, 30, 60])
df.Age.groupby(cuts).agg(mean="mean", ... | [
"The following is quite much, but I'm not aware of any nicer method.\nfrom pyspark.sql import functions as F\ndf = spark.createDataFrame([(12,), (20,), (40,), (60,), (72,)], ['Age'])\n\nbins = [0, 11, 30, 60]\n\nconds = F\nfor i, b in enumerate(bins[1:]):\n conds = conds.when(F.col('id') <= b, f'({bins[i]}, {b}]... | [
1
] | [] | [] | [
"apache_spark",
"group_by",
"grouping",
"pyspark",
"python"
] | stackoverflow_0074181171_apache_spark_group_by_grouping_pyspark_python.txt |
Q:
Reverse Inlines in Django Admin
I have 2 models as follows. Now I need to inline Model A on Model B's page.
models.py
class A(models.Model):
name = models.CharField(max_length=50)
class B(models.Model):
name = models.CharField(max_length=50)
a = models.ForeignKey(A)
admin.py
class A_Inline(admin.Tab... | Reverse Inlines in Django Admin | I have 2 models as follows. Now I need to inline Model A on Model B's page.
models.py
class A(models.Model):
name = models.CharField(max_length=50)
class B(models.Model):
name = models.CharField(max_length=50)
a = models.ForeignKey(A)
admin.py
class A_Inline(admin.TabularInline):
model = A
class B... | [
"No, as A needs to have a ForeignKey to B to be used as an Inline. Otherwise how would the relationship be recorded once you save the inline A?\n",
"You cannot do it as told by timmy O'Mahony. But you can make B inline in A if you want. Or maybe you can manipulate how django display it in \n\ndef unicode(self):\n... | [
1,
1,
0
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0008329856_django_django_admin_django_models_python.txt |
Q:
Download public group messages without authentiction - Telethon
Is there, at the moment, any way to download messages from a public group without phone authentication? While using a bot, I get an error:
Exception has occurred: BotMethodInvalidError
The API access for bot users is restricted. The method you tried ... | Download public group messages without authentiction - Telethon | Is there, at the moment, any way to download messages from a public group without phone authentication? While using a bot, I get an error:
Exception has occurred: BotMethodInvalidError
The API access for bot users is restricted. The method you tried to invoke cannot be executed as a bot (caused by GetHistoryRequest)
... | [
"The bot can't get the message history. Bots work with updates. You can receive new messages while your bot is connected\n@bot.on(events.NewMessage)\nasync def echo_all(event):\n print(event.message)\n\n"
] | [
0
] | [] | [] | [
"bots",
"download",
"python",
"telegram",
"telethon"
] | stackoverflow_0074181730_bots_download_python_telegram_telethon.txt |
Q:
"TypeError: 'WebDriver' object is not callable", when trying to select something from dropdown menu
I get the following error when trying to do:
Traceback (most recent call last):
File "c:\Users\seal\doc\main\main.py", line 172, in <module>
select()
File "c:\Users\seal\doc\main\main.py", line 108, in selec... | "TypeError: 'WebDriver' object is not callable", when trying to select something from dropdown menu | I get the following error when trying to do:
Traceback (most recent call last):
File "c:\Users\seal\doc\main\main.py", line 172, in <module>
select()
File "c:\Users\seal\doc\main\main.py", line 108, in select
drop = driver(By.ID, 'fulfillment_duration')
TypeError: 'WebDriver' object is not callable
driver... | [
"Instead of drop = driver(By.ID, 'fulfillment_duration')\nTry\ndrop = driver.find_element(By.ID, 'fulfillment_duration')\n\nAlso, you probably will need to introduce a delay here, so the better code will be:\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom ... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074181947_python_selenium_selenium_webdriver.txt |
Q:
Access to mssql Microsoft SQL server on docker with sqlalchemy flask
I'm trying to connect to an mssql server in a docker container using sqlalchemy and flask.
I create the docker container using the following code:
sudo docker run -e "ACCEPT_EULA=Y" -e "MSSQL_SA_PASSWORD=YourStrong_Passw0rd" -e "MSSQL_PID=Develop... | Access to mssql Microsoft SQL server on docker with sqlalchemy flask | I'm trying to connect to an mssql server in a docker container using sqlalchemy and flask.
I create the docker container using the following code:
sudo docker run -e "ACCEPT_EULA=Y" -e "MSSQL_SA_PASSWORD=YourStrong_Passw0rd" -e "MSSQL_PID=Developer" -e "MSSQL_AGENT_ENABLED=True" \
-p 1433:1433 --name sql1 --hostname... | [
"It was an issue with the connection String and the Certificates of descriptions of the ODBC Drivers 18.\nThe final connection string used to connect to the docker container running the SQL server, from the host computer running the application was:\n\"Driver={ODBC Driver 18 for SQL Server};Server=tcp:localhost,143... | [
0
] | [] | [] | [
"docker",
"flask",
"python",
"sql_server",
"sqlalchemy"
] | stackoverflow_0074151725_docker_flask_python_sql_server_sqlalchemy.txt |
Q:
camera calibration using charuco boards
I am working on camera calibration task using Charuco patterns using OpenCV, this is the first time i deals with this kind of boards but the problem that the corners_ids after interpolation step results the whole corners which is 70 corner in my case but the ids (0, 10, 20, ... | camera calibration using charuco boards | I am working on camera calibration task using Charuco patterns using OpenCV, this is the first time i deals with this kind of boards but the problem that the corners_ids after interpolation step results the whole corners which is 70 corner in my case but the ids (0, 10, 20, 30, 40, 50, 60) aren't accurate, i don't know... | [
"I assume you used the last version of opencv (4.6.0.66), in which it seems interpolateCornersCharuco is not rendering correct results. Uninstalling and reverting to 4.1.2.30 made it work for me :\npython3 -m pip install opencv-python==4.1.2.30\npython3 -m pip install opencv-contrib-python==4.1.2.30\npython3 -m pip... | [
0
] | [] | [] | [
"aruco",
"camera_calibration",
"opencv",
"python"
] | stackoverflow_0072794462_aruco_camera_calibration_opencv_python.txt |
Q:
code 400, message Bad request syntax ('\x88\x80\xa32\xc9\x98')
noVNC websocket log shows above message on an authentication event. The authentication is always failing and noVNC is reporting subject error.
Some times the error comes as
code 400, message Bad HTTP/0.9 request type ('\x88\x8fR\x80\x19\x98QhM\xf9')
Is... | code 400, message Bad request syntax ('\x88\x80\xa32\xc9\x98') | noVNC websocket log shows above message on an authentication event. The authentication is always failing and noVNC is reporting subject error.
Some times the error comes as
code 400, message Bad HTTP/0.9 request type ('\x88\x8fR\x80\x19\x98QhM\xf9')
Is ('\x88\x80\xa32\xc9\x98') an ASCII or UTF-8 ? How to read and under... | [
"It seems this was a bug on websockify's side. It is fixed now, but they didn't make a release that includes the fix, so you have to use the master branch if you want to benefit from it. \nAlternatively, you could just add the relevant line from that pull request to the file websockify/websocket.py.\n",
"For thos... | [
1,
0
] | [] | [] | [
"novnc",
"python",
"websocket"
] | stackoverflow_0034091337_novnc_python_websocket.txt |
Q:
'function' object has no attribute 'event' Eror discord bot python
i have a error on line 8 'function' object has no attribute 'event' i cant fix it
from http import client
from multiprocessing.connection import Client
import discord
import random
client = discord.Client(intents=discord.Intents.default())
@Clie... | 'function' object has no attribute 'event' Eror discord bot python | i have a error on line 8 'function' object has no attribute 'event' i cant fix it
from http import client
from multiprocessing.connection import Client
import discord
import random
client = discord.Client(intents=discord.Intents.default())
@Client.event
async def FunctionName():
print('vezi ca sunt on{0.user}'.for... | [
"Your Discord client variable is named client with a small c, but your decorator uses Client with a big C. The decorator should be registered to your Discord client instance.\nClient (big C) refers to your import (from multiprocessing.connection import Client) instead of your Discord client.\n@client.event # Your ... | [
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074178712_discord.py_python.txt |
Q:
How can I copy one collection from MongoDB using pymongo and paste to another empty collection?
I want to copy full collection (e.g. name 'home').
Then do some changes in the 'home' collection or remove doc inside it (not a collection).
And then replace changed 'home' collection to its default state from item 1.
... | How can I copy one collection from MongoDB using pymongo and paste to another empty collection? |
I want to copy full collection (e.g. name 'home').
Then do some changes in the 'home' collection or remove doc inside it (not a collection).
And then replace changed 'home' collection to its default state from item 1.
I do next:
db = client["database"]
home = db['home'].find() # get collection.
db['home'].remove({}... | [
"The problem with your code example is that find() returns a database cursor to the collection, not all documents in the collection. So when you remove all documents from the home collection, the cursor will also point to an empty collection. \nIn order to copy a collection to another collection in the same server,... | [
21,
8,
0
] | [] | [] | [
"mongodb",
"pymongo",
"python"
] | stackoverflow_0039788664_mongodb_pymongo_python.txt |
Q:
How to check if data's of two files are matching by checking column wise?
I have two files for eg input.txt and output.txt.
input.txt
000000008b8c5200 bcbiubcbueqihd167
0000000056fb2620 akbhjgbfre34168gf
0000000045ab4630 jbshjdb7usvyysdu8
00000000672fa001 jhwdggdiuqwhuhius
output.txt
00000000af16380f avhdhjwqdjdk... | How to check if data's of two files are matching by checking column wise? | I have two files for eg input.txt and output.txt.
input.txt
000000008b8c5200 bcbiubcbueqihd167
0000000056fb2620 akbhjgbfre34168gf
0000000045ab4630 jbshjdb7usvyysdu8
00000000672fa001 jhwdggdiuqwhuhius
output.txt
00000000af16380f avhdhjwqdjdkjdnxk
0000000056fb2620 akbhjgbfre34168gf
0000000045ab4630 jbshjdb7usvyysdu8
000... | [
"Based on the information provided, here is what I came up with:\nCode has been commented for further explanation:\n# ------------------------------------------------------\n# IMPORT the text files\n# ------------------------------------------------------\nfile_1 = None\nfile_2 = None\nwith open(\"input.txt\") as f... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074181162_python.txt |
Q:
How to incorporate a variable in code as a string (in the context of a for-loop)
Is there a way to express the code below with a for loop?
def get_data(self):
global num_of_labels
num_of_labels = num_of_labels + 1
print(num_of_labels)
if num_of_labels == 1:
user_input = (self.root.get_scree... | How to incorporate a variable in code as a string (in the context of a for-loop) | Is there a way to express the code below with a for loop?
def get_data(self):
global num_of_labels
num_of_labels = num_of_labels + 1
print(num_of_labels)
if num_of_labels == 1:
user_input = (self.root.get_screen("to_do_view").ids.data.text)
self.root.get_screen("to_do_view").ids.label_id... | [
"You can use getattr for this:\n for i in range(3)\n user_input = (self.root.get_screen(\"to_do_view\").ids.data.text)\n ids = self.root.get_screen(\"to_do_view\").ids\n getattr(ids, f\"label_id{i}\").text = user_input\n self.root.get_screen(\"to_do_view\").ids.data.text = ''\n\n",
... | [
0,
0
] | [] | [] | [
"kivy",
"kivy_language",
"kivymd",
"python"
] | stackoverflow_0074182023_kivy_kivy_language_kivymd_python.txt |
Q:
Circular shift of vector (equivalent to numpy.roll)
I have a vector:
a <- c(1,2,3,4,5)
And I'd like to do something like:
b <- roll(a, 2) # 4,5,1,2,3
Is there a function like that in R? I've been googling around, but "R Roll" mostly gives me pages about Spanish pronunciation.
A:
How about using head and tail.... | Circular shift of vector (equivalent to numpy.roll) | I have a vector:
a <- c(1,2,3,4,5)
And I'd like to do something like:
b <- roll(a, 2) # 4,5,1,2,3
Is there a function like that in R? I've been googling around, but "R Roll" mostly gives me pages about Spanish pronunciation.
| [
"How about using head and tail...\nroll <- function( x , n ){\n if( n == 0 )\n return( x )\n c( tail(x,n) , head(x,-n) )\n}\n\nroll(1:5,2)\n#[1] 4 5 1 2 3\n\n# For the situation where you supply 0 [ this would be kinda silly! :) ]\nroll(1:5,0)\n#[1] 1 2 3 4 5\n\nOne cool thing about using head and tail... you... | [
29,
25,
5,
3,
3,
1,
0
] | [] | [] | [
"numpy",
"python",
"r"
] | stackoverflow_0018791212_numpy_python_r.txt |
Q:
How would I sort averages by row and/or column of an array?
I've been having trouble with finding the average of an array of lists, specifically by row and by column. I know what I want to do with it, but I'm struggling with finding what kind of code to write for it. The array is as follows:
data = [[126, 91, 43],... | How would I sort averages by row and/or column of an array? | I've been having trouble with finding the average of an array of lists, specifically by row and by column. I know what I want to do with it, but I'm struggling with finding what kind of code to write for it. The array is as follows:
data = [[126, 91, 43],
[534, 59, 148],
[53, 78, 1],
[725, 727, 729],
[0, 12, 0],
[64, 2... | [
"import statistics\n\ndata = [\n [126, 91, 43],\n [534, 59, 148],\n [53, 78, 1],\n [725, 727, 729],\n [0, 12, 0],\n [64, 23, 3],\n]\n\nrow_average = [statistics.fmean(x) for x in data]\nprint(row_average) # [86.66666666666667, 247.0, 44.0, 727.0, 4.0, 30.0]\ncolumn_average = [statistics.fmean(x) ... | [
2,
2,
2,
0
] | [] | [] | [
"arrays",
"average",
"mean",
"python",
"python_3.x"
] | stackoverflow_0074182071_arrays_average_mean_python_python_3.x.txt |
Q:
Finding the IP address of the docker container
I have set up a fast-api docker container. I need to communicate with fast-api present in my docker container running locally through http requests, however I am not able to determine the IP address in which my fast-api docker container is running. My dockerfile is:
F... | Finding the IP address of the docker container | I have set up a fast-api docker container. I need to communicate with fast-api present in my docker container running locally through http requests, however I am not able to determine the IP address in which my fast-api docker container is running. My dockerfile is:
FROM jhonatans01/python-dlib-opencv
COPY . .
RUN pip3... | [
"Here is what worked for me to find IP address of the container:\ndocker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' your_container_id\n",
"docker exec <container_id> sh -c \"hostname --ip-address\"\n\n"
] | [
3,
0
] | [
"While running the application with docker run, you can pass an option called --network host. This will run your application on 127.0.0.1\nYou will not need the container IP to access your application\nBut, if you want to know the container IP in any case\nyou can do\ndocker ps \n// to list all the docker container... | [
-1
] | [
"docker",
"docker_networking",
"dockerfile",
"fastapi",
"python"
] | stackoverflow_0073343176_docker_docker_networking_dockerfile_fastapi_python.txt |
Q:
Update pandas cell in one dataframe from looked up value in second dataframe
Update pandas cell in one Dataframe from looked up value in second Dataframe
I have a case where I need to update a cell in one Dataframe, 'Stock', which holds records of stock on-hand, looking up its value in a second Dataframe, 'Items',... | Update pandas cell in one dataframe from looked up value in second dataframe | Update pandas cell in one Dataframe from looked up value in second Dataframe
I have a case where I need to update a cell in one Dataframe, 'Stock', which holds records of stock on-hand, looking up its value in a second Dataframe, 'Items', which is the table of all items. This is a simplified example of the Dataframes w... | [
"You can use:\n# keep max item_no per model_no\n# convert to mapping Series\nmapper = (items.sort_values(by='item_no')\n .drop_duplicates(subset='model_no', keep='last')\n .set_index('model_no')['item_no']\n )\n\n# identify rows with model_no\nm = stock['item_no'].isin(mapper.ind... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074182299_dataframe_pandas_python.txt |
Q:
Algorithm for computing all boolean combination DataFrame, with | and & expressions included
I have a DataFrame which contains a few thousand columns with tens of thousand of rows (the amount of rows I would like to increase later). All the values in the DataFrame are Boolean.
import numpy as np
import pandas as p... | Algorithm for computing all boolean combination DataFrame, with | and & expressions included | I have a DataFrame which contains a few thousand columns with tens of thousand of rows (the amount of rows I would like to increase later). All the values in the DataFrame are Boolean.
import numpy as np
import pandas as pd
column_amount = 6 # ambigue example value
row_amount = 10 # ambigue example value
df = pd.DataF... | [
"I have come up with a greedy solution that is acceptable for my use case. Just in case someone comes across a problem alike, maybe this might help you:\n\"\"\"\nSort all columns by reward_values\nMake all combinations of 2 columns and add to dataframe, if satisfies given rules\nRepeat until a full trial doesn't ad... | [
0
] | [] | [] | [
"algorithm",
"boolean",
"pandas",
"python",
"search"
] | stackoverflow_0074163643_algorithm_boolean_pandas_python_search.txt |
Q:
How to iterate a pandas dataframe and create new column in the same dataframe
I have dataframe as below
df = pd.DataFrame([[1,5,'Dog'],[2,6,'Dog'],[3,7,'Cat'],[4,8,'Cat']],columns=['A','B','Type'])
Index
A
B
Type
0
1
5
Dog
1
2
6
Dog
2
3
7
Cat
3
4
8
Cat
Based on the 'Type' column value, I need to apply its ow... | How to iterate a pandas dataframe and create new column in the same dataframe | I have dataframe as below
df = pd.DataFrame([[1,5,'Dog'],[2,6,'Dog'],[3,7,'Cat'],[4,8,'Cat']],columns=['A','B','Type'])
Index
A
B
Type
0
1
5
Dog
1
2
6
Dog
2
3
7
Cat
3
4
8
Cat
Based on the 'Type' column value, I need to apply its own function(for example for Dog rows, call its Dog function and get the... | [
"Hope this solves your issue. Does not seem that apply can return into multiple columns so I used a suggestion from here\ndf = pd.DataFrame([[1,5,'Dog'],[2,6,'Dog'],[3,7,'Cat'],[4,8,'Cat']],columns=['A','B','Type'])\n\ndef ext_fun(x1,x2,i):\n if i=='Dog':\n #Do some calc to find c and d value and return b... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074182285_dataframe_pandas_python.txt |
Q:
Updating run_daily time in Python Telegram Bot through users input
I have a problem, when user of the bot wants to update a time of a run_daily.
Example of the code.
def send_message_to_the_user(context):
context.bot.send_message(chat_id=CHAT_ID,text="Example of the message")
def main():
updater = Updater... | Updating run_daily time in Python Telegram Bot through users input | I have a problem, when user of the bot wants to update a time of a run_daily.
Example of the code.
def send_message_to_the_user(context):
context.bot.send_message(chat_id=CHAT_ID,text="Example of the message")
def main():
updater = Updater(API_KEY, use_context=True)
dp = updater.dispatcher
job = updat... | [
"I would suggest to just schedule a new job, then.\n\nPass a unique name to run_daily\nUse that name and JobQueue.get_jobs_by_name to get the job\nuse Job.schedule_removal to delete the job\nuse JobQueue.run_daily to schedule a new job.\n\nAlso have a look at the timerbot example, which does something similar.\n\nD... | [
0
] | [] | [] | [
"python",
"python_telegram_bot",
"telegram_bot"
] | stackoverflow_0074173050_python_python_telegram_bot_telegram_bot.txt |
Q:
Can I find an index from the minimum of one array and then use that same index to call a column from another array?
I'm trying to find the index of the minimum value of a 1D array and then find the corresponding column from a 2D array, I do this using:
find_index = np.where(min(function())
where the function crea... | Can I find an index from the minimum of one array and then use that same index to call a column from another array? | I'm trying to find the index of the minimum value of a 1D array and then find the corresponding column from a 2D array, I do this using:
find_index = np.where(min(function())
where the function creates the array in question. The array is a single column with 8 values. This seems to be working, but the problem arises w... | [
"It was almost correct, the issue being that where returns a tuple.\nYou can use:\nidx = varr.argmin(axis=0)\n\ncol = varr[:, idx]\nprint(col)\n\nFix of your code:\nfind_index = np.where(varr.min()) \nfind_column = varr2[:,find_index[0]]\n\noutput:\narray([[1],\n [2],\n [3]])\n\n",
"This should work:\... | [
0,
0
] | [] | [] | [
"arrays",
"indexing",
"numpy",
"python"
] | stackoverflow_0074182154_arrays_indexing_numpy_python.txt |
Q:
Match pattern and put following lines into data structure
I have a data feed that I download on a regular bases into a csv. It looks like this
TABLE # 196712 / 9000_
>= 10 : 0.002
>= 5 : 0.001
>= 2 : 0.0005
>= 1 : 0.0002
>= 0.5 : 0.0001
>= 0.2 : 0.0001
>= 0.1 : 0.0001
>= 0.0001 : 0.0001
TABLE # 196... | Match pattern and put following lines into data structure | I have a data feed that I download on a regular bases into a csv. It looks like this
TABLE # 196712 / 9000_
>= 10 : 0.002
>= 5 : 0.001
>= 2 : 0.0005
>= 1 : 0.0002
>= 0.5 : 0.0001
>= 0.2 : 0.0001
>= 0.1 : 0.0001
>= 0.0001 : 0.0001
TABLE # 196714 / Dark
>= 0.0001 : 5e-05
TABLE # 196715 / GBD
>= 25 : 0... | [
"Try:\ns = \"\"\"\\\nTABLE # 196712 / 9000_\n>= 10 : 0.002\n>= 5 : 0.001\n>= 2 : 0.0005\n>= 1 : 0.0002\n>= 0.5 : 0.0001\n>= 0.2 : 0.0001\n>= 0.1 : 0.0001\n>= 0.0001 : 0.0001\nTABLE # 196714 / Dark\n>= 0.0001 : 5e-05\nTABLE # 196715 / GBD\n>= 25 : 0.01\n>= 10 : 0.005\n>= 5 : 0.0025\n>= 0.1 ... | [
1,
0
] | [] | [] | [
"csv",
"dictionary",
"grep",
"list",
"python"
] | stackoverflow_0074181722_csv_dictionary_grep_list_python.txt |
Q:
Iterating pandas dictionary with if, elif, else clause for sql query execution
I'm using pandas dictionary in order to execute multiple sql statements.
Example dictionary:
my_dict = {'ETL_A': ['TABLE_001', 'TABLE_002', 'TABLE_003'],
'TEST1': ['TABLE_TEST', 'TEST001', 'SAMPLE_TEST'],
'TEST2'... | Iterating pandas dictionary with if, elif, else clause for sql query execution | I'm using pandas dictionary in order to execute multiple sql statements.
Example dictionary:
my_dict = {'ETL_A': ['TABLE_001', 'TABLE_002', 'TABLE_003'],
'TEST1': ['TABLE_TEST', 'TEST001', 'SAMPLE_TEST'],
'TEST2': ['TABLE_TEST2', 'TEST2', 'SAMPLE_TEST2'],
'MY_PRIVATE_SHEMA': ['WWW_00... | [
"If I understand it correctly, you want to make a conditional iteration over all the schemas on your dictionary.\nTo do that, I would perform the following:\ntimestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n\nmy_dict = {'ETL_A': ['TABLE_001', 'TABLE_002', 'TABLE_003'],\n 'ETL_TEST': ['TABLE_001',... | [
2
] | [] | [] | [
"pandas",
"python",
"sql"
] | stackoverflow_0074182098_pandas_python_sql.txt |
Q:
Add new colums with regex
I have a data frame and I want to create a new column of specific words that are in a particular column using pandas.
In this example:
I have a certain text and a list of words
I would like to locate those specific words in a new column.
enter image description here
import re
txt = df['t... | Add new colums with regex | I have a data frame and I want to create a new column of specific words that are in a particular column using pandas.
In this example:
I have a certain text and a list of words
I would like to locate those specific words in a new column.
enter image description here
import re
txt = df['text']
x = re.findall(("apple|ba... | [
"You could use pandas Series.str.contains to filter the df and pass the results to a new columns:\nimport pandas as pd\n\ndf = pd.DataFrame([[\"a\"], [\"applea\"], [\"bana\"], [\"bananak\"], [\"banana\"], [\"orange\"]],columns=[\"fruits\"])\ndf[\"new\"] = df[df[\"fruits\"].str.contains(pat=r\"banana|apple|orange\",... | [
3,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074182445_dataframe_pandas_python.txt |
Q:
How to create a line plot using the mean of a column and extracting year from a Date column?
Update: I've now managed to solve this. For extracting the year this is what I used,
df['year'] = pd.DatetimeIndex(df['Date']).year
this allowed me to add a new column for the year and then use that column to plot the cha... | How to create a line plot using the mean of a column and extracting year from a Date column? | Update: I've now managed to solve this. For extracting the year this is what I used,
df['year'] = pd.DatetimeIndex(df['Date']).year
this allowed me to add a new column for the year and then use that column to plot the chart.
sns.lineplot(y="Class", x="year", data=df)
plt.xlabel("Year",fontsize=20)
plt.ylabel("Success... | [
"What you are plotting is df['Class'].mean(), that of course is a fixed value. I don't know which time format you're using, but maybe you need to calculate different means for different years\nEDIT:\nYes there is:\ndf = pd.DataFrame({'Date':['2020-01-20','2019-01-20','2022-01-20','2021-01-20','2012-01-20','2013-01-... | [
0
] | [] | [] | [
"matplotlib",
"python",
"seaborn"
] | stackoverflow_0074182568_matplotlib_python_seaborn.txt |
Q:
Extract recurring subelements from XML file in Python
I have a large XML file which I am splitting into separate files.
Here's how the file looks like:
<xml>
<file id="13">
<head>
<talkid>2458</talkid>
<transcription>
<seekvideo id="645">THIS PART SHOULD BE EXTRACTED</seekvideo>
<seekvideo id... | Extract recurring subelements from XML file in Python | I have a large XML file which I am splitting into separate files.
Here's how the file looks like:
<xml>
<file id="13">
<head>
<talkid>2458</talkid>
<transcription>
<seekvideo id="645">THIS PART SHOULD BE EXTRACTED</seekvideo>
<seekvideo id="3349">THIS PART SHOULD BE EXTRACTED</seekvideo>
<se... | [
"@Olvin-Roght generously answered my question in another post. I'm going to post it here, as it may prove helpful to someone else. Here's how it worked:\nimport xml.etree.ElementTree as ET\nfrom pathlib import Path\n\ntalks = Path(r'path\\to\\talks.xml')\ncontext = ET.iterparse(all_talks, events=('start', 'end'))\n... | [
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0074182062_python_xml.txt |
Q:
Why is there no command line to find python location?
I can find python version with python --version
But I cannot find the location of python executable. Is there a command like python --path? If not, is there a reason why?
A:
Use sys.executable:
python -c 'import sys; print(sys.executable)'
A:
use 'where pyt... | Why is there no command line to find python location? | I can find python version with python --version
But I cannot find the location of python executable. Is there a command like python --path? If not, is there a reason why?
| [
"Use sys.executable:\npython -c 'import sys; print(sys.executable)'\n\n",
"use 'where python' in your terminal to get the path to it\nedit\nwhere python works for windows and which python works for linux\n",
"Use which python or which python3.\nWork on unix based OS.\nFor Windows, see other answers.\n",
"(Not... | [
3,
2,
0,
0,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0074102484_python_windows.txt |
Q:
Selenium, how do you instinatiate Opera webdriver using Python?
For firefox,chrome,safarim,edge it works smth like this:
driver_instance = webdriver.Chrome(chrome_options=chrome_options)
But I can't find information on how to do the same for the Opera web driver and apparently it's supported. I downloaded the Ope... | Selenium, how do you instinatiate Opera webdriver using Python? | For firefox,chrome,safarim,edge it works smth like this:
driver_instance = webdriver.Chrome(chrome_options=chrome_options)
But I can't find information on how to do the same for the Opera web driver and apparently it's supported. I downloaded the Opera webdriver, put it in my PATH but what command I'm supposed to run ... | [
"Download opera driver here: https://github.com/operasoftware/operachromiumdriver/releases\nAnd use like this:\noptions.binary_location = r'location_of_opera.exe'\nself.driver = webdriver.Opera(options=options, executable_path=r'location_of_operadriver.exe')\n\nExample:Example\n",
"You can use below code to initi... | [
2,
1
] | [] | [] | [
"opera",
"python",
"selenium"
] | stackoverflow_0074182090_opera_python_selenium.txt |
Q:
How can I scrap the Value of Hotel Class on Tripadvisor?
I want to scrap some Hotel data in Tripadvisor but I cant get the data from "Hotel Class". How can I do that?
Code:
import requests
from bs4 import BeautifulSoup
import re
import time
import datetime
url = 'https://www.tripadvisor.com/Hotel_Review-g60763-d93... | How can I scrap the Value of Hotel Class on Tripadvisor? | I want to scrap some Hotel data in Tripadvisor but I cant get the data from "Hotel Class". How can I do that?
Code:
import requests
from bs4 import BeautifulSoup
import re
import time
import datetime
url = 'https://www.tripadvisor.com/Hotel_Review-g60763-d93543-Reviews-The_Shelburne_Sonesta_New_York-New_York_City_New_Y... | [
"Not sure if it is the expected output, but you could scrape the value of attribute aria-label from the <svg>:\nhotel_class = soup.find('div',{'class':'euDRl _R MC S4 _a H'}).svg.get('aria-label')\n\nOutput:\n4.0 of 5 bubbles\n\n"
] | [
0
] | [] | [] | [
"html",
"python",
"web_scraping"
] | stackoverflow_0074180995_html_python_web_scraping.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.