content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How can I convert my "price" column from string to number format?
# Import required modules
import requests
from bs4 import BeautifulSoup
import time
import pandas as pd
# Get data from webpage
mystocks = ['GOOG', 'META', 'MSFT', 'PLTR', 'TSLA', 'ZS', 'PYPL', 'SHOP', 'TTCF']
def getData(symbol):
headers =... | How can I convert my "price" column from string to number format? | # Import required modules
import requests
from bs4 import BeautifulSoup
import time
import pandas as pd
# Get data from webpage
mystocks = ['GOOG', 'META', 'MSFT', 'PLTR', 'TSLA', 'ZS', 'PYPL', 'SHOP', 'TTCF']
def getData(symbol):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0;
Win64; x64) AppleWe... | [
"Do it like this.\nimport pandas as pd \nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport scipy.optimize as sco\nimport datetime as dt\nimport math\nfrom datetime import datetime, timedelta\nfrom pandas_datareader import data as wb\nfrom sklearn.cluster import KMeans\nnp.random.se... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074133034_python.txt |
Q:
Object Detection with YOLOV7 on custom dataset
I am trying to predict bounding boxes on a custom dataset using transfer learning on yolov7 pretrained model.
My dataset contains 34 scenes for training, 2 validation scenes and 5 test scenes. Nothing much happens on the scene, just the camera moves 60-70 degree aroun... | Object Detection with YOLOV7 on custom dataset | I am trying to predict bounding boxes on a custom dataset using transfer learning on yolov7 pretrained model.
My dataset contains 34 scenes for training, 2 validation scenes and 5 test scenes. Nothing much happens on the scene, just the camera moves 60-70 degree around the objects on a table/flat surface and scales/til... | [
"I would suggest you thoroughly review your dataset, to start.\n\nCheck the class distributions.\n\nHow many classes do you have, and what are the counts of the objects of these classes in the training set?\nWhat are the counts in the validation set? Are the ratios approximately similar or different?\nIs any class ... | [
1
] | [] | [] | [
"computer_vision",
"deep_learning",
"machine_learning",
"python",
"pytorch"
] | stackoverflow_0074507437_computer_vision_deep_learning_machine_learning_python_pytorch.txt |
Q:
How to render emojis in matplotlib with 'natural' colors?
I want to use emoji in a plot, which works with the correct font (Segoe UI Emoji on Windows), however I cannot figure out how to use the 'natural' colors. When rendered in a browser or MS Word, the glyphs have their own colors defined (I presume) by the fo... | How to render emojis in matplotlib with 'natural' colors? | I want to use emoji in a plot, which works with the correct font (Segoe UI Emoji on Windows), however I cannot figure out how to use the 'natural' colors. When rendered in a browser or MS Word, the glyphs have their own colors defined (I presume) by the font. In this example, they are grey and yellow. However they b... | [
"i have created a small library (imojify) to deal with colored emoji issue\nfrom imojify import imojify\nfrom matplotlib import pyplot as plt \nfrom matplotlib.offsetbox import OffsetImage,AnnotationBbox\n\ndef offset_image(cords, emoji, ax):\n\n img = plt.imread(imojify.get_img_path(emoji))\n im = OffsetImag... | [
0
] | [] | [] | [
"emoji",
"matplotlib",
"python"
] | stackoverflow_0071038093_emoji_matplotlib_python.txt |
Q:
after 13th api call yfinance will not give any earnings data
I have the following script to populate my database with yahoo finance information:
from multiprocessing import Pool
import json, time, yfinance
import django
django.setup()
from dividends_info.functions.stock_info import save_stock_info_data
from div... | after 13th api call yfinance will not give any earnings data | I have the following script to populate my database with yahoo finance information:
from multiprocessing import Pool
import json, time, yfinance
import django
django.setup()
from dividends_info.functions.stock_info import save_stock_info_data
from dividends_info.models import StockInfo
with open('tickers/nyse_ticke... | [
"Here you go.\nimport pandas_datareader as web\nimport pandas as pd\n \ndf = web.DataReader('AAPL', data_source='yahoo', start='2011-01-01', end='2021-01-12')\ndf.head()\n\nimport yfinance as yf\naapl = yf.Ticker(\"AAPL\")\naapl\n \n\n\n# show earnings\naapl.earnings\naapl.quarterly_earnings\n \n\nResult:\n ... | [
0
] | [] | [] | [
"multithreading",
"python",
"python_multiprocessing",
"yfinance"
] | stackoverflow_0073724165_multithreading_python_python_multiprocessing_yfinance.txt |
Q:
Python Pandas calculate standard deviation excluding current group, with vectorization solution
So i want to calculate standard deviation excluding current group using groupby. Here an example of the data:
import pandas as pd
df = pd.DataFrame ({
'group' : ['A','A','A','A','A','A','B','B','B'... | Python Pandas calculate standard deviation excluding current group, with vectorization solution | So i want to calculate standard deviation excluding current group using groupby. Here an example of the data:
import pandas as pd
df = pd.DataFrame ({
'group' : ['A','A','A','A','A','A','B','B','B','B','B','B'],
'team' : ['1','1','2','2','3','3','1','1','2','2','3','3',]
... | [
"You can use transform after combining group and team as a list:\ndf['std'] = (df.assign(new=df[['group', 'team']].values.tolist())['new'].transform(\n lambda x: df[df['group'].eq(x[0]) & df['team'].ne(x[1])]['value'].std())) \n\nOutput:\ngroup team value std\n0 A 1 1 2.217356\n1 A 1 2 ... | [
1
] | [] | [] | [
"pandas",
"python",
"standard_deviation",
"vectorization"
] | stackoverflow_0074508088_pandas_python_standard_deviation_vectorization.txt |
Q:
Copy previous value row if not nan based on another column if value
I have a Data Frame d1 where I would like to copy over the values of all rows in all columns when column 'C' is lower than 10k. Obtaining the result indicated on d2. This without overwriting the values of the row in case is different from Nan. On... | Copy previous value row if not nan based on another column if value | I have a Data Frame d1 where I would like to copy over the values of all rows in all columns when column 'C' is lower than 10k. Obtaining the result indicated on d2. This without overwriting the values of the row in case is different from Nan. On my example i have all values equal to '1' but on my real dataframe some ... | [
"If my understanding was correct, df2 would be seen as an unexpected result, and the expected result would be\n\nTo achieve the result shown by the above screenshot, we only need to run the below code\ndf_result = df1[df1.C < 1000]\n\nIn addition, it would be better (closer to convention) to use np.nan than nan, wi... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074508053_dataframe_pandas_python.txt |
Q:
Importing pickle file into mysql gives an error "ProgrammingError: not enough arguments for format string"
I'm trying to insert data from .pickle file into MySQL. I'm getting an error "ProgrammingError: not enough arguments for format string". As I understand, this error happens due to the count of placeholders (%... | Importing pickle file into mysql gives an error "ProgrammingError: not enough arguments for format string" | I'm trying to insert data from .pickle file into MySQL. I'm getting an error "ProgrammingError: not enough arguments for format string". As I understand, this error happens due to the count of placeholders (%s) being greater than the count of values for formating/templating. But in my case they are equal. cursor.execut... | [
"result is a DataFrame, so you could convert each row to a tuple and write the tuple to the database:\nfor t in result.itertuples():\n # We don't want the index, which is the first element.\n values = t[1:]\n cursor.execute(\"\"\"INSERT INTO directors(id, first_name, last_name) VALUES (%s,%s,%s)\"\"\", val... | [
0
] | [] | [] | [
"mysql",
"pandas",
"pickle",
"python",
"sql"
] | stackoverflow_0074503135_mysql_pandas_pickle_python_sql.txt |
Q:
Is there any way to plot emojis in matplotlib?
Does anybody know how to plot emojis in matplotlib while using windows? I've been struggling to find a solution as most out there seem to be specific for macOS.
Below is my current graph showing emojis plotted in a vector space, but as usual most do not show up.
Is t... | Is there any way to plot emojis in matplotlib? | Does anybody know how to plot emojis in matplotlib while using windows? I've been struggling to find a solution as most out there seem to be specific for macOS.
Below is my current graph showing emojis plotted in a vector space, but as usual most do not show up.
Is there perhaps any fonts already installed with matplo... | [
"This seems to work for me , but apparently depends on default fonts (eg \"Segoe UI Emoji\") being installed:\nplt.text(0,.5,' ☺️ ',fontsize=20)\n\n\n",
"i have created a small library (imojify) to deal with that issue\nfrom imojify import imojify\nfrom matplotlib import pyplot as plt \nfrom matplotlib.o... | [
1,
0
] | [] | [] | [
"emoji",
"matplotlib",
"python",
"seaborn",
"windows"
] | stackoverflow_0061701600_emoji_matplotlib_python_seaborn_windows.txt |
Q:
How to save the value entered by the user in the calculated field?
I made the computed field editable using the inverse field, but when I entering the value manually, when saving it is replaced with the value from _compute_test, how can I save the value entered manually?
My .py file:
class SaleOrderInherited(model... | How to save the value entered by the user in the calculated field? | I made the computed field editable using the inverse field, but when I entering the value manually, when saving it is replaced with the value from _compute_test, how can I save the value entered manually?
My .py file:
class SaleOrderInherited(models.Model):
_inherit = 'sale.order'
custom_field = fields.Char(s... | [
"Use store=True attribute in your field.\nYou also need to enforce your compute method logic so it doesn't always override field's value.\nforce_save attribute is used for read-only fields, which would be ignored from create and write methods instead.\n"
] | [
0
] | [] | [] | [
"odoo",
"odoo_15",
"python",
"python_3.x"
] | stackoverflow_0074507731_odoo_odoo_15_python_python_3.x.txt |
Q:
Unable to understand dictionaries behavior when simulating a linked list
I am trying to simulate linked lists in python using dictionaries - h (stands for head) and t (stands for tail):
t = {"value": 5, "next": None}
h = t
I add a new node n1 as value of the key "next" in t:
n1 = {"value": 10, "next": None}
t["ne... | Unable to understand dictionaries behavior when simulating a linked list | I am trying to simulate linked lists in python using dictionaries - h (stands for head) and t (stands for tail):
t = {"value": 5, "next": None}
h = t
I add a new node n1 as value of the key "next" in t:
n1 = {"value": 10, "next": None}
t["next"] = n1
print(t)
# {'value': 5, 'next': {'value': 10, 'next': None}}
print... | [
"\nMy understanding is that at this point h and t will start referring to different memory addresses.\n\nTrue, but h[\"next\"] and t reference the same.\nHere is a visualisation of all the actions you performed:\nt = {\"value\": 5, \"next\": None}\nh = t\n\nThe resulting state can be pictured like this:\n t h\... | [
0
] | [] | [] | [
"dictionary",
"linked_list",
"python"
] | stackoverflow_0074507361_dictionary_linked_list_python.txt |
Q:
Is there an easy way to use DBSCAN in python with dimensions higher than 2?
I've been working on a machine learning project using clustering algorithms, and I'm looking into using scikit-learn's DBSCAN implementation based on the data that I'm working with. However, whenever I try to run it with my feature arrays,... | Is there an easy way to use DBSCAN in python with dimensions higher than 2? | I've been working on a machine learning project using clustering algorithms, and I'm looking into using scikit-learn's DBSCAN implementation based on the data that I'm working with. However, whenever I try to run it with my feature arrays, it throws the following error:
ValueError: Found array with dim 3. Estimator exp... | [
"I believe the issue is with the \"min_samples\" parameter. The data you're fitting contains 3 features/dimensions but you've set \"min_samples=2\". Min_samples has to be equal to or greater than the number of features in your dataset.\n",
"I have an example of DBSCAN on my blog.\nimport statsmodels.api as sm\ni... | [
1,
0
] | [] | [] | [
"cluster_analysis",
"dbscan",
"python",
"scikit_learn"
] | stackoverflow_0061277791_cluster_analysis_dbscan_python_scikit_learn.txt |
Q:
How to write a conditional statement based on combination of two columns and a dictionary, using the dictionary for a mapping in a new column?
I am working with a pandas dataframe (the dataframe is called market_info_df):
And I have the following Python code:
market_info_df['is_and_mp'] = market_info_df['issue_st... | How to write a conditional statement based on combination of two columns and a dictionary, using the dictionary for a mapping in a new column? | I am working with a pandas dataframe (the dataframe is called market_info_df):
And I have the following Python code:
market_info_df['is_and_mp'] = market_info_df['issue_status'] + market_info_df['market_phase']
no_collision_issue_status = ['000', '200', '203', '204', '300']
MARKET_STATES_DICT = {
('000', ' '): MARK... | [
"Use apply function on dataframe. Check for the desired condition as you have written. If true then return the value from dict else return None:\nmarket_info_df[\"market_state\"] = market_info_df.apply(lambda row: MARKET_STATES_DICT[(row[\"is_and_mp\"],row[\"trading_status\"])] if row[\"is_and_mp\"] in no_collision... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074508231_dataframe_pandas_python.txt |
Q:
How can I tell what filter size to use for a certain size image?
I was developing a GAN to generate 48x48 images of faces. However, the generator makes strange images no matter how much training is done, and no matter how much the discriminator thinks it's fake. This leads me to believe that it is an architectural... | How can I tell what filter size to use for a certain size image? | I was developing a GAN to generate 48x48 images of faces. However, the generator makes strange images no matter how much training is done, and no matter how much the discriminator thinks it's fake. This leads me to believe that it is an architectural problem.
untrained output
After 25 epochs
The problem is obvious. ... | [
"Issue is caused when larger strides are introduced at the final layers\n\nConsider a 1d case:\n\ninput values = i1 | i2 | i3 \n\ntransposeConv1(k=2,s=3) \nweights (k=2) = w1 | w2 |\ninitialization = 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0\noutput =i1w1|i1w2| 0 |i... | [
1,
0,
0,
0
] | [] | [] | [
"generative_adversarial_network",
"machine_learning",
"python",
"tensorflow"
] | stackoverflow_0074257567_generative_adversarial_network_machine_learning_python_tensorflow.txt |
Q:
Appending hashes to a list for reference
I'm using the imagehash library in Python and i'm trying to compare one image to a set of images to determine if it's similar to any of them.
To avoid having to fetch the hashes every time I run the program I generated each hash and appended it to a list (one time operation... | Appending hashes to a list for reference | I'm using the imagehash library in Python and i'm trying to compare one image to a set of images to determine if it's similar to any of them.
To avoid having to fetch the hashes every time I run the program I generated each hash and appended it to a list (one time operation) however when running the program to actually... | [
"The hash value returned by the average_hash method can be converted to a hex value using the str builtin. E.g. str(hashit(img)).\nTo reverse this (for Part 2) you can use the function imagehash.hex_to_hash.\nfrom PIL import Image\nimport imagehash\nimport os\nimport time\n\ndef hashit(a):\n return((imagehash.... | [
1
] | [] | [] | [
"hash",
"imagehash",
"python"
] | stackoverflow_0074508395_hash_imagehash_python.txt |
Q:
VideoPlayer error loading video only plays sound - Warning: Removing channel layout 0x3, redundant with 2 channels
I am trying to use VideoPlayer to load a local video. The program runs fine when it is standalone (in its own file). But, when I bring it into my main program, it loads the video but only plays the so... | VideoPlayer error loading video only plays sound - Warning: Removing channel layout 0x3, redundant with 2 channels | I am trying to use VideoPlayer to load a local video. The program runs fine when it is standalone (in its own file). But, when I bring it into my main program, it loads the video but only plays the sound. I get an error (warning, to be more precise) message:
[WARNING] [ffpyplayer ] [ffpyplayer_abuffersink @ 000001e84... | [
"Your playnow() method returns the VideoPlayer widget, but that return is ignored. You must add that widget to your GUI in order to see it. Try using this version of start_play():\ndef start_play(self):\n\n v = MDApp.get_running_app().playnow()\n self.add_widget(v)\n\n"
] | [
0
] | [] | [] | [
"kivy",
"kivy_language",
"python",
"video_player"
] | stackoverflow_0074507339_kivy_kivy_language_python_video_player.txt |
Q:
How to get the highest value per category in a dataframe?
I have a dataframe called movie_df that has more than 3000 values of title, score, and rating.
Titles are unique. Scores are 0.0 - 10.0. Ratings are either PG-13, G, R, or X.
They are sorted by their rating, then ascending score.
I want to find the highest ... | How to get the highest value per category in a dataframe? | I have a dataframe called movie_df that has more than 3000 values of title, score, and rating.
Titles are unique. Scores are 0.0 - 10.0. Ratings are either PG-13, G, R, or X.
They are sorted by their rating, then ascending score.
I want to find the highest rated title per rating. The highest rated title doesn't have an... | [
"Let's try:\nmovie_df.reset_index(drop=True, inplace=True)\n\nm=max(movie_df['score'])\n\nprint(movie_df['rating'][list(movie_df['score']).index(m)])\n\n\nI think you can also use groupby() and agg()\n",
"I think your data isn't actually sorted right, that's why you're getting the wrong title but the right score.... | [
1,
0,
0,
0
] | [] | [] | [
"dataframe",
"jupyter_notebook",
"pandas",
"python"
] | stackoverflow_0074507915_dataframe_jupyter_notebook_pandas_python.txt |
Q:
checking user file if user has admin access
I am writing a very program that checks if a user is logged in with the correct username and password and also if a user has admin access . the password file is a simple text file with the columns seperated by tabs. the login part works, but I can't get the code to check... | checking user file if user has admin access | I am writing a very program that checks if a user is logged in with the correct username and password and also if a user has admin access . the password file is a simple text file with the columns seperated by tabs. the login part works, but I can't get the code to check if a user has admin access to work. if a user is... | [
"If I understand correctly what you're trying to achieve, I think your admin_user() is missing a parameter.\nAs is, you're only checking if the admin string is present once or more in your password.txt file but you don't check to which user it is associated to so the result is the same for all users.\nWhat about so... | [
0
] | [] | [] | [
"if_statement",
"python",
"return"
] | stackoverflow_0074507589_if_statement_python_return.txt |
Q:
JSON File Parsing In Python Brings Different Line In Each Execution
I am trying to analyze a large dataset from Yelp. Data is in json file format but it is too large, so script is crahsing when it tries to read all data in same time. So I decided to read line by line and concat the lines in a dataframe to have a p... | JSON File Parsing In Python Brings Different Line In Each Execution | I am trying to analyze a large dataset from Yelp. Data is in json file format but it is too large, so script is crahsing when it tries to read all data in same time. So I decided to read line by line and concat the lines in a dataframe to have a proper sample from the data.
f = open('./yelp_academic_dataset_review.json... | [
"You are using the expression f.readlines(i) several times as if it was referring to the same set of lines each time.\nBut as as side effect of evaluating the expression, more lines are actually read from the file. At one point you are basing the indices j on more lines than are actually available, because they cam... | [
1
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074508470_json_python.txt |
Q:
A way in Python to check previous values based on a condition and save them in a seperate array?
I have a list of numbers saved in an array in Python.
What i want to do is to continously check if a value in that array is lower than the all the previous ones, and then generate a number based on how many there are.
... | A way in Python to check previous values based on a condition and save them in a seperate array? | I have a list of numbers saved in an array in Python.
What i want to do is to continously check if a value in that array is lower than the all the previous ones, and then generate a number based on how many there are.
Is there a way to do this? I can't figure out how to do it. Alternative check the numbers and save all... | [] | [] | [
"create a list:\nal = [1,3,6,5,9,5,2,8,1,10,4]\n\nyour selected item(4) is at the index of : 11\nselected_item = 4\n\nindex = al.index(4) # will result as 11\n\n\nlen([al[a] for a in range(index) if al[a] > selected_item])\n\nwill give you the result you want.\n"
] | [
-2
] | [
"arrays",
"conditional_statements",
"counting",
"python"
] | stackoverflow_0074508559_arrays_conditional_statements_counting_python.txt |
Q:
How to rotate letters in a python string
Create a scrolling_text function that accepts a string as a parameter, sequentially rearranges all the characters in the string from the zero index to the last one, and returns a list with all the received combinations in upper case.
`
def scrolling_text(string: str) -> lis... | How to rotate letters in a python string | Create a scrolling_text function that accepts a string as a parameter, sequentially rearranges all the characters in the string from the zero index to the last one, and returns a list with all the received combinations in upper case.
`
def scrolling_text(string: str) -> list:
pass
`
Example`
scrolling_text("robot... | [
"The easiest way is to use slices of the string, which is an easy way of getting a subset of an sequence. In Python, str can be treated as a sequence of characters.\nThe following function would do it:\ndef scrolling_text(text: str) -> list[str]:\n ret = []\n for i in range(len(text)):\n ret.append(tex... | [
1,
0
] | [] | [] | [
"function",
"list",
"python",
"python_3.x",
"string"
] | stackoverflow_0074508580_function_list_python_python_3.x_string.txt |
Q:
read from a txt file with encoding= cp1256
I am trying to read and extract data from a file with encoding =cp1256
I can read the file and print all the information form it, but if I tried to search for something using the line.startswith it is not working
printing = False
with open(SourceFile,"r") as file:
for... | read from a txt file with encoding= cp1256 | I am trying to read and extract data from a file with encoding =cp1256
I can read the file and print all the information form it, but if I tried to search for something using the line.startswith it is not working
printing = False
with open(SourceFile,"r") as file:
for line in file:
if line.startswith("NODes... | [
"open has optional argument encoding, codecs - Standard Encodings shows table of encodings, as cp1256 is one of them it should suffice to replace\nwith open(SourceFile,\"r\") as file:\n\nusing\nwith open(SourceFile,\"r\",encoding=\"cp1256\") as file:\n\n"
] | [
2
] | [] | [] | [
"file_handling",
"python"
] | stackoverflow_0074508631_file_handling_python.txt |
Q:
combining dataframes that have the same 'country name' and same 'year'
I m trying to merge these dataframes in a way that the final data frame would have matched the country year gdp from first dataframe with its corresponding values from second data frame.
[]
[]
first data frame :
Country
Country code
year
rgdpe... | combining dataframes that have the same 'country name' and same 'year' | I m trying to merge these dataframes in a way that the final data frame would have matched the country year gdp from first dataframe with its corresponding values from second data frame.
[]
[]
first data frame :
Country
Country code
year
rgdpe
country1
Code1
year1
rgdpe1
country1
Code1
yearn
rgdpen
country2... | [
"First, from the data screen cap, it looks like the \"country\" column in your first dataset \"df_GDP\" is set as index. Reset it using \"reset_index()\". Then merge on multiple columns like left_on=[\"countries\",\"year\"] and right_on=[\"country\",\"year\"]. And since you want to retain all records from your main... | [
0
] | [] | [] | [
"data_analysis",
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074508510_data_analysis_dataframe_pandas_python_python_3.x.txt |
Q:
moving a file that contains specific element to another directory python
I have the following code that prints the element I need in all xml files i have in the directory, im trying to move the files that contains the element "drone" to another directory but i cant make it, maybe someone can help me with that?
imp... | moving a file that contains specific element to another directory python | I have the following code that prints the element I need in all xml files i have in the directory, im trying to move the files that contains the element "drone" to another directory but i cant make it, maybe someone can help me with that?
import os
import shutil
from xml.etree import ElementTree as ET
# files are in a ... | [
"The current code appears to be calling shutil.move with 2 hard-coded paths, but you should be passing the full path (fullname in your code) as the src argument instead.\nI recommend using pathlib instead of os.path functions.\nimport shutil\nfrom pathlib import Path\nfrom xml.etree import ElementTree as ET\n\n\nde... | [
0
] | [] | [] | [
"elementtree",
"python"
] | stackoverflow_0074508501_elementtree_python.txt |
Q:
ValueError: Number of labels=34866 does not match number of samples=2
I am trying to run Decision Tree Classifier but I face this problem.Please can you explain me how do I fix this Error?My English isn’t very good but I will try to understand!I'm just starting to learn the program, so please point me out if there... | ValueError: Number of labels=34866 does not match number of samples=2 | I am trying to run Decision Tree Classifier but I face this problem.Please can you explain me how do I fix this Error?My English isn’t very good but I will try to understand!I'm just starting to learn the program, so please point me out if there's anything that isn't good enough.thank you!
import matplotlib.pyplot as p... | [
"There is just a small error with:\nx=sale['年紀'],sale['單位售價']\n\nRather than selecting the columns you want, this creates a tuple of the columns, hence the end of the error message ... does not match number of samples=2\nOne way to create a new pd.DataFrame with your selected columns:\nx=sale[['年紀', '單位售價']]\n\n"
] | [
1
] | [] | [] | [
"decision_tree",
"python",
"scikit_learn"
] | stackoverflow_0074499590_decision_tree_python_scikit_learn.txt |
Q:
How do I scroll the comments in a Youtube Video? I have tired
I'm trying to build a Youtube Scraper. I've scrapped all the data I wanted from the video but I am not able to scroll all the way to the end of the comments.
I have tried the following code:
from selenium import webdriver
import time
url = "https://www... | How do I scroll the comments in a Youtube Video? I have tired | I'm trying to build a Youtube Scraper. I've scrapped all the data I wanted from the video but I am not able to scroll all the way to the end of the comments.
I have tried the following code:
from selenium import webdriver
import time
url = "https://www.youtube.com/watch?v=L8jN69GEBSw"
driver = webdriver.Chrome()
drive... | [
"Try to use selenium .scroll_by_amount function. You need to do something like this:\nfrom selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport time\n\ndriver=webdriver.Chrome()\nurl = \"https://www.youtube.com/watch?v=L8jN69GEBSw\"\ndriver.get(url)\ntime.sleep(5)\nAct... | [
0
] | [] | [] | [
"automation",
"python",
"selenium",
"selenium_webdriver",
"web_scraping"
] | stackoverflow_0074508552_automation_python_selenium_selenium_webdriver_web_scraping.txt |
Q:
3 Patterns in one for x in range(y) loop without list comprehension
Instead of using 3 loops separately, I'd like to use only one loop and speed up the code.
There are 3 different patterns of range(0,150), increasing 3 per loop:
0,3,6,9...
1,4,7,10...
2,5,8,11....
My code:
fromlist = [1,2,3,4,5]
req1list = ['z','... | 3 Patterns in one for x in range(y) loop without list comprehension | Instead of using 3 loops separately, I'd like to use only one loop and speed up the code.
There are 3 different patterns of range(0,150), increasing 3 per loop:
0,3,6,9...
1,4,7,10...
2,5,8,11....
My code:
fromlist = [1,2,3,4,5]
req1list = ['z','t','y']
req2list = [21,39,52]
req3list = [100,200,300]
for i in range(0,... | [
"Instead of trying to perform three appends in each iteration (in one loop), you'll get faster results if you call extend instead of append. You could also use slicing to avoid comprehension:\nreq1list.extend(fromlist[::3])\nreq2list.extend(fromlist[1::3])\nreq3list.extend(fromlist[2::3])\n\nAnd if it is important ... | [
2,
0
] | [] | [] | [
"loops",
"python",
"range"
] | stackoverflow_0074508464_loops_python_range.txt |
Q:
What does this error TypeError: 'Button' object is not callable mean?
This is my first time coding in tkinter. When I try to create a new button in the function 'Registering' i keep getting the same error 'Button' object is not callable. I don't understand what this error is suggesting about the simple code I hav... | What does this error TypeError: 'Button' object is not callable mean? | This is my first time coding in tkinter. When I try to create a new button in the function 'Registering' i keep getting the same error 'Button' object is not callable. I don't understand what this error is suggesting about the simple code I have written. Can anyone clarify this for me in the context of the code below?... | [
"Button = Button(root,text= \"Enter\",command=Registering)\nButton.pack()\n\nBy doing Button = Button (... you override tkinter's definition of Button.\nUse a different (hopefully more meaningful) name:\nregister_button = Button(root,text= \"Enter\",command=Registering)\nregister_button.pack()\n\n",
"the reason i... | [
11,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0052739334_python_tkinter.txt |
Q:
How to ignore certain rows while looping over pandas dataframe using iterrows
i am trying to loop over a pandas dataframe using iterrows. However, if i reach a certain predetermined row, i was to just skip over that row and now perform the next calculations and just continue to the next row. However, i am very uns... | How to ignore certain rows while looping over pandas dataframe using iterrows | i am trying to loop over a pandas dataframe using iterrows. However, if i reach a certain predetermined row, i was to just skip over that row and now perform the next calculations and just continue to the next row. However, i am very unsure on how to do so.
This is what i've trie so far.
dish_one = unimp_features.iloc[... | [
"I had to use a Series function called Series.equals(Series)\nSo end result is:\nfor index, row in unimp_features.iterrows():\n if row.equals(dish_one) | row.equals(dish_two) | row.equals(dish_three):\n continue\n else:\n df_unimportant.loc[index, 'cos_one'] = 1 - spatial.distance.cosine(dish_on... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074508664_pandas_python.txt |
Q:
How to get all combinations from array python
How to create all possible combinations from the elements of the array of certain length
For instance
N = 6 (length)
arr = ['11'] (mean 11 are adjacent)
Output:
110000
011000
001100
000110
000011
100001
If arr = ['1','1'] (mean, 11 couldn't be adjacent)
N = 6 (length)... | How to get all combinations from array python | How to create all possible combinations from the elements of the array of certain length
For instance
N = 6 (length)
arr = ['11'] (mean 11 are adjacent)
Output:
110000
011000
001100
000110
000011
100001
If arr = ['1','1'] (mean, 11 couldn't be adjacent)
N = 6 (length)
Output:
101000
100100
100010
010100
010010
010001
... | [
"please test\n\ncheck = []\ncheck2 = []\nfor x in range(5):\n arr = [0, 0, 0, 0, 0, 0]\n list_of_one_poz = []\n arr[x] = 1\n for y in range(x, 5):\n list_of_one_poz.append(y+1)\n\n for i in list_of_one_poz:\n arr[i] = 1\n txt = ''.join(str(e) for e in arr)\n r_index = txt.... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074508300_python.txt |
Q:
Tkinter: how to set a buttons position relative to the screen
from tkinter import *
Window = Tk()
Window.attributes('-fullscreen', True)
b1 = Button(Window, text="1", activeforeground="black", activebackground="gray", pady=2,
font='secular_one', relief=GROOVE)
b1.place(x=1100, y=50)
b2 = Button(Wind... | Tkinter: how to set a buttons position relative to the screen | from tkinter import *
Window = Tk()
Window.attributes('-fullscreen', True)
b1 = Button(Window, text="1", activeforeground="black", activebackground="gray", pady=2,
font='secular_one', relief=GROOVE)
b1.place(x=1100, y=50)
b2 = Button(Window, text="2", activeforeground="black", activebackground="gray", pa... | [
"The kwargs xand y for place define the widget absolute position in pixels. So if you run the program on a display with a different resolution, it won't look the same.\nTry to define relative positions instead:\nb1.place(relx=0.3, rely=0.1)\n\n"
] | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074508853_python_tkinter.txt |
Q:
How to delete property?
class C():
@property
def x(self):
return 0
delattr(C(), 'x')
>>> AttributeError: can't delete attribute
I'm aware del C.x works, but this deletes the class's property; can a class instance's property be deleted?
A:
Refer to this answer; TL;DR, it's not about properties,... | How to delete property? | class C():
@property
def x(self):
return 0
delattr(C(), 'x')
>>> AttributeError: can't delete attribute
I'm aware del C.x works, but this deletes the class's property; can a class instance's property be deleted?
| [
"Refer to this answer; TL;DR, it's not about properties, but bound attributes, and x is bound to the class, not the instance, so it cannot be deleted from an instance when an instance doesn't have it in the first place. Demo:\nclass C():\n pass\n\n@property\ndef y(self):\n return 1\n\nc = C()\nc.y = y\ndel c.... | [
2,
1,
0
] | [
"You can do something like this to delete attr from instance.\nhttps://stackoverflow.com/a/36931502/12789671\nclass C:\n def __init__(self):\n self._x: int = 0\n @property\n def x(self):\n return self._x\n @x.deleter\n def x(self):\n delattr(self, \"_x\")\n\nobj = C()\ndelattr(ob... | [
-1
] | [
"python",
"python_3.x"
] | stackoverflow_0062384952_python_python_3.x.txt |
Q:
Pycharm: import Serial is NOT working but i already did "pip3 install pyserial"
i am quite trouble why my pycharm does not recognize import serial. i am doing python code but i need to use Serial. so just from what i found:
i need to go to CMD, then enter "pip install pyserial" or "pip3 install pyserial"(this is ... | Pycharm: import Serial is NOT working but i already did "pip3 install pyserial" | i am quite trouble why my pycharm does not recognize import serial. i am doing python code but i need to use Serial. so just from what i found:
i need to go to CMD, then enter "pip install pyserial" or "pip3 install pyserial"(this is what i did).
after that the installation seems successful, i didnt see any errors
aft... | [
"Just open the terminal within the Pycharm IDE and use pip to install on there.\n",
"Try uninstalling it from pip and then using the Python Packages tab to install it. It worked for me when I tried that.\n"
] | [
0,
0
] | [
"I had the same problem since I started using python 3.10.\nI found that you have to download the complete pyserial package from github, unzip the entire package and edit the setup.py file and add the line 'Programming Language :: Python :: 3.10',\nand then from the CMD window run python setup.py build\nWith that i... | [
-1
] | [
"pip",
"pycharm",
"pyserial",
"python"
] | stackoverflow_0069833807_pip_pycharm_pyserial_python.txt |
Q:
An Issue with Cogs (discord.py)
Alright so I had some code that was working perfectly without cogs. I created two uses for my bot then decided it was time to start using cogs so that is what I did. The first of my first of my uses was a reaction role maker. So I copied the code and put it in a cog and changed all ... | An Issue with Cogs (discord.py) | Alright so I had some code that was working perfectly without cogs. I created two uses for my bot then decided it was time to start using cogs so that is what I did. The first of my first of my uses was a reaction role maker. So I copied the code and put it in a cog and changed all of the things that I knew that I had ... | [
"Change this:\n@commands.command()\n\nto this:\n@app_commands.command()\n\nthe decorator has an other name inside a cog.\n"
] | [
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074499735_discord_discord.py_python.txt |
Q:
Python venv not installing packages under my virtual environment
I have created and activated a virtual environment with Python on my Linux installation (On my AWS EC2 instance). It says it's using the correct python interpreter when I run which python3. But nonetheless when I run python3 -m pip install <package> ... | Python venv not installing packages under my virtual environment | I have created and activated a virtual environment with Python on my Linux installation (On my AWS EC2 instance). It says it's using the correct python interpreter when I run which python3. But nonetheless when I run python3 -m pip install <package> it's not there when I run pip freeze. It keeps installing to my global... | [
"Why run 'which python' then run python3? ... Try 'which python3' (even better, run 'type python3' because it could be an alias that bypasses your venv)\n",
"Delete Your actual virtual environment. And try again by following the python doc\n"
] | [
0,
0
] | [] | [] | [
"linux",
"pip",
"python",
"python_venv"
] | stackoverflow_0067915022_linux_pip_python_python_venv.txt |
Q:
How to reduce ticks?
I have 250 rows of data, it starts january 2002 and ends septemper 2022 and interwal per row is one row/one month of the year.
Now i want to plot it but it takes all 250 rows and plot it and i only want like one year shown per tick
The y axis is float and x axis is string
I have saw that you ... | How to reduce ticks? | I have 250 rows of data, it starts january 2002 and ends septemper 2022 and interwal per row is one row/one month of the year.
Now i want to plot it but it takes all 250 rows and plot it and i only want like one year shown per tick
The y axis is float and x axis is string
I have saw that you have to label them manualy... | [
"I believe if you used xticks you'll be fine\nhttps://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.xticks.html\nplt.xticks([0, 365, 730], ['2001', '2002', '2003'],rotation=0)\n\nAn approach like this one is what I propose, you can always customize and/or make it automatic.\nedit: I assumed that you have data... | [
0,
0
] | [] | [] | [
"matplotlib",
"plot",
"python"
] | stackoverflow_0074508859_matplotlib_plot_python.txt |
Q:
remove same combinations in dataframe pandas
I have a dataframe that is a edgelist for a undirected graph it looks like this:
node 1 node 2 doc
0 Kn Kn doc5477
1 TS Kn doc5477
2 Kn TS doc5477
3 TS TS doc5477
4 Kn Kn doc10967
5 Kn TS doc10967
6 TS TS doc10967
7 TS Kn doc10967... | remove same combinations in dataframe pandas | I have a dataframe that is a edgelist for a undirected graph it looks like this:
node 1 node 2 doc
0 Kn Kn doc5477
1 TS Kn doc5477
2 Kn TS doc5477
3 TS TS doc5477
4 Kn Kn doc10967
5 Kn TS doc10967
6 TS TS doc10967
7 TS Kn doc10967
How can I make sure that the combinations of... | [
"First, select the columns on which you need a unique combination (node1, node2 and doc in your case) then apply a sort to return a series with a list of combinations, and finally use a boolean mask with a negative pandas.DataFrame.duplicated to keep only the rows that represent a unique combination.\nTry this:\nou... | [
2
] | [] | [] | [
"graph",
"pandas",
"python"
] | stackoverflow_0074508880_graph_pandas_python.txt |
Q:
Bot wont join in "join" slash command discord.py V2.0
I need to update some old code to use slash commands and in the old code I have a join command that just makes the bot join the current voice channel. I have done some research but all I could find was just older tutorials on how you did a join command with the... | Bot wont join in "join" slash command discord.py V2.0 | I need to update some old code to use slash commands and in the old code I have a join command that just makes the bot join the current voice channel. I have done some research but all I could find was just older tutorials on how you did a join command with the old prefix and ctx. The solution I am seeking is a little ... | [
"It as pretty much the same for slash commands as compared to normal command, you use theinteraction object instead of ctx.\n@app_commands.command()\n async def join(self, interaction: discord.Interaction):\n channel = interaction.user.voice.channel\n await channel.connect()\n\n"
] | [
1
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074507334_discord_discord.py_python.txt |
Q:
How to validate list items when they change in a pydantic model?
I have a List in a pydantic model. I'd like my custom validator to run when the list changes (not only on assignment).
from typing import List
from pydantic import BaseModel, validator
class A(BaseModel):
b: List[int] = []
class Config:
... | How to validate list items when they change in a pydantic model? | I have a List in a pydantic model. I'd like my custom validator to run when the list changes (not only on assignment).
from typing import List
from pydantic import BaseModel, validator
class A(BaseModel):
b: List[int] = []
class Config:
validate_assignment = True
@validator("b")
def positive(... | [
"from pydantic import BaseModel, validator\nfrom typing import List\n\n\nclass PositiveIntList(BaseModel):\n __root__: List[int] = []\n\n def append(self, value: int) -> None:\n self.__root__.append(value)\n super().__init__(__root__=self.__root__)\n\n def __getitem__(self, item: int) -> int:... | [
2,
0
] | [] | [] | [
"pydantic",
"python",
"validation"
] | stackoverflow_0067748856_pydantic_python_validation.txt |
Q:
What's the difference between FastAPI background tasks and Celery tasks?
Recently I read something about this and the point was that celery is more productive.
Now, I can't find detailed information about the difference between these two and what should be the best way to use them.
A:
Straight from the documenta... | What's the difference between FastAPI background tasks and Celery tasks? | Recently I read something about this and the point was that celery is more productive.
Now, I can't find detailed information about the difference between these two and what should be the best way to use them.
| [
"Straight from the documentation:\n\nIf you need to perform heavy background computation and you don't\nnecessarily need it to be run by the same process (for example, you\ndon't need to share memory, variables, etc), you might benefit from\nusing other bigger tools like Celery.\nThey tend to require more complex c... | [
1
] | [] | [] | [
"background_task",
"celery",
"fastapi",
"python",
"scheduled_tasks"
] | stackoverflow_0074508774_background_task_celery_fastapi_python_scheduled_tasks.txt |
Q:
How to efficiently store and render orbits in pygame
I followed a tutorial by TechWithTimn youtube and completed this solar system project in pygame. I have a lot of plans to further expand it and I succeeded in many. But when I add more planets and leave the program for some minutes, the fps rate drops and eventu... | How to efficiently store and render orbits in pygame | I followed a tutorial by TechWithTimn youtube and completed this solar system project in pygame. I have a lot of plans to further expand it and I succeeded in many. But when I add more planets and leave the program for some minutes, the fps rate drops and eventually the program crashes due to lack of memory. I figured ... | [
"I solved your problem very easily. I added only these two lines to end of update_position function, which deletes first dot from array, when the circle is full.\nif len(self.orbit) > 720:\n del self.orbit[0]\n\nNumber 720 is the max length of self.orbit array for the most distant planet. You can change this num... | [
1
] | [] | [] | [
"memory_efficient",
"performance",
"pygame",
"python"
] | stackoverflow_0074508653_memory_efficient_performance_pygame_python.txt |
Q:
python - collect full path till leaf on organization tree
I got organizations tree stored as json
{
"name": "amos",
"direct_reports": [
{
"name": "bart",
"direct_reports": [
{
"name": "colin",
"direct_reports": []
... | python - collect full path till leaf on organization tree | I got organizations tree stored as json
{
"name": "amos",
"direct_reports": [
{
"name": "bart",
"direct_reports": [
{
"name": "colin",
"direct_reports": []
},
{
"name": "cl... | [
"Like this, maybe:\ndef get_chain(org, name):\n if org['name'] == name:\n return [name]\n for emp in org['direct_reports']:\n chain = get_chain(emp, name)\n if chain:\n return [org['name']] + chain\n return None\n\nprint(get_chain(org, 'bart')) # ['amos', 'bart']\nprint(g... | [
1
] | [] | [] | [
"breadth_first_search",
"python",
"tree"
] | stackoverflow_0074508822_breadth_first_search_python_tree.txt |
Q:
Extract text from class 'bs4.element.Tag' beautifulsoup
I have the following text in a class 'bs4.element.Tag' object:
<span id="my_rate">264.46013</span>
How do I strip the value of 264.46013 and get rid of the junk before and after the value?
I have seen this and this but I am unable to use the text.split() met... | Extract text from class 'bs4.element.Tag' beautifulsoup | I have the following text in a class 'bs4.element.Tag' object:
<span id="my_rate">264.46013</span>
How do I strip the value of 264.46013 and get rid of the junk before and after the value?
I have seen this and this but I am unable to use the text.split() methods etc.
Cheers
| [
"I'm not sure I follow, however, if you are using BeautifulSoup:\nfrom bs4 import BeautifulSoup as bs\n\nhtml = '<span id=\"my_rate\">264.46013</span>'\n\nsoup = bs(html, 'html.parser')\nvalue = soup.select_one('span[id=\"my_rate\"]').get_text()\nprint(value)\n\nResult:\n264.46013\n\n"
] | [
2
] | [] | [] | [
"beautifulsoup",
"html",
"python"
] | stackoverflow_0074508471_beautifulsoup_html_python.txt |
Q:
Tkinter: pack's anchor option is not working
I've two file for my app, and in my second one page_one.py I can't use properly the anchor method. The label 'left' and 'right' are always positioned in the middle of the screen and not on the side
# main.py
import tkinter as tk
from page_one import PageOne
class Main(... | Tkinter: pack's anchor option is not working | I've two file for my app, and in my second one page_one.py I can't use properly the anchor method. The label 'left' and 'right' are always positioned in the middle of the screen and not on the side
# main.py
import tkinter as tk
from page_one import PageOne
class Main(tk.Frame):
def __init__(self, parent, *args, **k... | [
"That's because your PageOne frame doesn't fill Main. Add fill=\"both\" to its pack method as well:\nimport tkinter as tk\n\nclass PageOne(tk.Frame):\n def __init__(self, parent, *args, **kwargs):\n super().__init__(parent, *args, **kwargs) \n \n... | [
2,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074508954_python_tkinter.txt |
Q:
Postgres database refusing connection from Airflow: Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections port 5432?
I have an existing database (Postgres) that i want to connect to apache-Airflow on my host machine(Windows 10), I installed the apache-airflow on the WSL running ubu... | Postgres database refusing connection from Airflow: Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections port 5432? | I have an existing database (Postgres) that i want to connect to apache-Airflow on my host machine(Windows 10), I installed the apache-airflow on the WSL running ubuntu. The installation was smooth and working fine since i was able to get the airflow webserver running on my localhost(port:8081).
I tried connecting airf... | [
"Found out the problem is with WSL 2, you cant connect to localhost from WSL2 without some complicated tweaks... The simplest thing to do is downgrade to WSL 1\nrunning this command in powershell:\nwsl.exe --set-version Ubuntu-20.04 1\n"
] | [
0
] | [] | [] | [
"airflow",
"airflow_webserver",
"postgresql",
"python"
] | stackoverflow_0074300916_airflow_airflow_webserver_postgresql_python.txt |
Q:
djangocms: command not found
I installed django cms by this command
$ sudo pip3 install django-cms
the installation is completed and returns this:
Requirement already satisfied: django-cms in /usr/local/lib/python3.6/dist-packages
Requirement already satisfied: django-classy-tags>=0.7.2 in /usr/local/lib/python3.... | djangocms: command not found | I installed django cms by this command
$ sudo pip3 install django-cms
the installation is completed and returns this:
Requirement already satisfied: django-cms in /usr/local/lib/python3.6/dist-packages
Requirement already satisfied: django-classy-tags>=0.7.2 in /usr/local/lib/python3.6/dist-packages (from django-cms)
... | [
"http://docs.django-cms.org/en/release-3.4.x/introduction/install.html\nMy guess is you forgot to run: pip install djangocms-installer\nI'm guessing that because I did that too. I installed pip install django-cms, then wondered why it didn't work. \n",
"Just ran into this and got it solved. Afterwards my palm we... | [
0,
0
] | [] | [] | [
"django",
"django_cms",
"python"
] | stackoverflow_0047657871_django_django_cms_python.txt |
Q:
Create a function called printtype that takes one parameter
If the parameter is a string, return "String"
If the parameter is an int, return "Int"
If the parameter is a float, return "Float"
Code:-
def printtype(x):
if isinstance(x,int):
return x
elif isinstance(x,float):
return x
... | Create a function called printtype that takes one parameter | If the parameter is a string, return "String"
If the parameter is an int, return "Int"
If the parameter is a float, return "Float"
Code:-
def printtype(x):
if isinstance(x,int):
return x
elif isinstance(x,float):
return x
else:
isinstance(x,str)
return x
print(type(print... | [
"This could solve your issue.\ndef printtype(x): \n if isinstance(x,int):\n return \"Int\"\n elif isinstance(x,float):\n return \"Float\"\n elif isinstance(x,str):\n return \"String\"\n else:\n return \"Unknown type\"\n \nprint(printtype(5))\nprint(printtype(5.0))\nprint... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074509086_python.txt |
Q:
Iterating a list: getting values as[set(), set(), set(), set(), set()]
I have a list (df_pop_initial_list), and it looks like this:
[['000000000000000000000000000001011000000'],
['000000001000000000000001000000000010000'],
['000000000000000000000000000000010011000'],
['000000000000001001000000000000010000000'],... | Iterating a list: getting values as[set(), set(), set(), set(), set()] | I have a list (df_pop_initial_list), and it looks like this:
[['000000000000000000000000000001011000000'],
['000000001000000000000001000000000010000'],
['000000000000000000000000000000010011000'],
['000000000000001001000000000000010000000'],
['000000000000000000010000001000000010000'],
['10000000001000000000100000... | [
"intial_population_bit_to_int is giving a list of sets because indices_initial_pop always (with the data you use) returns an empty set. Your actual question is why indices_initial_pop returns an empty set. And the answer is because the value you pass as argument in your call, i.e. chrome, is not a string, but a lis... | [
1
] | [] | [] | [
"genetic_algorithm",
"genetic_programming",
"jupyter_notebook",
"list",
"python"
] | stackoverflow_0074509131_genetic_algorithm_genetic_programming_jupyter_notebook_list_python.txt |
Q:
How to get JSON data in expected format using Python json.dump
I read multiple sheets from excel files and combine then to a single JSON file.
Sample Data:
df1
Metric Value
0 salesamount 9.0
1 salespercentage 80.0
2 salesdays 56.0
3 sa... | How to get JSON data in expected format using Python json.dump | I read multiple sheets from excel files and combine then to a single JSON file.
Sample Data:
df1
Metric Value
0 salesamount 9.0
1 salespercentage 80.0
2 salesdays 56.0
3 salesconversionpercentage 0.3
df2
Metric Value
0 FromB... | [
"Try:\nout = {\n \"ExpectedPlanPerformance\": [\n {\n \"ExpectedOutcome\": dict(zip(df3.Metric, df3.Value)),\n \"Sales\": dict(zip(df1.Metric, df1.Value)),\n \"EstimatedBudget\": dict(zip(df2.Metric, df2.Value)),\n }\n ]\n}\n\nprint(out)\n\nPrints:\n{\n \"Expe... | [
1
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074509147_json_python.txt |
Q:
Run multiple schedule jobs at same time using Python Schedule
I am using cx Oracle and schedule module in python. Following is the psuedo code.
import schedule,cx_Oracle
def db_operation(query):
'''
Some DB operations like
1. Get connection
2. Execute query
3. commit result (in case of DML ope... | Run multiple schedule jobs at same time using Python Schedule | I am using cx Oracle and schedule module in python. Following is the psuedo code.
import schedule,cx_Oracle
def db_operation(query):
'''
Some DB operations like
1. Get connection
2. Execute query
3. commit result (in case of DML operations)
'''
schedule.every().hour.at(":10").do(db_operation,... | [
"I took a look at the code of schedule and I have come to the following conclusions:\n\nThe schedule library does not work in parallel or concurrent. Therefore, jobs that have expired are processed one after the other. They are sorted according to their due date. The job that should be performed furthest in the pas... | [
1
] | [] | [] | [
"cx_oracle",
"python",
"python_3.x",
"python_schedule"
] | stackoverflow_0074497651_cx_oracle_python_python_3.x_python_schedule.txt |
Q:
Merge specific rows which have the same ID value in a specific column in pandas DataFrame
I have a DataFrame df1 with ID and Amount on specific Dates. I try to sum up the Amount of two specific rows which have the same ID value.
df1:
Date ID Amount
0 2022-01-02 1200 10.0
1 2022-01-02 1200 ... | Merge specific rows which have the same ID value in a specific column in pandas DataFrame | I have a DataFrame df1 with ID and Amount on specific Dates. I try to sum up the Amount of two specific rows which have the same ID value.
df1:
Date ID Amount
0 2022-01-02 1200 10.0
1 2022-01-02 1200 1.0
2 2022-01-02 1400 12.0
3 2022-01-02 1500 11.0
4 2022-01-03 1300 12.5
5... | [
"If I understand your problem correctly, it looks like a transaction data and the groups you need are by [Date, ID].\nIf so, then you can achieve it as:\ndf1[\"Amount\"] = df1.groupby([\"Date\", \"ID\"])[\"Amount\"].transform(lambda x: [x.sum() if i==0 else 0 for i,_ in enumerate(x)])\n\nFull example. I have added ... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"shift"
] | stackoverflow_0074508504_dataframe_pandas_python_shift.txt |
Q:
How to remove links from tags in html?
I'm writing scraper in Python with bs4 and want to remove links from all 'a' tags
I have html code
html_code = '<a href="link">some text</a>'
I want to remove href="link" and get only
html_code = '<a>some text</a>'
How can i do it?
A:
I would do it following way
from bs4 ... | How to remove links from tags in html? | I'm writing scraper in Python with bs4 and want to remove links from all 'a' tags
I have html code
html_code = '<a href="link">some text</a>'
I want to remove href="link" and get only
html_code = '<a>some text</a>'
How can i do it?
| [
"I would do it following way\nfrom bs4 import BeautifulSoup\nhtml_code = '<a href=\"link\">some text</a>'\nsoup = BeautifulSoup(html_code)\nprint(\"Before\")\nprint(soup.prettify())\nfor node in soup.find_all(\"a\"):\n node.attrs = {}\nprint(\"After\")\nprint(soup.prettify())\n\ngives output\nBefore\n<html>\n <b... | [
2,
0,
0
] | [] | [] | [
"beautifulsoup",
"html",
"python",
"web_scraping"
] | stackoverflow_0074508666_beautifulsoup_html_python_web_scraping.txt |
Q:
How to sum values of a column where the column name has been duplicated?
I have a dataframe:
df = pd.DataFrame({'grps': list('aaabbcaabcccbbc'),
'vals': [12,345,-3,1,45,14,4,52,54,23,235,-21,57,-3,87]})
I want to find the sum of 'vals' of each group: a,b,c
I've tried using the .sum() function but... | How to sum values of a column where the column name has been duplicated? | I have a dataframe:
df = pd.DataFrame({'grps': list('aaabbcaabcccbbc'),
'vals': [12,345,-3,1,45,14,4,52,54,23,235,-21,57,-3,87]})
I want to find the sum of 'vals' of each group: a,b,c
I've tried using the .sum() function but I'm struggling on how to group all the values of the same letter.
| [
"You can use GroupBy.sum :\nout= df.groupby(\"grps\", as_index=False).sum()\n\n# Output :\nprint(out)\n\n grps vals\n0 a 410\n1 b 154\n2 c 338\n\n"
] | [
2
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074509208_dataframe_numpy_pandas_python.txt |
Q:
Missing data in excel from 2 products
I am working on a code where it is necessary to scrape data from the website of all locomotives.
When exporting to Excel, 2 products do not appear:
Line 6 in excel (product: 63256) and 7 (product: 69256)
Could someone give me a hint why?
Here is the code:
.
.
.
.
import reques... | Missing data in excel from 2 products | I am working on a code where it is necessary to scrape data from the website of all locomotives.
When exporting to Excel, 2 products do not appear:
Line 6 in excel (product: 63256) and 7 (product: 69256)
Could someone give me a hint why?
Here is the code:
.
.
.
.
import requests
from bs4 import BeautifulSoup
import pan... | [
"Do not use except the way you do just skipping the error, instead print it and do some research to handle the issue:\nexcept Exception as e: \n print(e)\n\nYou do not allow redirects, so in some cases you won't get a soup - enabling redirects will lead in some cases to an infinity redirct, what in my opinon is ... | [
0
] | [] | [] | [
"export_to_excel",
"python",
"web_scraping"
] | stackoverflow_0074502975_export_to_excel_python_web_scraping.txt |
Q:
Why does del (x) with parentheses around the variable name work?
Why does this piece of code work the way it does?
x = 3
print(dir()) #output indicates that x is defined in the global scope
del (x)
print(dir()) #output indicates that x is not defined in the global scope
My understanding is that del is a keywo... | Why does del (x) with parentheses around the variable name work? | Why does this piece of code work the way it does?
x = 3
print(dir()) #output indicates that x is defined in the global scope
del (x)
print(dir()) #output indicates that x is not defined in the global scope
My understanding is that del is a keyword in Python, and what follows del should be a name. (name) is not a n... | [
"The definition of the del statement is:\ndel_stmt ::= \"del\" target_list\n\nand from the definition of target_list:\ntarget_list ::= target (\",\" target)* [\",\"]\ntarget ::= identifier\n | \"(\" target_list \")\"\n | \"[\" [target_list] \"]\"\n | ...\n\nyo... | [
12,
0
] | [] | [] | [
"python"
] | stackoverflow_0039028249_python.txt |
Q:
Python truncate a long string
How does one truncate a string to 75 characters in Python?
This is how it is done in JavaScript:
var data="saddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsaddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsadddddddd... | Python truncate a long string | How does one truncate a string to 75 characters in Python?
This is how it is done in JavaScript:
var data="saddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsaddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsaddddddddddddddddddddddddddddddddddddddddddd... | [
"info = (data[:75] + '..') if len(data) > 75 else data\n\n",
"Even more concise:\ndata = data[:75]\n\nIf it is less than 75 characters there will be no change.\n",
"Even shorter :\ninfo = data[:75] + (data[75:] and '..')\n\n",
"If you are using Python 3.4+, you can use textwrap.shorten from the standard libra... | [
549,
173,
154,
128,
45,
15,
13,
6,
6,
6,
4,
4,
3,
2,
1,
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002872512_python.txt |
Q:
Python MSAL PATCH to mark email as read CompactToken parsing failed
I have a program that utilizes the MS Graph API and pulls emails received yesterday that have an attachment and have not been read. My endpoint looks like this:
'https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?$expand=attachments&$s... | Python MSAL PATCH to mark email as read CompactToken parsing failed | I have a program that utilizes the MS Graph API and pulls emails received yesterday that have an attachment and have not been read. My endpoint looks like this:
'https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?$expand=attachments&$search="hasAttachments:true AND received:yesterday AND isRead:false"'
Aft... | [
"It should be:\nrequests.patch(f'https://graph.microsoft.com/v1.0/me/messages/{emailid}', json={'isRead': True}, headers={'Authorization': f'Bearer {oauth_token_access_token}'})\n\n"
] | [
1
] | [] | [] | [
"microsoft_graph_api",
"msal",
"python",
"python_requests"
] | stackoverflow_0074480887_microsoft_graph_api_msal_python_python_requests.txt |
Q:
Poission Distribution considering time left
I want to calculate the remaining probabilities for each result in a football game at n minute.
In this case I have expected goals for home team of 2.69 and away team 1.12 at 70 minute for a current result of 2-1
Code
from scipy.stats import poisson
from itertools import... | Poission Distribution considering time left | I want to calculate the remaining probabilities for each result in a football game at n minute.
In this case I have expected goals for home team of 2.69 and away team 1.12 at 70 minute for a current result of 2-1
Code
from scipy.stats import poisson
from itertools import product
import numpy as np
import pandas as pd
... | [
"Math considerations\nPoisson distribution is the probability that an event occurs k times in a given time frame, knowing that, on average, it is supposed to occur μ times in this same time frame.\nThe postulate of Poisson distribution is that events are totally independent. So how many times it has already occurre... | [
1
] | [] | [] | [
"poisson",
"probability",
"probability_distribution",
"python"
] | stackoverflow_0074507895_poisson_probability_probability_distribution_python.txt |
Q:
how to us the prefix if there are two forms and one submit button?
I try to upload two forms with one submit button.
A user can select a pdf file and a excel file. And then uploading both files. And then the contents of both are returned.
So I try to upload both files with one submit button.
But the two selected f... | how to us the prefix if there are two forms and one submit button? | I try to upload two forms with one submit button.
A user can select a pdf file and a excel file. And then uploading both files. And then the contents of both are returned.
So I try to upload both files with one submit button.
But the two selected file options are not visible for uploading the files.
So I have the templ... | [
"The variable name used in the template is the key of the dictionary, not the value. The value is what is inserted into the template when django renders the page.\nYou have {{form1.as__p}} in your template, but you send \"form\": [form1, form2] as your context, so the variable in the template should be {{ form.0.a... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074508785_django_python.txt |
Q:
How do I implement a range function in this program?
I am making a program that allows students to predict their progression at the end of each academic year.
ble 1: Progression outcomes as defined by the University regulations.
Volume of Credit at Each Level
fist digit is Pass
second digit is Defer
third digit ... | How do I implement a range function in this program? | I am making a program that allows students to predict their progression at the end of each academic year.
ble 1: Progression outcomes as defined by the University regulations.
Volume of Credit at Each Level
fist digit is Pass
second digit is Defer
third digit is Fail
i have already implmented this in to my program. h... | [
"For part 1, a simple func can test that the input value exists between the two end values and is a multiple of 20. The 'mod' func is good for the multiple part\ndef input_valid_number(which=\"pass\"):\n while True:\n n = input(\"Enter your {} credits: \".format(which)).strip()\n if n.isdigit():\n ... | [
0,
0
] | [] | [] | [
"integer",
"python",
"range"
] | stackoverflow_0058791012_integer_python_range.txt |
Q:
Creating simple password cracker using numpy arrays
I'm Trying to create a (number) password cracker function using numpy arrays instead of for-loops.
What can I add to my cracker function to avoid this error? (See image of code attached)
Image of my code
I want the cracker function to return the value in the 'pos... | Creating simple password cracker using numpy arrays | I'm Trying to create a (number) password cracker function using numpy arrays instead of for-loops.
What can I add to my cracker function to avoid this error? (See image of code attached)
Image of my code
I want the cracker function to return the value in the 'possible' array that returns 'Correct' when used as the argu... | [
"You can refer to my way\ndef password(correctedpassword):\n if 13 in correctedpassword:\n return \"Correct\"\n else:\n return \"Incorrect\"\n \ndef cracker(testrange):\n possible = np.linspace(0,testrange,testrange+1)\n return password(possible)\n\nOutput when call function cracker(100... | [
0,
0
] | [] | [] | [
"numpy",
"python",
"python_3.x"
] | stackoverflow_0074508661_numpy_python_python_3.x.txt |
Q:
Selenium: trying to upload two files but three or more files have been uploaded
I tried to add photo to Facebook marketplace in here with selenium python like this:
driver.find_element(By.XPATH, '//input[@type="file"]').send_keys('C:/image.jpg')
when I try to send one photo, one photo have been sent, the problem i... | Selenium: trying to upload two files but three or more files have been uploaded | I tried to add photo to Facebook marketplace in here with selenium python like this:
driver.find_element(By.XPATH, '//input[@type="file"]').send_keys('C:/image.jpg')
when I try to send one photo, one photo have been sent, the problem is when I try to send two or more photo like this:
driver.get('https://www.facebook.co... | [
"This seems to be a bug.\nWhen uploading a file with a send_keys() method in a loop the file is being uploaded twice.\nI.e. if you performing send keys 2 times the file file be uploaded 4 time, for 3 iterations 6 files will be uploaded etc.\nCurrently I see no solution for this issue. F.e. adding a delay inside the... | [
1
] | [] | [] | [
"file_upload",
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074508781_file_upload_python_selenium_selenium_webdriver.txt |
Q:
How to add on the left and on the right order like 1 to 8
Hi I have small problem I dont know how to add oder like from 1 to number 8 on the right and on the left of this program.Here is the list but How to add numbers on the left and on the righ. I did this with letters up and down
Here is my code
sachy = [[0, 1,... | How to add on the left and on the right order like 1 to 8 | Hi I have small problem I dont know how to add oder like from 1 to number 8 on the right and on the left of this program.Here is the list but How to add numbers on the left and on the righ. I did this with letters up and down
Here is my code
sachy = [[0, 1, 0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1... | [
"You need to pair the row indices with the row itself, also use \" \".join() for shorted code\nprint(\" \", \" \".join(poradi), \"\\n\")\n\nfor idx, seznam in zip(poradi_2, sachy):\n print(idx, \" \".join(map(str, seznam)), idx)\n\nprint(\"\\n \", \" \".join(poradi), \"\\n\\n\")\n\n a b c d e f g h\n\n1 0 1 0 1... | [
0
] | [] | [] | [
"list",
"numbers",
"python"
] | stackoverflow_0074509279_list_numbers_python.txt |
Q:
How can I access and manage iterables inside each pandas.DataFrame column?
I have the following JSON file:
{
"IMG1.tif": {
"0": [
100,
192,
[
129,
42,
32
]
],
"1": [
299,
208,
[
133,
42,
24
]
]
},
... | How can I access and manage iterables inside each pandas.DataFrame column? | I have the following JSON file:
{
"IMG1.tif": {
"0": [
100,
192,
[
129,
42,
32
]
],
"1": [
299,
208,
[
133,
42,
24
]
]
},
"IMG2.tif": {
"0": [
100,
207,
[
128,
41,
... | [
"I'd suggest building a dataframe with multiindex columns:\ndf = df.T # first transpose your df\n\ndf_out = pd.concat([\n pd.DataFrame(df[col].tolist(), index=df.index,\n columns=pd.MultiIndex.from_tuples(zip([col]*3, [\"x\", \"y\", \"z\"]))\n ) for col in df.columns\n], axis=1\n)\n\nThis will give you the fol... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074509039_dataframe_pandas_python.txt |
Q:
Python transform data long to wide
I'm looking to transform some data in Python.
Originally, in column 1 there are various identifiers (A to E in this example) associated with towns in column 2. There is a separate row for each identifier and town association. There can be any number of identifier to town associat... | Python transform data long to wide | I'm looking to transform some data in Python.
Originally, in column 1 there are various identifiers (A to E in this example) associated with towns in column 2. There is a separate row for each identifier and town association. There can be any number of identifier to town associations.
I'd like to end up with ONE row pe... | [
"One way to do it is using gruopby. For example, you can group by Column 1 and apply a function that returns the list of unique values for each group (i.e. each code).\nimport numpy as np\nimport pandas as pd\ndf = pd.DataFrame({\n 'col1': 'A A A A B B C C C D E E E E E'.split(' '),\n 'col2': ['Accrington', '... | [
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0074508861_python.txt |
Q:
Python, Unicode, and the Windows console
When I try to print a Unicode string in a Windows console, I get an error .
UnicodeEncodeError: 'charmap' codec can't encode character ....
I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this?
Is there any wa... | Python, Unicode, and the Windows console | When I try to print a Unicode string in a Windows console, I get an error .
UnicodeEncodeError: 'charmap' codec can't encode character ....
I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this?
Is there any way I can make Python automatically print a ? in... | [
"Update: Python 3.6 implements PEP 528: Change Windows console encoding to UTF-8: the default console on Windows will now accept all Unicode characters. Internally, it uses the same Unicode API as the win-unicode-console package mentioned below. print(unicode_string) should just work now.\n\n\nI get a UnicodeEncode... | [
86,
39,
29,
11,
10,
6,
5,
2,
2,
2,
1,
1,
0
] | [
"James Sulak asked,\n\nIs there any way I can make Python automatically print a ? instead of failing in this situation?\n\nOther solutions recommend we attempt to modify the Windows environment or replace Python's print() function. The answer below comes closer to fulfilling Sulak's request.\nUnder Windows 7, Pyth... | [
-1,
-1
] | [
"python",
"unicode"
] | stackoverflow_0000005419_python_unicode.txt |
Q:
"assert" statement with or without parentheses
Here are four simple invocations of assert:
>>> assert 1==2
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError
>>> assert 1==2, "hi"
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError: hi
>>> assert(1==2)
T... | "assert" statement with or without parentheses | Here are four simple invocations of assert:
>>> assert 1==2
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError
>>> assert 1==2, "hi"
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError: hi
>>> assert(1==2)
Traceback (most recent call last):
File "<stdin>", ... | [
"The last assert would have given you a warning (SyntaxWarning: assertion is always true, perhaps remove parentheses?) if you ran it through a full interpreter, not through IDLE. Because assert is a keyword and not a function, you are actually passing in a tuple as the first argument and leaving off the second arg... | [
153,
47,
26,
19,
1,
0
] | [] | [] | [
"assert",
"parentheses",
"python",
"statements"
] | stackoverflow_0003112171_assert_parentheses_python_statements.txt |
Q:
loop through nested dictionary in python and display key value pair
i am a beginner in python i and i came up this problem and i cant seem to solve it.I have the following dictionary
stats = {1: {"Player": "Derrick Henry", "yards": 870, "TD": 9}, 2: {"Player": "Nick Chubb", "Yards": 841, "TD": 10}, 3: {"Player": "... | loop through nested dictionary in python and display key value pair | i am a beginner in python i and i came up this problem and i cant seem to solve it.I have the following dictionary
stats = {1: {"Player": "Derrick Henry", "yards": 870, "TD": 9}, 2: {"Player": "Nick Chubb", "Yards": 841, "TD": 10}, 3: {"Player": "Saquon Barkley", "Yards": 779, "TD": 5}}
I want to loop through a dictio... | [
"Don't you see here the useless logic : if a variable is something, you write manualmy that thing in a string, just use it directly\nif x == \"Player\":\n print(\"Player = {}\".format(x))\nif y == \"Yards\":\n print(\"Yards = {}\".format(y))\nif z == \"TD\":\n print(\"TD = {}\".format(y))\n\n\nAlso you did... | [
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074509308_dictionary_python.txt |
Q:
PyQt QTableView resizeRowsToContents not completely resize on initialisation
I have a minimum example here of a QTableView widget that displays a long string that I want word wrapped when I start the app.
from PyQt6.QtWidgets import (
QMainWindow,
QTableView,
QHeaderView,
QApplication,
)
from PyQt6... | PyQt QTableView resizeRowsToContents not completely resize on initialisation | I have a minimum example here of a QTableView widget that displays a long string that I want word wrapped when I start the app.
from PyQt6.QtWidgets import (
QMainWindow,
QTableView,
QHeaderView,
QApplication,
)
from PyQt6.QtCore import (
Qt,
QEvent,
QAbstractTableModel,
QSize,
QEve... | [
"\nwhy does self.table.horizontalHeader().sectionResized.connect(self.table.resizeRowsToContents) work upon resizing when resizeRowsToContents() does not work in the init method?\n\nBecause the window isn't rendered yet, that's why the QTableView doesn't know yet how big the text is in order to resize the rows.\n\n... | [
1
] | [] | [] | [
"pyqt",
"pyqt5",
"pyqt6",
"python",
"qtableview"
] | stackoverflow_0074509116_pyqt_pyqt5_pyqt6_python_qtableview.txt |
Q:
simple affine encryption using python problem
I'm a beginner to python I'm actually trying to encrypt a message using basic python
LETTERS = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z"]
crpt = input("please enter your ... | simple affine encryption using python problem | I'm a beginner to python I'm actually trying to encrypt a message using basic python
LETTERS = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z"]
crpt = input("please enter your message")
K = 3
z = ""
r = ""
for i in range(len(cr... | [
"The problem is caused by the statement LETTERS[r] = \" \" and do not understand the purpose of it.\nWhen you encrypt the first \"A\", r become 0.\nThen you try to encrypt a space but there is no space character in your alphabet. So you execute the \"if crypt ...\" code and wipe-out your alphabet[0]. Next time you... | [
0
] | [] | [] | [
"cryptography",
"python",
"python_cryptography"
] | stackoverflow_0074509056_cryptography_python_python_cryptography.txt |
Q:
Auto reloading python Flask app upon code changes
I'm investigating how to develop a decent web app with Python. Since I don't want some high-order structures to get in my way, my choice fell on the lightweight Flask framework. Time will tell if this was the right choice.
So, now I've set up an Apache server with ... | Auto reloading python Flask app upon code changes | I'm investigating how to develop a decent web app with Python. Since I don't want some high-order structures to get in my way, my choice fell on the lightweight Flask framework. Time will tell if this was the right choice.
So, now I've set up an Apache server with mod_wsgi, and my test site is running fine. However, I'... | [
"Run the flask run CLI command with debug mode enabled, which will automatically enable the reloader. As of Flask 2.2, you can pass --app and --debug options on the command line.\n$ flask --app main.py --debug run\n\n--app can also be set to module:app or module:create_app instead of module.py. See the docs for a f... | [
455,
299,
59,
26,
21,
15,
11,
11,
9,
3,
3,
1,
1
] | [] | [] | [
"apache",
"flask",
"python"
] | stackoverflow_0016344756_apache_flask_python.txt |
Q:
why does not pyfirmata import?
I just wanted to make python and Arduino work together. I saw tutorial that showed that we need library called "Pyfirmata" to do it. when I type "pip install pyfirmata" in command prompt, it shows that the library is already installed. but when I type "import pyfirmata" in python it... | why does not pyfirmata import? | I just wanted to make python and Arduino work together. I saw tutorial that showed that we need library called "Pyfirmata" to do it. when I type "pip install pyfirmata" in command prompt, it shows that the library is already installed. but when I type "import pyfirmata" in python it shows error that library does not e... | [
"It works fine for me, check if your ide is using the same version of python you installed Pyfirmata with\n"
] | [
0
] | [] | [] | [
"arduino",
"pyfirmata",
"python"
] | stackoverflow_0074509458_arduino_pyfirmata_python.txt |
Q:
How to solve the discord chatbot didnt reply message
This is my python code for the discord chatbot that I want to create:
import discord
import os
from dotenv import load_dotenv
from neuralintents import GenericAssistant
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(... | How to solve the discord chatbot didnt reply message | This is my python code for the discord chatbot that I want to create:
import discord
import os
from dotenv import load_dotenv
from neuralintents import GenericAssistant
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
chatbot = GenericAssistant('intents.json... | [
"response is an empty string. It then tries to send an empty string, yeilding the error.\nEdit: It seems you might want to look up discord.py docs instead of using an alpha third party library which provides nothing of value as of now.\n"
] | [
1
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074509531_discord_discord.py_python.txt |
Q:
Updating values inside a python list
ItemList = [
{'name': 'item', 'item_code': '473', 'price': 0},
{'name': 'item', 'item_code': '510', 'price': 0},
{'name': 'item', 'item_code': '384', 'price': 0},
]
data_1 = '510'
data_2 = 200
def update_item(data_1, data_2):
for a in ItemList:
if a['... | Updating values inside a python list | ItemList = [
{'name': 'item', 'item_code': '473', 'price': 0},
{'name': 'item', 'item_code': '510', 'price': 0},
{'name': 'item', 'item_code': '384', 'price': 0},
]
data_1 = '510'
data_2 = 200
def update_item(data_1, data_2):
for a in ItemList:
if a['item_code'] == data_1:
update_... | [
"You can assign the value to the dictionary, with:\ndef update_item(data_1, data_2):\n for a in ItemList:\n if a['item_code'] == data_1:\n a['price'] = data_2\n return\n",
"we can also use the dict update() method to solve this task:\ndef update_item(data_1, data_2):\n for sub i... | [
1,
1
] | [] | [] | [
"django",
"list",
"python"
] | stackoverflow_0074508389_django_list_python.txt |
Q:
Selenium presence_of_element_located look for children of an element
I was wondering if it's possible to look for children of an element with the presence_of_element_located function. I know I could just use the entire path, but that would make my code more confusing due to it's nature. My code would look somethin... | Selenium presence_of_element_located look for children of an element | I was wondering if it's possible to look for children of an element with the presence_of_element_located function. I know I could just use the entire path, but that would make my code more confusing due to it's nature. My code would look something like this (much more complicated but this is the important bit):
current... | [
"Child element with class name className can be located by relative XPath .//*[contains(@class,'className')] or with relative CSS Selector .className.\nSo, I think your code can be modified to be\ncurrentEl = driver.find_element(By.XPATH, (\"//*[@id='2']\"))\nfunc(currentEl)\n\ndef func(currentEl):\n #Wait for t... | [
0
] | [] | [] | [
"css_selectors",
"python",
"selenium",
"selenium_chromedriver",
"xpath"
] | stackoverflow_0074509419_css_selectors_python_selenium_selenium_chromedriver_xpath.txt |
Q:
Adding a new column in one DataFrame where values are based from a second DataFrame
I have two DataFrames, df_a is the DataFrame we want to manipulate. I want to add a new column but the values are found in a second DataFrame with a similar column name.
Let me expound.
df_a contains
_ | Code | Speed | Velocity |
0... | Adding a new column in one DataFrame where values are based from a second DataFrame | I have two DataFrames, df_a is the DataFrame we want to manipulate. I want to add a new column but the values are found in a second DataFrame with a similar column name.
Let me expound.
df_a contains
_ | Code | Speed | Velocity |
0 | DA | 23 | 22 |
1 | ES | 23 | 22 |
2 | DA | 23 | 22 |
... | [
"You just want to pd.merge() (which is similar to a SQL join).\nIn your case:\nnew_df = pd.merge(df_a,df_b,how='left',on='Code')\nnew_df = new_df[['Code','Name','Speed','Velocity']] # if you want to re-arrange the columns in your order\n\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"jupyter_notebook",
"pandas",
"python"
] | stackoverflow_0074509515_dataframe_jupyter_notebook_pandas_python.txt |
Q:
How do I add operator precedence to a lark grammar for FOL with Equality?
How do I modify this grammar so it matches parenthesis that are further away?
?wff: compound_wff
?compound_wff: biconditional_wff
?biconditional_wff: conditional_wff (SPACE? BICONDITIONAL_SYMBOL SPACE? biconditional_wff)*
?conditional_wff: d... | How do I add operator precedence to a lark grammar for FOL with Equality? | How do I modify this grammar so it matches parenthesis that are further away?
?wff: compound_wff
?compound_wff: biconditional_wff
?biconditional_wff: conditional_wff (SPACE? BICONDITIONAL_SYMBOL SPACE? biconditional_wff)*
?conditional_wff: disjunctive_wff (SPACE? CONDITIONAL_SYMBOL SPACE? conditional_wff)*
?disjunctive... | [
"There are a couple of problems with this grammar.\n1. Erroneous whitespace handling\nIn the cascading precedence rules, each rule imposes the requirement for an additional SPACE following the leftmost symbol, even if the repetition is null. So in the cascade, these SPACEs add up as each cascading level adds it's o... | [
0
] | [] | [] | [
"bnf",
"grammar",
"lark_parser",
"parsing",
"python"
] | stackoverflow_0074507340_bnf_grammar_lark_parser_parsing_python.txt |
Q:
Python - Use multiple str.startswith() in a for loop get their specific values
The below function parses multiple csv files in a directory and takes out values using str.startwith().
It works find using 'firstline.startswith('TrakPro')' and 'txt.startswith('Serial')'. However, when I add a third str.startwith() i.... | Python - Use multiple str.startswith() in a for loop get their specific values | The below function parses multiple csv files in a directory and takes out values using str.startwith().
It works find using 'firstline.startswith('TrakPro')' and 'txt.startswith('Serial')'. However, when I add a third str.startwith() i.e. txt2.startswith('Test'), nothing prints out, no error, appears to ignore it. What... | [
"To print only the value of the line that starts with Test Name: you can use following code:\nwith open(\"your_file.csv\", \"r\") as f_in:\n for line in map(str.strip, f_in):\n if line.startswith(\"Test Name:\"):\n _, value = line.split(\",\", maxsplit=1)\n print(value)\n\nPrints:\n1... | [
2,
0
] | [] | [] | [
"csv",
"python",
"startswith",
"string"
] | stackoverflow_0074496853_csv_python_startswith_string.txt |
Q:
FastAPI returns "Error 422: Unprocessable entity" when I send multipart form data with JavaScript Fetch API
I have some issue with using Fetch API JavaScript method when sending some simple formData like so:
function register() {
var formData = new FormData();
var textInputName = document.getElementById('textI... | FastAPI returns "Error 422: Unprocessable entity" when I send multipart form data with JavaScript Fetch API | I have some issue with using Fetch API JavaScript method when sending some simple formData like so:
function register() {
var formData = new FormData();
var textInputName = document.getElementById('textInputName');
var sexButtonActive = document.querySelector('#buttonsMW > .btn.active');
var imagesInput = docum... | [
"The 422 response body will contain an error message about which field(s) is missing or doesn’t match the expected format. Since you haven't provided that (please do so), my guess is that the error is triggered due to how you defined the images parameter in your endpoint. Since images is expected to be a List of Fi... | [
1,
0
] | [] | [] | [
"fastapi",
"fetch",
"fetch_api",
"javascript",
"python"
] | stackoverflow_0074507306_fastapi_fetch_fetch_api_javascript_python.txt |
Q:
How do I generate a vector from a pandas dataframe?
Below is a screenshot of a csv file. I want to generate a vector of growth rates by using pandas.
1
The growth rate is defined as log(this year/previous year) in my case.
Thank you very much!
A:
Welcome to SO. This should work but you should read up on how to ... | How do I generate a vector from a pandas dataframe? | Below is a screenshot of a csv file. I want to generate a vector of growth rates by using pandas.
1
The growth rate is defined as log(this year/previous year) in my case.
Thank you very much!
| [
"Welcome to SO. This should work but you should read up on how to ask good questions:\nimport numpy as np\nimport pandas as pd\n\nnp.random.seed(42)\nYearCode = np.arange(1970, 1975)\ndf = pd.DataFrame(np.random.rand(5, 3), columns = ['VariableCode', 'Region', 'AggValue'])\ndf['YearCode'] = YearCode\nshifted = df[... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"quantitative_finance"
] | stackoverflow_0074509473_dataframe_pandas_python_quantitative_finance.txt |
Q:
Every time I run this function it is slower and slower
I am trying to do code a simple game in python using tkinter where a block jumps over obstacles, however I got stuck on the jumping part. Every time I call the jump function it jumps slower and slower, and I don't know the reason. Ty in advance.
import time
im... | Every time I run this function it is slower and slower | I am trying to do code a simple game in python using tkinter where a block jumps over obstacles, however I got stuck on the jumping part. Every time I call the jump function it jumps slower and slower, and I don't know the reason. Ty in advance.
import time
import tkinter
import random
bg = "white"
f = 2
k=0
t = 0.01
... | [
"Problem with your code is you are always adding new items into your canvas. When you jump you update orange rectangle and repaint its old place. However they stack top of each other and handling too many elements makes slower your program.\nWe create player and return it to main function.\ndef startPlayer(xx,yy):\... | [
0
] | [] | [] | [
"python",
"sleep",
"time",
"tkinter",
"while_loop"
] | stackoverflow_0074509121_python_sleep_time_tkinter_while_loop.txt |
Q:
What is the mean of '*' when use 'from math import *'
i made a code like this. and i learnedimport *calling all module in math
but i don't know mean of '*'
the result is diffrent with the thing i think
i thinked answer of 'd*e' is 16
also, answer of 'd**e' is 64
and so, sqrt(d**e) will be 8
i searched google but i... | What is the mean of '*' when use 'from math import *' | i made a code like this. and i learnedimport *calling all module in math
but i don't know mean of '*'
the result is diffrent with the thing i think
i thinked answer of 'd*e' is 16
also, answer of 'd**e' is 64
and so, sqrt(d**e) will be 8
i searched google but i don know the mean of *
d = 8
e = 2
from math import *
pr... | [
"* is a wildcard that loads all of the functions in that library into your local namespace.\n"
] | [
1
] | [] | [] | [
"import",
"math",
"python",
"sqrt"
] | stackoverflow_0074509692_import_math_python_sqrt.txt |
Q:
Reading large table by chunks
I have a table generated on a server and I connect to it using a presto client as follows:
conn = presto.connect('hostname',port)
db = "some_large_table"
What I would like to do is to read in 1 chunk at a time then do my processing and append that chunk to an existing df. Ie:
sql = ... | Reading large table by chunks | I have a table generated on a server and I connect to it using a presto client as follows:
conn = presto.connect('hostname',port)
db = "some_large_table"
What I would like to do is to read in 1 chunk at a time then do my processing and append that chunk to an existing df. Ie:
sql = "select column1, .. column20 limit ... | [
"In my query I limited the number of rows to 10. For some reason df_full.append() does not work, I changed it to df_full = df_full.append() and it works fine. \nsql = \"select*...limit 10\"\ndf_source = pd.read_sql_query(sql, conn, chunksize=2)\nchunk_count = 0\n\ndf_list = []\ndf_full = pd.DataFrame(columns = col_... | [
1,
1
] | [
"Well I can't be sure that this will work without more context but I can tell you that your issue arises because dfs is a list of data frames not a data frame... That said with this approach you will assign dfs to be equal to your first query and append subsequent querys to that result.\nsql = \"select column1, .. ... | [
-1
] | [
"pandas",
"python",
"python_3.x"
] | stackoverflow_0060254908_pandas_python_python_3.x.txt |
Q:
Detect square symbols in a diagram image in python using OpenCV
I am trying to detect the square shaped symbols in a P&ID (a diagram) image file using OpenCV.
I tried following tutorials that use contours, but that method doesn't seem to work with such diagram images. Using Hough Lines I am able to mark the vertic... | Detect square symbols in a diagram image in python using OpenCV | I am trying to detect the square shaped symbols in a P&ID (a diagram) image file using OpenCV.
I tried following tutorials that use contours, but that method doesn't seem to work with such diagram images. Using Hough Lines I am able to mark the vertical edges of these squares, but I am not sure how to use these edges d... | [
"If you know that the lines are horizontal or vertical you can filter them out by combining erode and dilate (the docs describe how it works).\nAfter seperating horizontal and vertical lines, you can filter them by size. At the end you can fill all remaining closed contours and again use erode/delete to exract the ... | [
1
] | [] | [] | [
"hough_transform",
"opencv",
"python"
] | stackoverflow_0074488983_hough_transform_opencv_python.txt |
Q:
Reading multiple zip archive comments with python
My zip file contains a lot of smaller zip files.
I want to iterate through all those files,
reading and printing each of their comments.
I've found out that zipfile file.zip or unzip -z file.zipcan do this to a file in separate, but I'm looking for a way to go th... | Reading multiple zip archive comments with python | My zip file contains a lot of smaller zip files.
I want to iterate through all those files,
reading and printing each of their comments.
I've found out that zipfile file.zip or unzip -z file.zipcan do this to a file in separate, but I'm looking for a way to go through all of them.
Couldn't find anything perfect yet, ... | [
"Not sure exactly what your looking for but here are a few ways I did it on an Ubuntu Linux machine.\nfor i in `ls *.zip`; do unzip -l $i; done\n\nor\nunzip -l myzip.zip\n\nor\nunzip -p myzip.zip | python -c 'import zipfile,sys,StringIO;print \"\\n\".join(zipfile.ZipFile(StringIO.StringIO(sys.stdin.read())).nam... | [
1,
1,
0
] | [] | [] | [
"archive",
"python",
"zip"
] | stackoverflow_0050288127_archive_python_zip.txt |
Q:
Python pandas selecting subset of dataframe using filter condition
I have a Pandas DataFrame as below
enter image description here
I want to query on the columns to find out all the columns that contain 'X' for each Name.
sample output be like: (John, O, P) here O and P are the column ids against John that have th... | Python pandas selecting subset of dataframe using filter condition | I have a Pandas DataFrame as below
enter image description here
I want to query on the columns to find out all the columns that contain 'X' for each Name.
sample output be like: (John, O, P) here O and P are the column ids against John that have the character 'X'.
I tried query on Dataframe on columns using loc, but di... | [
"Here is a proposition using pandas.DataFrame.apply and dict to return a dictionnary where the keys are the person names and the values are the columns names that fulfill the condition (is equal to \"X\")\ndico= dict(zip(df[\"Name\"], df.eq(\"X\").apply(lambda x: x.index[x].tolist(), axis=1)))\n\n# Output :\nprint(... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074509652_dataframe_pandas_python.txt |
Q:
Subsetting pandas dataframe with list returns an apparently incorrectly sized resultant dataframe
I am attempting to subset a pandas DatFrame df with a list L that contains only the column names in the DataFrame that I am interested in. The shape of df is (207, 8440) and the length of L is 6894. When I subset my... | Subsetting pandas dataframe with list returns an apparently incorrectly sized resultant dataframe | I am attempting to subset a pandas DatFrame df with a list L that contains only the column names in the DataFrame that I am interested in. The shape of df is (207, 8440) and the length of L is 6894. When I subset my dataframe as df[L] (or df.loc[:, L]), I get a bizarre result. The expected shape of the resultant Dat... | [
"[moving from comment to answer]\nA pandas dataframe can have multiple columns with the exact same name. If this happens, passing a list of column names can return more columns than the size of the list.\nYou can check if the dataframe has duplicates in the column names using {col for col in df.columns if list(df.c... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074509554_pandas_python.txt |
Q:
Reading .sav with python
So, I'm trying to read a .sav file using python and turn it into a .csv. I already got my code to read .sav files, and I also checked it with a test .sav, which I managed to turn into a csv. I then went on to use the real .sav file, and not it no longer works.
Here is the code:
import pyre... | Reading .sav with python | So, I'm trying to read a .sav file using python and turn it into a .csv. I already got my code to read .sav files, and I also checked it with a test .sav, which I managed to turn into a csv. I then went on to use the real .sav file, and not it no longer works.
Here is the code:
import pyreadstat
df, meta = pyreadstat.... | [
"Here is the Solution. I Hope it would help.\nimport pandas as pd\nimport numpy as np\nimport os\n\n# Set the working directory\nos.chdir(\"C:/Users/Desktop/\")\n\n# Read the .sav file\ndf = pd.read_spss(\"file.sav\")\n\n# Print the dataframe\nprint(df)\n\n# Write the .csv file\ndf.to_csv(\"file.csv\")\n\n",
"I f... | [
0,
0,
0
] | [] | [] | [
"csv",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074410261_csv_dataframe_pandas_python.txt |
Q:
Ideas to improve language detection between Spanish and Catalan
I'm working on a text mining script in python. I need to detect the language of a natural language field from the dataset.
The thing is, 98% of the rows are in Spanish and Catalan. I tried using some algorithms like the stopwords one or the langdetect... | Ideas to improve language detection between Spanish and Catalan | I'm working on a text mining script in python. I need to detect the language of a natural language field from the dataset.
The thing is, 98% of the rows are in Spanish and Catalan. I tried using some algorithms like the stopwords one or the langdetect library, but these languages share a lot of words so they fail a lot... | [
"Approach 1: Distinguishing characters\nSpanish and Catalan (note: there will be exceptions for proper names and loanwords e.g. Barça):\nesp_chars = \"ñÑáÁýÝ\"\ncat_chars = \"çÇàÀèÈòÒ·ŀĿ\"\n\nExample:\nsample_texts = [\"El año que es abundante de poesía, suele serlo de hambre.\",\n \"Cal no abandonar... | [
1
] | [
"DicCat = ['amb','cap','dalt','damunt','des','dintre','durant','excepte','fins','per','pro','sense','sota','llei','hi','ha','més','mes','moment','órgans', 'segóns','Article','i','per','els','amb','és','com','dels','més','seu','seva','fou','també','però','als','després','aquest','fins','any','són','hi','pel','aquest... | [
-1
] | [
"language_detection",
"python"
] | stackoverflow_0045672720_language_detection_python.txt |
Q:
Send a wake on lan packet from a docker container
I have a docker container running a python uwsgi app. The app sends a wake on lan broadcast packet to wake a pc in the local network.
It works fine without the use of docker (normal uwsgi app directly on the server), but with docker it won't work.
I exposed port 9/... | Send a wake on lan packet from a docker container | I have a docker container running a python uwsgi app. The app sends a wake on lan broadcast packet to wake a pc in the local network.
It works fine without the use of docker (normal uwsgi app directly on the server), but with docker it won't work.
I exposed port 9/udp and bound it port 9 of the host system.
What am I m... | [
"It seems that UDP broadcast from docker isn't being routed properly (possibly only broadcasted in the container itself, not on the host).\nYou can't send UDP WoL messages directly, as the device you're trying to control is 'offline' it doesn't show up in your router's ARP table and thus the direct message can't be... | [
3,
0
] | [] | [] | [
"docker",
"python",
"uwsgi",
"wake_on_lan"
] | stackoverflow_0033101603_docker_python_uwsgi_wake_on_lan.txt |
Q:
How can i access spider's file data in items file in scrapy python?
FlipKart.py main spider file for scrap name, price, and link from flipkart.com
import scrapy
from ..items import FlipkartScraperItem
class FlipkartSpider(scrapy.Spider):
name = 'FlipKart'
allowed_domains = ['www.flipkart.com']
start_... | How can i access spider's file data in items file in scrapy python? | FlipKart.py main spider file for scrap name, price, and link from flipkart.com
import scrapy
from ..items import FlipkartScraperItem
class FlipkartSpider(scrapy.Spider):
name = 'FlipKart'
allowed_domains = ['www.flipkart.com']
start_urls = ['https://www.flipkart.com/search?q=mobile']
def parse(self, ... | [
"To pull the desired data, you can try to implement the next working example.\nFull working code as an example:\nimport scrapy\nfrom ..items import FlipkartScraperItem\nfrom itemloaders import ItemLoader\n\nclass FlipkartSpider(scrapy.Spider):\n\n name = 'flipKart'\n allowed_domains = ['www.flipkart.com']\n ... | [
1
] | [] | [] | [
"csv",
"python",
"scrapy",
"web_scraping"
] | stackoverflow_0074508265_csv_python_scrapy_web_scraping.txt |
Q:
Pandas: filling missing values by mean in each group
This should be straightforward, but the closest thing I've found is this post:
pandas: Filling missing values within a group, and I still can't solve my problem....
Suppose I have the following dataframe
df = pd.DataFrame({'value': [1, np.nan, np.nan, 2, 3, 1, 3... | Pandas: filling missing values by mean in each group | This should be straightforward, but the closest thing I've found is this post:
pandas: Filling missing values within a group, and I still can't solve my problem....
Suppose I have the following dataframe
df = pd.DataFrame({'value': [1, np.nan, np.nan, 2, 3, 1, 3, np.nan, 3], 'name': ['A','A', 'B','B','B','B', 'C','C','... | [
"One way would be to use transform:\n>>> df\n name value\n0 A 1\n1 A NaN\n2 B NaN\n3 B 2\n4 B 3\n5 B 1\n6 C 3\n7 C NaN\n8 C 3\n>>> df[\"value\"] = df.groupby(\"name\").transform(lambda x: x.fillna(x.mean()))\n>>> df\n name value\n0 A 1\n1... | [
129,
104,
27,
16,
14,
6,
4,
2,
0
] | [
"df.fillna(df.groupby(['name'], as_index=False).mean(), inplace=True)\n\n",
"You can also use \"dataframe or table_name\".apply(lambda x: x.fillna(x.mean())).\n"
] | [
-1,
-1
] | [
"fillna",
"imputation",
"pandas",
"pandas_groupby",
"python"
] | stackoverflow_0019966018_fillna_imputation_pandas_pandas_groupby_python.txt |
Q:
How to remove trailing lines when appending to a file
The problem is when I add a student record (append txt to my file) for the first time a major blank gap is added
username,passcode
jack,Adidas123_
man,Adidas123_
kal,Adidas123_
ll,Adidas123_
I have tried to use the .strip() function it did not seem to help , ... | How to remove trailing lines when appending to a file | The problem is when I add a student record (append txt to my file) for the first time a major blank gap is added
username,passcode
jack,Adidas123_
man,Adidas123_
kal,Adidas123_
ll,Adidas123_
I have tried to use the .strip() function it did not seem to help , I was expecting my csv file to appear like this
username,pa... | [
"Your code is correct, the problem must reside in your students.csv file. You may have by mistake left a newline in the file.\nCheck if you students.csv is:\nusername,password\n\nor\nusername,password\n\n\nwith a newline.\nHope my answer helps!\n",
"As mentioned by RandomCoder59.\nRight now we can only see add_us... | [
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074509646_python.txt |
Q:
djangocms Currently installed Django version 3.2.15 differs from the declared 3.1
I am running an AWS Bitnami Django instance. Django 3.2.15 installed by default. Django documentation recommends version django 3.2 so all is good there. Once installed I am having a hard time getting djangocms to create a new projec... | djangocms Currently installed Django version 3.2.15 differs from the declared 3.1 | I am running an AWS Bitnami Django instance. Django 3.2.15 installed by default. Django documentation recommends version django 3.2 so all is good there. Once installed I am having a hard time getting djangocms to create a new project. I keep getting dependency errors when I issue the command
djangocms -f -p . projectn... | [
"I couldn't figure out why I was receiving these errors when I knew I had more recent versions installed and followed the documentation correctly. Following these steps should get the issue resolved, it is what worked for me:\ncd /home/projects-folder/\nrm -R myproject/\nrm -R venv/ (if you used a virtualenv)\npyth... | [
0
] | [] | [] | [
"django",
"django_cms",
"pip",
"python"
] | stackoverflow_0074509904_django_django_cms_pip_python.txt |
Q:
How to init an empty np array and add one-dimensional ones to it?
I try to create an empty array into which I can add other arrays and get a matrix:
arr = np.array([])
arr = np.append(arr, [1, 2])
arr = np.append(arr, [3, 4])
As a result, I get a one-dimensional array:
array([1., 2., 3., 4.])
Expected result:
ar... | How to init an empty np array and add one-dimensional ones to it? | I try to create an empty array into which I can add other arrays and get a matrix:
arr = np.array([])
arr = np.append(arr, [1, 2])
arr = np.append(arr, [3, 4])
As a result, I get a one-dimensional array:
array([1., 2., 3., 4.])
Expected result:
array([[1., 2.], [3., 4.]])
I tried to init an array as multidimensional... | [
"You need to start with an array with the right dimensions and append using the same dimensions. You also need to note whether you are appending rows or columns, otherwise np.append will flatten the result into a 1d array. Since you are starting with an empty array, you'll need to use a function that lets you speci... | [
1,
1,
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074509525_arrays_numpy_python.txt |
Q:
Fill NaN based on max value from a group and another string column with the value at the NaN row
I have an input data as shown:
df = pd.DataFrame({"colony" : [22, 22, 22, 33, 33, 33],
"measure" : [np.nan, 7, 11, 13, np.nan, 9,],
"net/gross" : [np.nan, "gross", "net", "gross", "... | Fill NaN based on max value from a group and another string column with the value at the NaN row | I have an input data as shown:
df = pd.DataFrame({"colony" : [22, 22, 22, 33, 33, 33],
"measure" : [np.nan, 7, 11, 13, np.nan, 9,],
"net/gross" : [np.nan, "gross", "net", "gross", "np.nan", "net"]})
df
colony measure net/gross
0 22 NaN NaN
1 22 7 ... | [
"My solution\nWhat I would do is compute a column of max\nmx=df.groupby('colony').measure.transform(max)\n\nand a list of rows to be filled\nf=df.measure.isna()\n\nAnd then use them to fill what you want\ndf['remarks']='unchanged'\ndf.loc[f, 'measure']=mx\ndf.loc[f, 'net/gross']=df[f]['net/gross']\ndf.loc[f, 'remar... | [
0,
0
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074509414_dataframe_numpy_pandas_python.txt |
Q:
Setting colours to multiple lines in matplotlib (python)
I have a graph computed from matplotlib, containing six plotted lines, and I want to know what I'm doing wrong for assigning each of my lines a unique colour.
I've got a list for the colours using hex codes, and each listx in "lists" contains the y axis data... | Setting colours to multiple lines in matplotlib (python) | I have a graph computed from matplotlib, containing six plotted lines, and I want to know what I'm doing wrong for assigning each of my lines a unique colour.
I've got a list for the colours using hex codes, and each listx in "lists" contains the y axis data for each line:
colours = ["#ffa500", "#008000", "#ff0000", "#... | [
"I think what is probably happening in your code is because you are looping through your colours list index and then for each index in your colours you are looping through lists.\nSo what will happen is you will get to the end of your colours list indexes (pink) and then loop through lists plotting each using that ... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074509790_matplotlib_python.txt |
Q:
Time formatting with strptime in a dataframe
I'm trying to read a CSV file, where some columns have date or time values.
I started with this:
import pandas as pd
from datetime import datetime
timeparse = lambda x: datetime.strptime(x, '%H:%M:%S.%f')
lap_times = pd.read_csv(
'data/lap_times.csv',
parse_da... | Time formatting with strptime in a dataframe | I'm trying to read a CSV file, where some columns have date or time values.
I started with this:
import pandas as pd
from datetime import datetime
timeparse = lambda x: datetime.strptime(x, '%H:%M:%S.%f')
lap_times = pd.read_csv(
'data/lap_times.csv',
parse_dates={'time_datetime': ['time']},
date_parser=... | [
"It would be easier if you post a sample of your CSV file, but something like this may work:\nimport pandas as pd\nfrom datetime import datetime as dt\n\ndf = pd.DataFrame({'Time': ['12:34:56', '12:34:56.789']})\n\ndf.Time = df.Time.apply(lambda x: dt.strptime(x, '%H:%M:%S.%f') if len(x) > 8 else dt.strptime(x, '%H... | [
0
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074508325_dataframe_python.txt |
Q:
Why is __init__() always called after __new__()?
I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.
However, I'm a bit confused as to why __init__ is always called after __new__. I wasn't expecting this. Can anyone tell me why t... | Why is __init__() always called after __new__()? | I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.
However, I'm a bit confused as to why __init__ is always called after __new__. I wasn't expecting this. Can anyone tell me why this is happening and how I can implement this function... | [
"\nUse __new__ when you need to control\nthe creation of a new instance.\n\n\nUse\n__init__ when you need to control initialization of a new instance.\n__new__ is the first step of instance creation. It's called first, and is\nresponsible for returning a new\ninstance of your class.\n\n\nIn contrast,\n__init__ doe... | [
696,
198,
174,
28,
13,
12,
10,
7,
7,
5,
5,
5,
5,
5,
3,
2,
1,
1,
0
] | [] | [] | [
"class_design",
"design_patterns",
"python"
] | stackoverflow_0000674304_class_design_design_patterns_python.txt |
Q:
How to get mouse inputs from raw data?
Hello I am trying to develop a Linux game in Panda3D which uses python for coding so anything in python would work. The game requires two mouse inputs (movement and mouse clicks). I want to get the info from the files in /dev/input but a more convenient way would help.
I've a... | How to get mouse inputs from raw data? | Hello I am trying to develop a Linux game in Panda3D which uses python for coding so anything in python would work. The game requires two mouse inputs (movement and mouse clicks). I want to get the info from the files in /dev/input but a more convenient way would help.
I've already got code to get the input file I want... | [] | [] | [
"The pynput module has a callback-based interface that let's you monitor mouse events such as movement and and clicks.\nCheck it out\n"
] | [
-1
] | [
"input",
"python"
] | stackoverflow_0074509920_input_python.txt |
Q:
How to create an ordered list of keys based on their value in a dict?
I'm quite stuck with this problem in Python and I'm pretty sure it should be pretty easy to solve.
Please find this dict example:
d = {
"a": "abc1",
"b": "abc1",
"c": "abc2",
"d": "abc3",
"e": "abc3",
"f": "abc3",
"g"... | How to create an ordered list of keys based on their value in a dict? | I'm quite stuck with this problem in Python and I'm pretty sure it should be pretty easy to solve.
Please find this dict example:
d = {
"a": "abc1",
"b": "abc1",
"c": "abc2",
"d": "abc3",
"e": "abc3",
"f": "abc3",
"g": "abc4"
}
Now I want a to create a list where 'a' till 'g' will be put i... | [
"This is the first code I got working. And now it also removes f. Any other ideas?\nd = {\n \"a\": \"abc1\",\n \"b\": \"abc1\",\n \"c\": \"abc2\",\n \"d\": \"abc3\",\n \"e\": \"abc3\",\n \"f\": \"abc3\",\n \"g\": \"abc4\"\n}\n\nlist_number = {}\nkey_lists = []\n\nfor key, value in d.items():\n ... | [
1,
0,
0,
0
] | [] | [] | [
"dictionary",
"python",
"unique"
] | stackoverflow_0074476573_dictionary_python_unique.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.