Unnamed: 0
int64
0
1.91M
id
int64
337
73.8M
title
stringlengths
10
150
question
stringlengths
21
64.2k
answer
stringlengths
19
59.4k
tags
stringlengths
5
112
score
int64
-10
17.3k
2,600
64,374,751
Sum value in a row based on the head of the columns
<p>I have a dataset like this: <a href="https://i.stack.imgur.com/VndaS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VndaS.png" alt="enter image description here" /></a></p> <p>I want to calculate the sum of <code>apple_*_C</code>,<code>apple_*_Cr</code>, <code>apple_*_Cu</code> in each row, respe...
<pre><code>import pandas as pd data = { &quot;Apple_1_C&quot; : [1,2], &quot;Apple_2_C&quot; : [2,3], &quot;Apple_3_C&quot; : [3,4], &quot;Apple_1_Cr&quot; : [4,5], &quot;Apple_1_Cr&quot; : [5,6], &quot;Apple_1_Cu&quot; : [6,7], &quot;Apple_2_Cu&quot; : [7,8], } df = pd.DataFra...
python|regex|dataframe
1
2,601
70,486,174
Insert weekend dates into dataframe while keeping prices in index location
<p>I have a pandas DataFrame with dates, open and close prices of USD that looks something like this:</p> <pre><code>Date Open Close 2021-12-08 0.88707 0.88680 2021-12-07 0.88617 0.88600 2021-12-06 0.88475 0.88458 2021-12-03 0.88442 0.88447 2021-12-02 0.88342 0.88343 2021-12-01 0.88261 0.88259 </...
<p>You can use:</p> <pre><code>df['Date'] = pd.to_datetime(df['Date']) df.set_index('Date', inplace=True) df = df.reindex(pd.date_range(df.index.min(), df.index.max())).sort_index(ascending=False).reset_index().rename(columns={'index': 'Date'}) </code></pre> <p><code>OUTPUT</code></p> <pre><code> Date Open ...
pandas|dataframe|date|currency
0
2,602
70,645,072
open_sharded_output_tfrecords causes FailedPreconditionError Writer is not open
<p>I am trying to implement the Tensorflow Detection API following mainly the tutorial and I am running into an issue when trying to generate the <b>TFRecord</b>.</p> <p>I have gotten to a point where I generate the tfexamples and want to write them to a list of tfrecord files. I have seen a <a href="https://www.progra...
<p>The problem is because the writer has exited after the <code>with</code> statement finishes:</p> <pre><code>with contextlib2.ExitStack() as tf_record_close_stack: output_tfrecords = tf_record_creation_util.open_sharded_output_tfrecords( tf_record_close_stack, output_folder_test, num_shards) </cod...
python|tensorflow|object-detection-api
0
2,603
55,999,075
Pandas access the first entry of a series of matrix
<p>I have a pandas df that looks like this:</p> <pre class="lang-py prettyprint-override"><code> beta 0 matrix([[1], [2], [3]]) 1 matrix([[2], [3], [4]]) 2 matrix([[0], [0], [0]]) : 999 matrix([[2], [1], [3]]) </code></pre> <p>And I want to access the first entry of <code>df['beta']</code>, idealy either a l...
<p>I believe you need:</p> <pre><code>df['beta_t'].apply(lambda x: x[0][0][0]) </code></pre> <p>Or:</p> <pre><code>[x[0][0][0] for x in df['beta_t']] </code></pre>
python-3.x|pandas|matrix
1
2,604
55,677,285
How do I return the sum of values from a file?
<p>I am trying to convert a string of plus and minus signs from a file to +1 and -1 respectively, and then print the resulting sum of all of the plus and minus 1's.</p> <p>Here is my attempt at the problem: <a href="https://i.stack.imgur.com/Y5Iqa.png" rel="nofollow noreferrer">Problem statement and attempted code</a>...
<p>You are returning the first operator you come across before iterating through all of them. You should remove both the return statements inside the for loop i.e</p> <pre><code>return num_plus return num_minus </code></pre>
python-3.x|file
-1
2,605
55,685,163
Call pyqt widget from Qt widgets application
<p>I am trying to extend my Qt application with python scripts plugins. It works fine if I call any not pyqt script. It works fine too if I call any pyqt script from c++ function, but I am outside a Qt Widget Application. Something like that:</p> <pre><code>#include "/usr/include/python3.5m/Python.h" int CargaPlugins...
<p>Since you have a QApplication it is not necessary to create another one so the solution is:</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/python # -*- coding: utf-8 -*- import importlib import os import sys from PyQt5 import QtCore, QtGui, QtWidgets from DialogoImprimir import DialogoImprimir def...
python|c++|qt|pyqt|pyqt5
2
2,606
49,855,421
How to convert the string '100+20*50/10-9' to float value using python
<p>Haii friends</p> <p>How can I convert the string expression value to float value ex: <code>s1 = '100+20*50/10-9'</code> this <code>s1</code> convert to <code>float</code> value. Based on the arithmetic operator priority rule it should give 191. But the string expression is not convert to float.</p> <p>I had use <c...
<p>If you are trying to parse a calculation string to a value, you have to evaluate the string first. Like this:</p> <p><code>eval('100+20*50/10-9')</code></p> <p>Then you may convert it to a float like this <code>float(eval('100+20*50/10-9'))</code>.</p> <hr> <p><strong>However</strong>, if the calculation string ...
python-3.x|python-2.7|floating|arithmetic-expressions
3
2,607
49,982,788
Django: Form with multiple inputs is invalid
<p>My template html has the following inputs (multiple):</p> <pre><code>&lt;form method="post" enctype="multipart/form-data"&gt; {% csrf_token %} &lt;input name="image_field" type="file"&gt; &lt;input name="image_field" type="file"&gt; </code></pre> <p>My view is:</p> <pre><code>def add_listing(request): if requ...
<p>I needed to replace <code>image_form = ImageForm(request.FILES)</code> </p> <p>with <code>image_form = ImageForm(request.POST, request.FILES)</code>.</p> <p>I'm not sure why this was required as the <code>listing_form</code> contains only File field, and any explanation would be appreciated!</p>
python|django|django-forms|django-views
0
2,608
64,936,287
Trying to send form data from React.js form to Flask API, yet it doesn't allow to submit to MongoDB
<p>I am trying to make a simple create-User form in order to understand the functions of the API using react.js, python(Flask) and mongodb. However, I keep getting error that none of the input are getting sent to the Flask backend. Any way I can resolve the issue?</p> <p>This is the identity.py where the post get's han...
<pre><code>`await fetch('/user/join', { method: 'POST' })` </code></pre> <p>You are only making a post request and not sending anything to it. That's why nothing is being received on the other end.</p> <p>Refer to this post to know how to send a fetch post request in react. <a href="https://stackoverflow.com/question...
javascript|python|reactjs|mongodb|flask-restful
0
2,609
64,989,289
How to convert a string to a multi-level JSON?
<p>I have an HTML file structured this way:</p> <blockquote> <p>Section 1.1<br /> 1.1.1 random paragraph<br /> 1.1.1.1 random paragraph</p> <p>Section 1.2<br /> 1.2.1 random paragraph<br /> 1.2.1.1 random paragraph<br /> ...</p> <p>Section 11.4 ...<br /> 11.4.12 random paragraph<br /> 11.2.12.1 random paragraph</p> </b...
<p>Your HTML doesn't have a proper format, but it's still possible to achieve the result your after. It does require a bit more work:</p> <pre class="lang-py prettyprint-override"><code>html = &quot;&quot;&quot; &lt;p&gt; &lt;span class=&quot;c1&quot;&gt;Section 1.1.&lt;span class=&quot;c7&quot;&gt;&amp;nbsp;&amp;n...
python|html|json
2
2,610
53,097,331
How to sort first half in ascending and second half in descending order in python?
<p>I have a python list [1,2,3,4,5] I have to print [1,2,3,4,5,5,4,3,2,1].</p> <p>Please suggest how to do in loop(while or for)</p>
<p>As you say it's sorted list (right?), so do:</p> <pre><code>print(l+l[::-1]) </code></pre> <p>Or:</p> <pre><code>print(l+reversed(l)) </code></pre> <p>Both cases, the output is:</p> <pre><code>[1, 2, 3, 4, 5, 5, 4, 3, 2, 1] </code></pre>
python|list|for-loop|while-loop
0
2,611
72,051,838
How to run an existing Django application on aws ec2 instance?
<p>I am trying to run a Django application on AWS Ec2 instance. I've chosen Ubuntu as my platform. After cloning the git repository, and creating a virtual environment, I have installed all apps in my requirements.txt. When I try to the following lines of code <code>python3 manage.py migrate</code> ; <code>python3 mana...
<p>You are missing a running database, the app code except it to be PostgreSQL, you have multiple choices:</p> <ul> <li>Install and run a local PostgreSQL instance directly in your EC2</li> <li>Use Amazon's managed database RDS</li> <li>Use Sqlite which is simple to setup and doesn't require more configuration, but you...
python|django|amazon-web-services|amazon-ec2
3
2,612
68,840,021
How to prevent undetected chromedriver from closing window after last line of code
<p>I am using the <strong>undetected chromedriver</strong> in python selenium, my problem is that it always closes the window after ending the program.</p> <p>For example I have a line of code like:</p> <pre><code>driver.get('www.google.com') </code></pre> <p>It obviously opens google but then immediately closes the wi...
<p>I simply add a time.sleep(100) function, or kill the kernel</p>
python|selenium|web-scraping|selenium-chromedriver|undetected-chromedriver
0
2,613
10,289,242
One-to-many relationships SQLAlchemy that depend on each other
<p>I'm trying to get the following models working together. Firstly the scenario is as follows: </p> <ol> <li>A user can have many email addresses, but each email address can only be associated with one user;</li> <li>Each user can only have one <em>primary email address</em> (think of it like their current email addr...
<p>You have already got a pretty good solution, and a small fix will make your code work. Find below the quick feedback on your code below:</p> <ul> <li><strong>Do you need the <code>use_alter=True</code>? No</strong>, you actually do not need that. If the <code>primary_key</code> for the <code>Email</code> table was ...
python|database|database-design|sqlalchemy
5
2,614
62,524,666
Why does subprocess.Popen want a list instead of a string?
<p>I'd like to understand what is going on under the hood in terms of why Popen wants a list instead of a string. Example:</p> <pre><code>cmd_desired = 'func -a arg1 arg2' subprocess.Popen(cmd_desired) # Doesn't work list_cmd = cmd_desired.split() subprocess.Popen(list_cmd) # Works subprocess.Popen(cmd_desired, shel...
<p>The question is erring in that it refers to the contents of <code>dict_cmd</code> as a dictionary. It is a list, for example <code>['func', '-a', 'arg1', 'arg2']</code>. As such, <code>dict_cmd</code> is not a good name for the variable. Renaming it accordingly, we have:</p> <pre><code>cmd_desired = 'func -a arg1...
python
2
2,615
62,023,613
Why does the order of function order matter?
<p>I am having a problem with a function I am trying to fit to some data. I have a model, given by the equation inside the function which I am using to find a value for v. However, the order in which I write the variables in the function definition greatly effects the value the fit gives for v. If, as in the code block...
<p>Have a look at the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html?highlight=curve_fit#scipy.optimize.curve_fit" rel="nofollow noreferrer">documentation</a> again, it says that the callable that you pass to <code>curve_fit</code> (the function you are trying to fit) must t...
python|curve-fitting|scipy-optimize
0
2,616
61,667,274
Plotting multiple countplots using seaborn
<p>I have categorical variables in my data set, most of them are binary 0,1 but some are multi-class. I used <code>countplot</code> to plot the distribution.</p> <pre><code>f, axes = plt.subplots(4,3,figsize=(17,13), sharex=True) for i, feature in enumerate(cat_var_list): sns.countplot(df[feature],ax=axes[i%4, i//...
<p>I see your code works as expected with this sample data:</p> <pre><code>np.random.seed(1) df = pd.DataFrame(np.random.choice([0,1], (100,11)), columns=list('abcdefABCDE')) df['F'] = np.random.choice([0,1,2], 100) cat_var_list = 'abcdefABCDEF' f, axes = plt.subplots(4,3,figsize=(17,13), sharex=Tr...
python-3.x|matplotlib|seaborn
2
2,617
60,652,773
How to sort dictionary of sets by using length to sort them?
<p>Key Is a number and value of key is a set i want to sort them according to length of sets? </p> <pre><code>Ans={} for i in range(N): x=set(x for x in range(1,N+1)) Ans[i+1]=x </code></pre> <p>In later stages of code this dictionary will have values of variable length and I want to sort them ...
<p>If you want to sort the dictionary which is a <code>int-&gt;set</code> mapping, this piece of code should be enough</p> <pre><code>Ans = {item[0]:item[1] for item in sorted(Ans.items(), key= lambda x: len(x[1]))} </code></pre> <p>It converts the dictionary to a tuple sorted on values, and build the dictionary from...
python|python-3.x|set
0
2,618
71,229,984
building a prefect pipeline to run tasks forever
<p>I am having trouble building a prefect pipeline. Suppose I have a file, call it streamA.py and streamB.py. The purpose of these two files, is to stream data continuously 24/7 and push data into a redis stream once every 500 records streamed.<br /> I created another file called redis_to_postgres.py that grabs all t...
<p>An interesting use case! Are you asking this for Prefect ≤ 1.0 or for Orion? For Orion, there is a <a href="https://www.prefect.io/blog/you-no-longer-need-two-separate-systems-for-batch-processing-and-streaming/" rel="nofollow noreferrer">blog post</a> that discusses the problem in more detail and shows example flow...
python-3.x|prefect
2
2,619
11,184,751
How to do loop in Python Map?
<p>I want to do a loop in a map. My code is like this: </p> <pre><code>for (abcID,bbbID) in map(abcIdList,bbbIdList): buildXml(abcID,bbbID) </code></pre> <p>How should I do to make this work?</p>
<p>Uh, I think you want <code>zip()</code> instead...</p> <pre><code>&gt;&gt;&gt; zip((1, 2), ('a', 'b')) [(1, 'a'), (2, 'b')] </code></pre>
python|loops|map
4
2,620
11,249,313
store openid user in cookie google appengine
<p>I am using OpenID as a login system for a google appengine website and I right now for every website I am just passing the user info to every page using <code>user = users.get_current_user()</code></p> <p>Would using a cookie to do this be more efficient? (I know if would be easier that putting that in every singl...
<p><code>users.get_current_user()</code> is actually reading the cookies so you don't need to do anything more to optimize it (you can easily verify it by deleting your cookies and then refreshing the page). Unless you want to store more information and have access to them without accessing the datastore on every reque...
python|google-app-engine|cookies|openid
1
2,621
69,842,510
how to read the Azure blob file with Azure function in python?
<p>I am new in Azure cloud. Now I hope to create a work flow: upload a audio file to the blob --&gt; Blob trigger is invoked --&gt; deployed python function read the upload audio file and extract harmonics --&gt; harmonics output as json file and save in another container. Blow is my code but it doesn't work:</p> <pre ...
<p>The input binding allows you to read blob storage data as input to an Azure Function.</p> <p>For more details refer this document : <a href="https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-blob-input?tabs=python" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/azure/azur...
python|audio|azure-functions|azure-blob-storage
0
2,622
18,010,077
Make elements in Pandas rows
<p>I have a pandas table df:</p> <pre><code> course ID 1 physics101 1 astronomy 2 maths 2 another </code></pre> <p>I'd like to derive a table that has the following result:</p> <pre><code> physics101 astronomy maths another ID 1 True ...
<p>You can use <code>crosstab()</code>:</p> <pre><code>import pandas as pd from StringIO import StringIO data = StringIO("""ID course 1 physics101 1 astronomy 2 maths 2 another""") df = pd.read_csv(data, delim_whitespace=True) pd.crosstab(df.ID, df.course) &gt; 0 </code></pre> ...
pandas
3
2,623
61,045,578
ModuleNotFoundError: No module named 'requests' even after pip installed requests in Pycharm
<p>Previously "requests" library was working, but I wanted to do a project and install a few libraries and "requests==2.22.0" was included among the libraries. After installing the libraries, I found out I get an error on PyCharm:</p> <pre><code>Traceback (most recent call last): File "C:/Users/User/Desktop/python/p...
<p>You have not configured Python interpreter for PyCharm. Follow <a href="https://www.jetbrains.com/help/pycharm/configuring-python-interpreter.html" rel="nofollow noreferrer">this tutorial</a> and you should be fine. I'd recommend to use Anaconda and create a <a href="https://docs.conda.io/projects/conda/en/latest/us...
python|pip
2
2,624
60,807,978
FileNotFoundError: No such file or directory ERROR
<pre><code>football_players = [] while True: print(""" ******************* CHOOSE OPERATION: 1. ADD FOOTBALLER (NAME SURNAME, FOOTBALL TEAM) 2. SHOW ME PLAYERS OF FENERBAHÇE TEAM 3. SHOW ME PLAYERS OF GALATASARAY TEAM ENTER 'q' to quit... ******************* """) operati...
<p>You are trying to open a file </p> <pre><code>with open("fenerbahçe_players.txt", "r", encoding = "utf-8") as file2:``` </code></pre> <p>But that file does not exist.</p>
python
0
2,625
60,896,223
How to resize image in CV2 image in Colab Editor
<p>I am trying to resize an image in cv2 in Colab editor, but I am getting the below error. Can anyone help me to debug this error?</p> <p>My code:</p> <pre><code>img= cv2.imread(&quot;/content/drive/My Drive/DL_DATAset/Autotag/Test Image/image100.jpg&quot;) height = 220 width = 220 dim = (width, height) res = cv2.resi...
<p>The error simply means that the image cannot be loaded/read. It's coming from this line here</p> <pre><code>img= cv2.imread("/content/drive/My Drive/DL_DATAset/Autotag/Test Image/image100.jpg") </code></pre> <p><strong>Path: The image should be in the working directory or a full path of image should be given.</str...
python|opencv|resize
0
2,626
68,908,344
When I save a PySpark DataFrame with saveAsTable in AWS EMR Studio, where does it get saved?
<p>I can save a dataframe using <code>df.write.saveAsTable('tableName')</code> and read the subsequent table with <code>spark.table('tableName')</code> but I'm not sure where the table is actually getting saved?</p>
<p>It is stored under the default location of your database.</p> <p>You can get the location by running the following spark sql query:</p> <p><code>spark.sql(&quot;DESCRIBE TABLE EXTENDED tableName&quot;)</code></p> <p>You can find the <code>Location</code> under the <code># Detailed Table Information</code> section. P...
python|amazon-web-services|pyspark|amazon-emr|aws-emr-studio
1
2,627
68,875,418
workbook save failing, not sure why
<p>I apologize for the length of this. I am a relative Neophyte to Excel VBA and even more junior with Python. I have run into an issue with an error that occasionally occurs in python using OpenPyXl (just trying that for the first time).</p> <p>Background: I have a series of python scripts (12) running and querying...
<p>Not sure if this is the best way, but the comment from simpleApp gave me an idea that I may want to use a technique I used elsewhere in the VBA. Since I am new to these tools, perhaps someone can suggest a cleaner approach, but I am going to try using a semaphore file to signal when I am copying the file to alert t...
python|python-3.x|excel|vba|openpyxl
0
2,628
59,300,559
NoSuchElementException: no such element: Unable to locate element: css selector but im using find_element
<p>I used selenium IDE to trace my UI activity. I got this following code from IDE and i inspected in UI also,but while using find_element by id i'm getting css selector error.</p> <pre><code>driver.find_element(By.ID, "button-1034-btnIconEl").click() </code></pre> <p>error is</p> <blockquote> <p>raise exception_c...
<p>The id seems to be dynamic one so you cannot use static id in the selector. You need to use a dynamic xpath for this.<br> You can use the below xpath:</p> <pre><code>driver.find_element(By.XPATH, "//span[contains(@id,'btnIconEl')]").click() </code></pre> <p>OR </p> <p>You can find the element using its text as...
python|selenium-webdriver|selenium-chromedriver|selenium-ide
0
2,629
73,121,199
How do I make .tmp files (of a given size) with batch and Python
<p>I am trying to make 20 .tmp files in batch or python. I have been looking through everything and cant find a solution. I want the .tmp files to store in <code>C:\Users\%USERNAME%\AppData\Local\Temp</code> here is the code.</p> <p>Python:</p> <pre><code>import tempfile # This makes a .tmp file but only 0kb i want lik...
<p>Whilst the question has already been answered, and a <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> solution accepted, the OP did also include the <a href="/questions/tagged/batch-file" class="post-tag" title="show questions tagged &#39;batch-f...
python|batch-file
1
2,630
63,280,121
Create CSV from irregular list of dictionaries in python
<p>I have a list of dictionaries like</p> <pre><code>[ {'AB Code': 'Test AB Code', 'Created': '2020-08-04 13:20:55.196500+00:00'}, {'AB Code': 'Test AB Code', 'Created': '2020-08-04 13:20:11.315136+00:00', 'Name': 'John Doe', 'Email': 'john@example.com', 'Phone No.': '1234567890', 'Age': '31'} ] </code></pre> <p>Th...
<p>There is answer using <code>pandas</code> provided by @bigbounty in comments to the question. Here is solution using just standard library</p> <pre><code>import csv from collections import ChainMap data = [ {'AB Code': 'Test AB Code', 'Created': '2020-08-04 13:20:55.196500+00:00'}, {'AB Code': 'Test AB Code', '...
python|csv
2
2,631
63,083,744
I can't install streamlit with pip
<p>I am running python 3.8.2 and pip 20.1.1 on Windows 10. When I try to install streamlit with <code>pip install streamlit</code> I get a long list of errors that appear in the console. Some of the errors seem to say that it needs to be installed on a python version &lt; 3.7, however streamlit is supposed to work for ...
<p>After reading about a similar <a href="https://github.com/numpy/numpy/issues/12016" rel="nofollow noreferrer">issue</a> as yours, they recommended Python 3.7 as it is not quite stable for 3.8.</p> <p>Another solution one of the user provided:</p> <blockquote> <p>I was able to fix it by installing two visual studio d...
python|pip|streamlit
3
2,632
62,455,488
RNN, Keras, Python: Min Max Scaler Data normalization ValueError: Found array with dim 3. Estimator expected <= 2
<p>I prepared a simple dataset and labels set. I want to learn how can I implement simple RNN in Keras. I prepared my data. When I do not use normalization (MinMaxScaler) everything compiles without errors. </p> <p>However, when I try to use the scaler, I got <code>ValueError: Found array with dim 3. Estimator expecte...
<p>this is because you are passing 3d sequences to minmaxscaler. it accepts 2d sequences. what you have to do is to transform your prediction in 2d and then return to 3d. this can be done in one line...</p> <pre><code>test_predictions = min_max_scaler.inverse_transform(test_predictions.reshape(-1,1)).reshape(test_pred...
python|numpy|tensorflow|machine-learning|keras
1
2,633
62,444,516
nanmean with weights to calculate weighted average in pandas .agg
<p>I'm using a lambda function in a pandas aggregation to calculate the weighted average. My issue is that if one of the values is nan, the whole result is nan of that group. How can I avoid this?</p> <pre><code>df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', 'h'],columns = ['one', 'two', 'three'])...
<p>For me working implemented <a href="https://stackoverflow.com/a/21113467">this</a> solution:</p> <pre><code>def f(x): indices = ~np.isnan(x) return np.average(x[indices], weights=df.loc[x.index[indices], 'two']) df = df.groupby('four').agg(sum=('two','sum'), weighted_avg=('one', f)) print (df) ...
pandas|numpy|pandas-groupby|weighted-average
2
2,634
62,416,223
How to select only few columns in scikit learn column selector pipeline?
<p>I was reading the scikitlearn tutorial about column transformer. The given example (<a href="https://scikit-learn.org/stable/modules/generated/sklearn.compose.make_column_selector.html#sklearn.compose.make_column_selector" rel="noreferrer">https://scikit-learn.org/stable/modules/generated/sklearn.compose.make_column...
<p>If you don't mind <code>mlxtend</code>, it has built-in transformer for that.</p> <h1>Using mlxtend</h1> <pre><code>from mlxtend.feature_selection import ColumnSelector pipe = ColumnSelector(mycols) pipe.fit_transform(df) </code></pre> <h1>For sklearn &gt;= 0.20</h1> <ul> <li>Reference: <a href="https://scikit-lear...
python|pandas|scikit-learn
13
2,635
35,490,075
making dictionary from some logic
<p>team 'A' , 'B' and 'C' did consecutive goals 12, 1, and 9 times respectively.</p> <pre><code>teams = ['A','B','C'] goals = [12,1,9] </code></pre> <p>Which team did 5th goal? Answer is team 'A'. Which team did 13th goal? Answer is team 'B'. Which team did 21th goal? Answer is team 'C'.</p> <p>I want to make dicti...
<pre><code>&gt;&gt;&gt; teams = ['A','B','C'] &gt;&gt;&gt; goals = [12,1,9] &gt;&gt;&gt; d = dict(enumerate([t for t,g in zip(teams, goals) for _ in range(g)], 1)) &gt;&gt;&gt; d[5] 'A' &gt;&gt;&gt; d[13] 'B' &gt;&gt;&gt; d[21] 'C' </code></pre> <p>This is roughly equivalent to:</p> <pre><code>d = {} count = 1 for te...
python
1
2,636
58,932,664
What is happening with torch.Tensor.add_?
<p>I'm looking at this implementation of SGD for PyTorch: <a href="https://pytorch.org/docs/stable/_modules/torch/optim/sgd.html#SGD" rel="noreferrer">https://pytorch.org/docs/stable/_modules/torch/optim/sgd.html#SGD</a> </p> <p>And I see some strange calculations which I don't understand. </p> <p>For instance, ta...
<p>This works for scalars:</p> <pre><code>a = t.tensor(1) b = t.tensor(2) c = t.tensor(3) a.add_(b, c) print(a) </code></pre> <blockquote> <p>tensor(7)</p> </blockquote> <p>Or <code>a</code> can be a tensor:</p> <pre><code>a = t.tensor([[1,1],[1,1]]) b = t.tensor(2) c = t.tensor(3) a.add_(b, c) print(a) </code></...
pytorch
3
2,637
59,016,634
format date from excel to dd-Mmm-yyyy to Python
<p>I have pulled date from excel to python , when I print the date is shows like "2019-11-28 00:00:00" . I want to again pass this date to python program in format 24-Nov-2019. How to do it ?</p>
<p>Here's a function that will do the job:</p> <pre class="lang-py prettyprint-override"><code>from datetime import datetime def excel_to_formatted_date(input_date): return datetime.fromisoformat(input_date).strftime('%d-%b-%Y') </code></pre> <p>Testing with your value gives the following:</p> <pre><code>&gt;&gt...
python|excel
0
2,638
31,433,422
/usr/include folder missing in mac
<p>I've tried pretty much everything on stackoverflow and other forums to get the /usr/include/ folder on my mac (currently using OS X 10.9.5)</p> <ol> <li>Re-installed Xcode and command line tools (actually, command line tool wasn't one of the downloads available - so I'm guessing it's was already downloaded)</li> <l...
<p>Try on 10.14:</p> <p><code>sudo installer -pkg /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg -target /</code></p>
python|xcode|macos|terminal
4
2,639
15,572,288
General decorator to wrap try except in python?
<p>I'd interacting with a lot of deeply nested json I didn't write, and would like to make my python script more 'forgiving' to invalid input. I find myself writing involved try-except blocks, and would rather just wrap the dubious function up.</p> <p>I understand it's a bad policy to swallow exceptions, but I'd rathe...
<p>You could use a defaultdict and <a href="https://speakerdeck.com/pyconslides/transforming-code-into-beautiful-idiomatic-python-by-raymond-hettinger-1">the context manager approach as outlined in Raymond Hettinger's PyCon 2013 presentation</a></p> <pre><code>from collections import defaultdict from contextlib import...
python|try-catch|wrapper|decorator
47
2,640
59,576,531
How to combine groupby and sort values
<p>How to merge two groupby and sort_values in to one </p> <p><code>df_most_ordered = online_rt.groupby(by=['Country']).sum()</code></p> <p><code>df_most_ordered.sort_values(['Quantity'],ascending=False).iloc[1:11]</code></p>
<p>You can use <a href="https://tomaugspurger.github.io/method-chaining.html" rel="nofollow noreferrer">method chaining</a>:</p> <pre><code>online_rt.groupby(by=["Country"]).sum().sort_values( ["Quantity"], ascending=False ).iloc[1:11] </code></pre>
pandas
2
2,641
59,781,313
Is it possible to reuse import code in Python?
<p>There are several imports that are common between some files in my project. I would like to reuse this code, concentrating it in a unique file and have just one import in the other files. Is it possible?</p> <p>Or is there another way not to replicate the desired import list in multiple files?</p>
<p>Yes its possible. You can create a Python file with imports and then import that Python file in your code.</p> <p>For Eg:</p> <p><strong>ImportFile.py</strong></p> <pre><code>import pandas as pd import numpy as np import os </code></pre> <p><strong>MainCode.py:</strong></p> <pre><code>from ImportFile import * #Here...
python|import|python-import|code-reuse
2
2,642
59,580,914
Data frame indexing not working as it should be. Does not give error as well. Pandas-Python
<p>Lets say we have a dataframe: '''</p> <pre><code>df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(), 'B': 'one one two three two two one three'.split(), 'C': np.arange(8), 'D': np.arange(8)**2}) df </code></pre> <p>'''</p> <p>I am trying to set Values of column...
<p>Since <code>C</code> contains a single value , you would need an OR instead of an and, please use:</p> <pre><code>df.loc[(df['C']&lt;2) | (df['C']&gt;5),'C']=np.nan </code></pre>
python-3.x|pandas|dataframe
0
2,643
66,980,359
Migrating ctypes function from Python 2 to Python 3
<p>In case this is a XY problem, here is what i want to do:</p> <p>I have a wxPython app, that has to communicate with another process using the WM_COPYDATA windows message. While sending the message with the <code>ctypes</code> module was surprisingly easy, receiving the answer requires me to overwrite the wx loop, si...
<p>One problem is here:</p> <pre class="lang-py prettyprint-override"><code>_LONG_PTR = ctypes.c_long _LRESULT = _LONG_PTR </code></pre> <p>The type <code>LONG_PTR</code> is &quot;an integer the size of a pointer&quot;, which varies between 32-bit and 64-bit processes. Since you are using 64-bit Python, pointers are 6...
python|python-3.x|python-2.7|wxpython|ctypes
1
2,644
67,087,296
How to convert a list into 3 digits in Python?
<p>I need to calculate every 3 digits of my decimal input. I have a code like this:</p> <pre><code>decimal = 136462380542525933949347185849942359177 #Encryption e = 79 n = 3337 def mod(x,y): if (x&lt;y): return x else: c = x%y return c def enkripsi(m): deci...
<p>you're almost there:</p> <pre><code>def decimal2list(num, length=3): string = str(num) return [int(string[i:i+length]) for i in range(0, len(string), length)] </code></pre>
python|list
2
2,645
42,923,514
How to improve performance of converting data to json format?
<p>I have the following code to convert a data(row data from postgress) to json. Usually <code>len(data) = 100 000</code></p> <pre><code>def convert_to_json(self, data): s3 = self.session.client('s3') infos = { 'videos':[], 'total_count': len(data) } for row in data: video_id =...
<p>Most of the time in your program is probably wasted by <em>waiting</em> for the network. Indeed you call <code>s3.generate_presigned_url</code> which will send a request to Amazon and then you have to wait until the server finally responds. In the meantime there is no much processing you can do.</p> <p>So the most ...
python|json|algorithm|amazon-s3
1
2,646
72,270,500
Customize ListItem contains colorful label, colorful label background not show?
<p>I customize <code>QListView</code> and <code>ListItem</code>, the <code>ListItem</code> contain colorful label,but the colorful label not working?I can't find why the <code>QLabel</code> not show it's color.</p> <p><strong>Demo code</strong></p> <pre class="lang-py prettyprint-override"><code>from qtpy.QtWidgets imp...
<p>You have to use <code>Base</code> instead of <code>Window</code>:</p> <pre class="lang-py prettyprint-override"><code>def setLabelColor(self, color): pal = self._colorLabel.palette() pal.setColor(QPalette.Base, color) self._colorLabel.setPalette(pal) </code></pre>
python-3.x|pyqt|qlistwidget
3
2,647
65,605,688
Output of interactive python to shell variable
<p>There is an interactive python script something like</p> <pre><code>def myfunc(): print(&quot;enter value between 1 to 10&quot;) i=int(input()) if(i&lt;1 or i&gt;10): print(&quot;again&quot;) myfunc() else: print(i) </code></pre> <p>I want to store the final output which is <c...
<p>If you are working on Linux or other Unix variants, would you please try:</p> <pre><code>import os def myfunc(): tty = os.open(&quot;/dev/tty&quot;, os.O_WRONLY) os.write(tty, &quot;enter value between 1 to 10\n&quot;) i=int(input()) if(i&lt;1 or i&gt;10): os.write(tty, &quot;again\n&quot;) ...
python
2
2,648
34,910,086
Pygame. How do I resize a surface and keep all objects within proportionate to the new window size?
<p>If I set a pygame window to resizable and then click and drag on the border of the window the window will get larger but nothing blit onto the surface will get larger with it. (Which is understandable) How would I make it so that when I resize a window all blit objects resize with it and fill the window properly?</p...
<p>Don't draw on the screen directly, but on another surface. Then scale that other surface to size of the screen and blit it on the screen.</p> <p>Here's a simple example:</p> <pre><code>import pygame from pygame.locals import * def main(): pygame.init() screen = pygame.display.set_mode((200, 200),HWSURFACE|D...
python|pygame|resizable|surface|blit
11
2,649
26,921,294
Sorting a list of dictionaries by key in Python
<p>I have a list of dictionaries in Python which each contain just one numerical key, and I want to sort them by their keys. Example: </p> <pre><code>list = [{.56: 'a'}, {1.0: 'a'}, {.98: 'b'}, {1.0: 'c'}] </code></pre> <p>I want to sort this and return something like this:</p> <pre><code>[{1.0: 'a'}, {1.0: 'c'}, {...
<p>This is a simplified version of @dkamins</p> <pre><code>&gt;&gt;&gt; lst = [{.56: 'a'}, {1.0: 'a'}, {.98: 'b'}, {1.0: 'c'}] &gt;&gt;&gt; sorted(lst, key=max, reverse=True) [{1.0: 'a'}, {1.0: 'c'}, {0.98: 'b'}, {0.56: 'a'}] </code></pre> <p>recall that <code>max(d.keys())</code> returns the same result as <code>max...
python|list|sorting
3
2,650
56,841,548
How to fix "Invalid encoding' error in python 3?
<p>I was creating a python-based shell where I used one latin-1 character: "└──>". So I tried this:</p> <pre><code>~python 3.8 # -*- coding: latin-1 -*- input_prompt = input(''' └──&gt; ''') </code></pre> <p>But it gave me error:</p> <pre><code>Invalid encoding 'latin-1' Saving as 'UTF-8' </code></pre> <p>Why do...
<p>The prompt string is not composed of characters that can be represented in latin-1, hence the error:</p> <pre><code>&gt;&gt;&gt; s = '''└──&gt;''' &gt;&gt;&gt; import unicodedata as ud &gt;&gt;&gt; for c in s:print(ud.name(c)) ... BOX DRAWINGS LIGHT UP AND RIGHT BOX DRAWINGS LIGHT HORIZONTAL BOX DRAWINGS LIGHT HOR...
python|python-3.x|utf-8|encode|iso-8859-1
0
2,651
64,912,543
How to write data in a specific tab of a spreadsheet with the Google Sheets API in Python?
<p>I'm writing data in a Google Sheet using this function :</p> <pre><code>def Export_Data_To_Sheets(df): response_date = service.spreadsheets.values().update( spreadsheetId=SAMPLE_SPREADSHEET_ID_input, valueInputOption='RAW', range=SAMPLE_RANGE_NAME, body=dict( majorDimension='ROWS', v...
<p>In this point in the code:</p> <pre><code>range=SAMPLE_RANGE_NAME </code></pre> <p>You can replace this value with a sheet and cell reference, something like:</p> <pre><code>range=&quot;Sheet1!A1:D5&quot; </code></pre> <p>Reference</p> <ul> <li><a href="https://developers.google.com/sheets/api/samples/writing" rel="...
python|google-sheets|google-sheets-api
0
2,652
60,614,948
How to iteratively nest a nested function
<p>I have an array <code>arr_multi_dim</code> which is multi-dimensional. Every time when I increase a parameter n, there will be more entries created in the array results and the array will get larger.</p> <p>With each increase in <code>n</code>, I need to perform the function <code>np.concatenate()</code> on the arr...
<p>If i understood you correctly its pretty simple:</p> <pre><code>arr_multi_dim = results for i in range(n): if i &lt; 2: arr_multi_dim = np.concatenate(arr_multi_dim , axis=1) else: arr_multi_dim = np.concatenate(np.concatenate(arr_multi_dim , axis=1), axis=1) </code></pre> <p>becase the first two itera...
python|numpy|loops|for-loop|concatenation
1
2,653
58,135,953
How to get the stack trace of a nested exeption in python?
<p>If an exception is raised I'd like to analyse the stack trace in python that tells about where exactly the problem is in the source code file.</p> <p>Of course for that purpose the module <code>traceback</code> exists. And that works fine for regular exceptions. But how do you deal with this situation if nested exc...
<p>There is a variable named <code>__context__</code> associated with an exception. This variable can be used to access nested exceptions. See this example:</p> <pre class="lang-py prettyprint-override"><code>import traceback def test(): try: a = 0 b = 5 / a except Exception as ee1: as...
python|exception|stack|traceback
0
2,654
56,374,425
Web-scraping articles from WSJ using Beautifulsoup in python 3.7?
<p>I am trying to scrape articles from the Wall Street Journal using Beautifulsoup in Python. However, the code which I am running is executing without any error (exit code 0) but no results. I don't understand what is happening? Why this code is not giving expected results.</p> <p>I even have paid a subscription.</p> ...
<p>Replace your code :</p> <pre><code>resp = requests.get(item.get("href")) </code></pre> <p>To:</p> <pre><code>_href = item.get("href") try: resp = requests.get(_href) except Exception as e: try: resp = requests.get("https://www.wsj.com"+_href) except Exception as e: continue </code></p...
python|web-scraping|beautifulsoup
5
2,655
71,486,983
Value Error: could not convert string to float: 'good'
<p>I am trying to fit a decision tree model with the training dataset. But finding this error</p> <pre><code>credit_df=pd.read_csv('credit.csv') credit_df.head() </code></pre> <p>[! <a href="https://i.stack.imgur.com/04z5P.png" rel="nofollow noreferrer">dataframe</a>]<a href="https://i.stack.imgur.com/04z5P.png" rel="n...
<p>I tried the code below and now the error is fixed. There were some object data types and i converted them into categorical values</p> <pre><code>for feature in credit_df.columns: if credit_df[feature].dtype == 'object': credit_df[feature] = pd.Categorical(credit_df[feature]).codes </code></pre>
python|decision-tree|valueerror
0
2,656
69,443,812
Highlight or bold strings in a text file using python-docx?
<p>I have a list of 'short strings', such as:</p> <p>['MKWVTFISLLLLFSSAYSRGV', 'SSAYSRGVFRRDTHKSEIAH', 'KPKATEEQLKTVMENFVAFVDKCCA']</p> <p>That I need to match to a 'long string' contained in a word file (BSA.docx) or .txt file (does not matter) such as:</p> <blockquote> <p>sp|P02769|ALBU_BOVIN Albumin OS=Bos taurus OX...
<p>You can use the <a href="https://pypi.org/project/regex/" rel="nofollow noreferrer">third-party <code>regex</code> module</a> to do an overlapping keyword search. Then, it is perhaps easiest to go through the matches in 2 passes: (1) storing the start and end positions of each highlighted segment and combining any t...
python|text|highlight
1
2,657
55,539,617
Qt Designer Auto Fitting the tableWidget directly from the Designer
<p>I am trying to auto fit the <code>tableWidget</code> columns to the available area of the <code>tableWidget</code></p> <p>Currently my layout looks like the picture below. As can be seen there is unnecessary white space to the right which I would like to fill out evenly between the four columns.</p> <p><a href="ht...
<p>The feature you indicate can not be done with Qt Designer. In Qt Designer, only the Q_PROPERTY enabled by the DESIGNABLE flag can be modified, but <code>setSectionResizeMode()</code> is not a Q_PROPERTY but a method of QHeaderView, that is indicated in the <a href="https://doc.qt.io/qt-5/properties.html#requirements...
python|python-3.x|pyqt|pyqt5|qt-designer
3
2,658
53,814,044
Kosaraju's Algorithm for SCCs, non-recursive
<p>I have an implementation of Kosaraju's algorithm for finding SCCs in Python. The code below contains a recursive (fine on the small test cases) version and a non-recursive one (which I ultimately need because of the size of the real dataset).</p> <p>I have run both the recursive and non-recursive version on a few t...
<p>Ok, I figured out the missing cases. The algorithm wasn't performing correctly on very strongly connected graphs and duplicated edges. Here is an adjusted version of the test case I posted above with a duplicated edge and more edges to turn the whole graph into one big SCC.</p> <pre><code>1 5 1 4 2 3 2 6 2 11 3 2 3...
python|recursion|graph-theory|depth-first-search|kosaraju-algorithm
0
2,659
53,820,926
Python Compare Dataframe columns and replace with contents based on prefix
<p>Still relatively new to working in python and am having some issues.</p> <p>I currently have a small program that takes csv files, merges them, puts them into a data frame, and then converts to excel.</p> <p>What I want to do is match the values of 'Team' and 'Abrev' from the data frame columns based on the prefix...
<p><code>pandas</code> is what you are looking for import pandas as pd</p> <pre><code>df = pd.read_csv('input.csv') df['team'] = df['Abrev'] df.drop('Abrev', axis=1, inplace=True) df.to_excel('output.xls') </code></pre>
python|csv|dataframe|match|multiple-columns
0
2,660
54,237,418
Pandas pd.concat works on first pass but says 'No objects to concat' on subsequent passes
<p>I have an interesting problem with Python PANDAS leveraging concat.</p> <p>On the first pass everything works fine on the subsequent passes I receive "No objects to concat". It doesn't make sense because it's looking at the same "CSV's" on each run so in theory there should always be something to "concat" </p> <p>...
<p>Your list_ is empty which is what is throwing that error. You should look at the csv's in allFiles. Are you moving the csv's or are they getting renamed in the directory?</p>
python|pandas|concat
0
2,661
58,351,057
Python: split into lines and remove specific line based on search
<p>i have a csv file like below, and with my little python knowledge i am trying to split its content into lines based "sec" as start field and remove specific lines which has field with sip:+99*, sip:+88*, sip:+77*.</p> <p>cat text.csv</p> <pre><code>sec,sip:+1111,2222,3333,4444,5555,sec,6666,sip:+7777,8888,sec,sip:...
<p>Python:</p> <pre><code>import re s = 'sec,sip:+1111,2222,3333,4444,5555,sec,6666,sip:+7777,8888,sec,sip:+9999,1000,1100,110,1200,1300,1400' pos = [m.start() for m in re.finditer('sec', s)] i = 0 start_idx = end_idx = None raw_data = [] while i &lt; len(pos)-1: start_idx = pos[i] end_idx = pos[i+1]-1 ...
python|regex|python-3.x|linux|unix
0
2,662
58,488,731
C++ python module (based on Pybind11) import error: ModuleNotFoundError
<p>A C++ python module based on pybind11 library cannot be imported anymore in python. It was working until a few weeks ago but not any more (may be since the installation of miniconda). Cannot track the exact point when this stopped working as I was not using it since many weeks. I start python in the same directory a...
<p>As is, many times the case, if nothing really works, a restart would definitely do. I did that and seems to solve the case. Never the less, im just relieved it is loading now. </p>
python|conda|miniconda|pybind11
1
2,663
58,544,971
How To Extract Three Letters Followed By Five Digits Using Regex in Python
<p>I have the following dataframe in Python:</p> <p>abc12345 </p> <p>abc1234</p> <p>abc1324.</p> <p>How do I extract only the ones that have three letters followed by five digits? </p> <p>The desired result would be:</p> <p>abc12345.</p> <pre><code>df.column.str.extract('[^0-9](\d\d\d\d\d)$') </code></pre> <p>I...
<p>You should be able to use:</p> <pre><code>'[a-zA-Z]{3}\d{5}' </code></pre> <p>If the strings don't include capital letters this can reduce to:</p> <pre><code>'[a-z]{3}\d{5}' </code></pre> <p>Change the values in the <code>{x}</code> to adjust the number of chars to capture.</p>
python|regex
3
2,664
58,283,975
Elegant way to drop records in pandas based on size/count of a record
<p><strong>This isn't a duplicate. I am not trying drop rows based on Index</strong></p> <p>I have a dataframe like as shown below</p> <pre><code>df = pd.DataFrame({ 'subject_id':[1,1,1,1,1,1,1,2,2,2,2,2], 'time_1' :['2173-04-03 12:35:00','2173-04-03 12:50:00','2173-04-05 12:59:00','2173-05-04 13:14:00','2173-05-05 ...
<p>Use:</p> <pre><code>df[df.groupby('subject_id')['subject_id'].transform('size')&gt;5] </code></pre> <p>Output:</p> <pre><code> subject_id time_1 val day 0 1 2173-04-03 12:35:00 5 3 1 1 2173-04-03 12:50:00 2 3 2 1 2173-04-05 12:59:00 3 5 3 ...
python|python-3.x|pandas|dataframe|pandas-groupby
3
2,665
58,215,034
Implementation of Python code which uses Tensorflow library into HTML?
<p>Machine learning beginner here. I've been following the tensorflow text classification tutorial. I have code which uses a trained keras model to classify movie reviews based on user inputted text.</p> <p>My main question is this: How do I integrate this code into html so that I can create a website which takes in u...
<p>You can use <a href="https://www.fullstackpython.com/flask.html" rel="nofollow noreferrer">Flask</a> to make a Web App that gets the data via a Form POST and do you thing with the tensorflow and display the results in another Page.</p> <p>Something Like</p> <pre class="lang-py prettyprint-override"><code>from flas...
javascript|python|html|tensorflow|keras
1
2,666
65,386,338
Missing modules when running Jupyter notebook on aws
<p>I'm running a Jupyter notebook on a virtual machine on AWS, and I am having issues loading modules. Apparently the notebook doesn't find the modules (see image below), but these are listed if I give the command <code>!conda list</code>. Does anyone have suggestions on how to fix this? Thanks!</p> <p><a href="https:/...
<p>Try:</p> <pre><code>import sys !{sys.executable} -m pip install &lt;your package&gt; </code></pre> <p><a href="https://jakevdp.github.io/blog/2017/12/05/installing-python-packages-from-jupyter/" rel="nofollow noreferrer">Here</a>’s a link that might help you find some more information on how to install python packa...
python|jupyter-notebook
1
2,667
41,269,220
Can't override the Model Field in Django ModelForm
<p>I'm trying to add a <code>DateTimeWidget</code> and Initial value to the due_date field of my Model, I'm following the documentation as close as I can tell. No matter what I try, I can't get the field declared in my <code>ModelForm</code> class to override my existing field in the Model.</p> <p><a href="https://doc...
<p>In fact you are definfing the field in the wrong place, It should be outside <code>Meta</code> class:</p> <pre><code>class EstRequestModelForm(forms.ModelForm): due_date = forms.DateTimeField(widget=forms.DateTimeInput, initial=due_date) class Meta: model = EstRequest fields = [ ...
python|django|django-forms
11
2,668
41,567,335
The python documentation about format does not match the running results
<p>A word in the python documentation <a href="https://docs.python.org/3/library/string.html#format-specification-mini-language" rel="nofollow noreferrer">Format Specification Mini-Language</a>:</p> <blockquote> <p>A general convention is that an empty format string ("") produces the same result as if you had called...
<p>You have an empty <strong>template</strong>, not an empty <strong>format string</strong>. The format string is the part after the optional <code>:</code> in a <code>{..}</code> placeholder. By completely omitting the placeholder, there is nowhere for the value to placed into.</p> <p>So the following produces the sa...
python|format|string-formatting
4
2,669
6,466,315
how to trim file - for rows which with the same value in two columns, conserve only the row with max in another columns
<p>I am now facing a file trimming problem. I would like to trim rows in a tab-delimited file. </p> <p>The rule is: for rows which with the same value in two columns, preserve only the row with the largest value in the third column. There may be different numbers of such redundant rows defined by two columns. If there...
<p>Here's a solution that will rely on the input file already being sorted appropriately. It will scan line-by-line for lines with similar start (e.g. two first columns identical), check the third column value and preserve the line with the highest value - or the line that came first in the file. When a new start is fo...
python|perl|unix|awk
2
2,670
25,769,621
Python how to compare data like in PHP arrays
<p>I have to compare different operations results on two data sources using Python.</p> <p>For each datasource, I get all tables names. For each table, I get all columns. For each column, I do some 'operations' like getting count(column), sum(column). For example, in PHP, it would have given this type of array:</p> <...
<p>If you want to know if the results are the same, use <code>==</code>. For example</p> <pre><code>dict1 = {'foo':'bar'} dict2 = {'foo':'baz'} dict1 == dict2 # False dict2 = {'foo':'bar'} dict1 == dict2 # True </code></pre>
php|python
0
2,671
44,730,943
fixed error instance object is not callable
<p>I need code for editing user details like first_name , last_name by using APIView Class based. THe serializers.py and views.py are given under but it is not making the changes according to the user details . i am passing token for user authentication. Any assistance will be appreciated.</p> <p><strong><em>Serialize...
<p>This view will work . Thanks Linovia</p> <pre><code>class UserEditProfile(APIView): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) def post(self, request): obj = User.objects.get(id=request.user.id) serializer = UserEdi...
python|django|api|django-rest-framework
0
2,672
23,795,222
How can I run mrjob with no input file?
<p>I have a mrjob program, and just get data from sql database, so I don't need read local file or any input file, however mrjob forces me to 'reading from STDIN', so I just create an empty file as input file. It's really ugly, is there a way to run the job with no input files?</p>
<p>Have you tried piping the output from mysql to mrjob? Something like:</p> <pre><code>mysql -D database -u user &lt; test.sql | python mrjob_script.py </code></pre>
python|mrjob
2
2,673
23,680,643
Remove object from list after lifetime expires
<p>I am creating a program that spawns objects randomly. These objects have a limited lifetime.</p> <p>I create these objects and place them in a list. The objects keep track of how long they exist and eventually expire. They are no longer needed after expiration.</p> <p>I would like to delete the objects after th...
<p>You can use the refCount in case you define "no longer used" as "no other object keeps a reference". Which is a good way, for as no references exist, the object can no longer be accessed and may be disposed of. In fact, Python's garbage collector will do that for you.</p> <p>Where it goes wrong is when you also hav...
python|oop
0
2,674
24,191,799
How do I install the pip package for python on mac osx?
<p>I'm currently stuck on exercise 46 in Zed Shaw's "Learn Python the Hardway". He says I need to install the following python packages: </p> <ol> <li><a href="http://pypi.python.org/pypi/pip" rel="nofollow">pip</a></li> <li><a href="http://pypi.python.org/pypi/distribute" rel="nofollow">distribute</a></li> <li><a hre...
<p>You can do:</p> <pre><code>sudo easy_install pip </code></pre> <p>or install it with homebrew: <a href="http://mxcl.github.io/homebrew/" rel="nofollow">http://mxcl.github.io/homebrew/</a></p> <p>and then:</p> <pre><code>brew install python </code></pre>
python|macos|pip|virtualenv|nose
1
2,675
24,424,495
Python Pyramid not rendering JSON correctly
<p>I am using MongoEngine's <code>to_json</code> method on an object I wish to render in a json-rendered Pyarmid page. I've done lots of json rendering in Pyramid, but not with MongoEngine. MongoEngine's <code>to_json</code> method simple calls <code>json_util.dumps</code>. It all works fine in Python. The problem i...
<p>Thanks to a comment by @AnttiHappala above, I found the problem. MongoEngine's <code>to_json</code> method converts objects to a jsonified string. However, Pyramid needs a json data structure. So, to fix it, I added the following function to my custom renderer:</p> <pre><code>def render_to_json(obj): ret...
python|json|pyramid|mongoengine
0
2,676
35,987,023
How to quickly generate an OpenPGP key pair using GnuPG for testing purposes?
<p>I'm testing some code that uses <a href="https://pypi.python.org/pypi/python-gnupg" rel="nofollow noreferrer"><code>python-gnupg</code></a> to encrypt/sign/decrypt some plaintext, and I'd like to generate a key pair on the fly. GnuPG is (of course) super paranoid in generating the key pair, and it sucks a lot of ent...
<p>Using any method to change <code>/dev/random</code> to pull out of <code>/dev/urandom</code> is totally fine once the entropy pool was initiated with a proper random state (which is not a problem on hardware x86 machines, but might require discussion for other devices). I strongly recommend watching <a href="https:/...
python|python-3.x|gnupg|openpgp
4
2,677
49,601,031
Why Z3 falling at this?
<p>i'm trying to solve this using z3-solver<br> but the proplem is that it gives me wrong values<br> i tried to replace the <code>&gt;&gt;</code> with <code>LShR</code> the values changes but non of them is corrent<br> however i know the value of <code>w</code> should be <code>0x41414141</code> in hex<br> i also tried ...
<p>Python uses arbitrary-size integers, whereas z3 clamps all intermediate results to 32 bits, so F gives different results for Python and z3. You'd need something like</p> <pre><code>def F1(w): return ((w * 31337) ^ (((w * 1337) &amp; 0xffffffff) &gt;&gt; 16)) % 2**32 def F1Z(w): return ((w * 31337) ^ LShR(((...
python|bit-manipulation|z3|z3py|sat-solvers
1
2,678
49,503,850
using filter to add similar values for a list of tuples
<p>I have this list </p> <pre><code>order = [('5464', 39.96), ('8274', 233.82), ('9744', 404.55), ('5464', 89.91), ('9744', 404.55), ('5464', 89.91), ('88112', 274.89), ('8732', 83.93), ('7733', 208.89), ('88112', 199.75)] </code></pre> <p>and it is basically a list of book order number and the to...
<p>You can try itertools with lambda :</p> <pre><code>import itertools order = [('5464', 39.96), ('8274', 233.82), ('9744', 404.55), ('5464', 89.91), ('9744', 404.55), ('5464', 89.91), ('88112', 274.89), ('8732', 83.93), ('7733', 208.89), ('88112', 199.75)] print(list(map(lambda m:(m[0],sum(map(la...
python|python-3.x
0
2,679
21,076,983
Django fandjango migration 4.2
<p>After migration fandjango to version 4.2., I've got an error when I access my facebook application:</p> <p>Exception Value: [u'Enter valid JSON']</p> <p>Exception Location: /usr/local/lib/python2.7/dist-packages/jsonfield/fields.py in pre_init, line 77</p> <p>Trace: </p> <p>/usr/local/lib/python2.7/dist-packages...
<p>Ok, I get it. The problem was with mysql database. The new version added a json field extradata. MySql interpreted it as text field with NULL value. So the problem was that fandjango wanted empty json, not NULL. I have updated the extradata field with '{}' and it's worked. </p> <p>Now I have a standart problem: The...
python|django|facebook|fandjango
1
2,680
21,160,773
How do I make Scrapy print all duplicate urls?
<p>I am getting this message once in the logs: </p> <pre><code>2014-01-16 12:41:45+0100 [mybot] DEBUG: Filtered duplicate request: &lt;GET https://mydomain/someurl&gt; - no more duplicates will be shown (see DUPEFILTER_CLASS) </code></pre> <p>The url was requested using Request() and it says it's a duplicate on the v...
<p>Try exact url with <code>curl -v URL</code> and see if the headers contains a 301 or 302. Alternatively you can try <code>scrapy shell URL</code>.</p> <p>I've seen some sites that redirects to the same page when the parameters are not in the same order or the expected letter case. Scrapy doesn't consider the order ...
python|scrapy
0
2,681
62,735,910
Count list length in a column of a DataFrame
<p>This is my Dataframe:</p> <pre><code>CustomerID InvoiceNo 0 12346.0 [541431, C541433] 1 12347.0 [537626, 542237, 549222, 556201, 562032, 57351] 2 12348.0 [539318, 541998, 548955, 568172] 3 12349.0 [577609] 4 12350.0 [543037] </code></pre> <p>Desired Output:</p> <pre><code> CustomerID InvoiceCount 0 12346....
<p>See if this works:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;InvoiceCount&quot;] = df['InvoiceNo'].str.len() </code></pre>
python|pandas|dataframe
2
2,682
53,424,052
How to convert string extracted by regex to integer in python?
<p>i'm trying to convert string to integer, but it's not that so easier than i'm thinking. </p> <pre><code>content = ''' &lt;entry colname="1" morerows="1" morerowname="2"&gt;&lt;p&gt;111&lt;/p&gt;&lt;/entry&gt; &lt;entry colname="2" rowname="2"&gt;&lt;p&gt;&lt;/p&gt;&lt;/entry&gt;''' morerows = ''.join(re.findall...
<p>I guess there are non-integer characters in the morerows attribute in your real case.</p> <pre><code>How about this: content = ''' &lt;entry colname="1" morerows="1x" morerowname="2"&gt;&lt;p&gt;111&lt;/p&gt;&lt;/entry&gt; &lt;entry colname="1" morerows="1" morerowname="2"&gt;&lt;p&gt;111&lt;/p&gt;&lt;/entry&gt; &...
python|regex
1
2,683
40,972,693
'\n' == 'posix' , '\r\n' == 'nt' (python) is that correct?
<p>I'm writing a python(2.7) script that writes a file and has to run on linux, windows and maybe osx. Unfortunately for compatibility problems I have to use carriage return and line feed in windows style. Is that ok if I assume:</p> <pre><code>str = someFunc.returnA_longText() with open('file','w') as f: if os.nam...
<p>Python file objects can handle this <em>for you</em>. By default, writing to a text-mode file translates <code>\n</code> line endings to the platform-local, but you can override this behaviour.</p> <p>See the <code>newline</code> option in the <a href="https://docs.python.org/3/library/functions.html#open" rel="nof...
python|posix|carriage-return|linefeed|nt
7
2,684
38,059,042
Python - " AttributeError: 'str' object has no attribute 'Tc' (Tc is one of the arguments)
<p>I have this code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from scipy.optimize import newton R = 8.314e-5 # universal gas constant, m3-bar/K-mol class Molecule: """ Store molecule info here """ def __init__(self, name, Tc, Pc, omega): """ Pass parameters desribing molecules ""...
<p>It's here:</p> <pre><code>def preos(molecule, T, P, plotcubic=True, printresults=True): Tr = T / molecule.Tc # reduced temperature ... preos("methane", 160, 10, "true", "true") </code></pre> <p>You're clearly passing "methane" into the <code>preos</code> function as a string, then trying to call .Tc on that s...
python|numpy|matplotlib|scipy
0
2,685
40,091,698
What does this ImportError mean when importing my c++ module?
<p>I've been working on writing a Python module in C++. I have a C++ <a href="https://github.com/justinrixx/Asteroids2.0/blob/master/gameNNRunner.cpp" rel="nofollow">program</a> that can run on its own. It works great, but I thought it would be better if I could actually call it like a function from Python. So I took m...
<p>Most likely it means that you're importing a shared library that has a binary interface not compatible with your Python distribution. </p> <p>So in your case: You have a 64-bit Python, and you're importing a 32-bit library, or vice-versa. (Or as suggested in a comment, a different compiler is used).</p>
python|c++
1
2,686
29,259,923
PyQt5 cannot import name 'QApplication'
<p>I am trying convert my code from PyQt4 to PyQt5 but I am getting errors.</p> <pre><code>from PyQt5.QtGui import QApplication, QPixmap desktop = QApplication.desktop() QPixmap.grabWindow(desktop.screen().winId()).save("screen.png", "PNG") 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64...
<p><code>QApplication</code> is located in <code>PyQt5.QtWidgets</code> module. So your import statement should be:</p> <pre><code>from PyQt5.QtWidgets import QApplication </code></pre>
python|pyqt5
55
2,687
8,437,220
High performance computing projects using Python
<p>For a paper I want to argue why I have used Python for the implementation of my algorithm. Besides the typical arguments that it is fast -using suitable libraries- and it is easy to implement the algorithm with it, I thought maybe there are some big HPC projects that are using it. </p> <p>Does anyone know a famous ...
<p>To be honest, as great a language as python is, it wouldn't be a suitable environment for scientific computing and in particular high performance computing, if those libraries weren't available. So you can see python as one pieces of a larger puzzle - much as MATLAB can be. </p> <p>The two key reasons to use python...
python|parallel-processing|hpc
2
2,688
52,021,255
Kivy popup call structure and bindings not making sence
<p>Below is a working snippet example of a program that presents the user with menu popups to enter info. </p> <p>The issues is getting the dismiss bindings working correctly. The program flow is currently: </p> <ul> <li>declare content with a return callback </li> <li>Load content into a popup object </li> <li>ca...
<p>In the example, it demonstrates implementation of numpad using Popup widget with keyboard binding. It accepts input from Buttons, Keyboard, and NumPad.</p> <p><a href="https://kivy.org/doc/stable/api-kivy.uix.popup.html#examples" rel="nofollow noreferrer">Popup » dismiss</a></p> <blockquote> <p>By default, any c...
python|kivy
0
2,689
52,082,100
Python set to array and dataframe
<p><strong>Interpretation by a friendly editor:</strong></p> <p>I have data in the form of a set.</p> <pre><code>import numpy as n , pandas as p s={12,34,78,100} print(n.array(s)) print(p.DataFrame(s)) </code></pre> <p>The above code converts the set without a problem into a numpy array. But when I try to create a D...
<p>Pandas can't deal with sets (dicts are ok you can use <code>p.DataFrame.from_dict(s)</code> for those)</p> <p>What you need to do is to convert your <code>set</code> into a <code>list</code> and then convert to <code>DataFrame</code>:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd s = {12,3...
python
5
2,690
51,854,353
Use python PGSQL driver without installing it?
<p>Is there anyway I can use any pgsql driver without actually installing it? I see <code>Psycopg2</code> is most commonly used for connecting to PGSQL database but that need installing and The issue I have here is I need to distribute the code but the we are not allowed to install anything on the server. Anything stan...
<p>Yes, you can import modules from local files - you can even import whole python files of your own if you want. You can download the <a href="https://github.com/psycopg/psycopg2?files=1" rel="nofollow noreferrer">source code</a> and put it onto your system by using a USB stick (if permitted). However, you <a href="ht...
python|postgresql|psql
0
2,691
69,173,852
Unable to parse an image link from a webpage using requests
<p>I'm trying to scrape two images from two identical links using requests. However, the script that I've created can't grab them. Although the image link is generated dynamically, most of the times there are ways to parse that using requests. So, I tried to find it using dev tools but failed. To let you know, this is ...
<p>Try this:-</p> <pre><code>from requests_html import HTMLSession links = [ 'https://www.glideapps.com/templates/baby-reveal-boy-or-girl-wr', 'https://www.glideapps.com/templates/escool-virtual-school-6d' ] def main(): with HTMLSession() as session: for link in links: res = session.g...
python|python-3.x|web-scraping|python-requests
0
2,692
36,285,273
get IP adresses of my local network
<p>I am working on a GUI program to command power supplies by Ethernet. I have the DHCP of my computer activated, therefore I guess that the IP adresses of my power supplies are fixed by my computer. I would like to know the IP addresses of my power supplies, in order to communicate with them through the TCP/IP protoco...
<p>Finally I solved my problem, using statique IP addresses. Therefore I know them and I don't need anymore to "scan" my network.</p>
python|windows|dhcp|service-discovery
-2
2,693
13,428,747
Multiple timers in Python (Pygame)
<p>I'm an amateur programmer. I am trying to write a simple program that will measure the reaction time for a series of visual stimuli (flashes of squares) that will be used for a biology experiment. Here's my code (beware, first time coding a graphical interface):</p> <pre><code>stimulus = pygame.Rect(100,250,100,100...
<p>Your problem is that the computer will be doing nothing for 0.5 seconds due to the line you marked as a problem. What you need to do is make it so it is possible for the reaction to be registered while the square is still being shown. Instead of having <code>time.sleep(0.5)</code>, put this:</p> <pre><code>while ...
python|time|pygame
1
2,694
16,595,270
Python: Determine assigned serial port my hardware connected to
<p>Microcontroller interfacing with Windows PC via USB CDC creating virtual serial port. Windows assign port number randomly depend on availability, USB port and differs from computer to computer. The question is how via Python script determine which port assigned for my microcontroller and use it.</p>
<p>you can use ctypes to figure out which ports are available</p> <p>you can connect to each port that is available and send something like <code>get ver</code> where you know the expected response.</p> <p>when you find expected response you have found your serialport</p> <p>alternatively (and probably easier) you c...
python|numpy|scipy|microcontroller|pyserial
0
2,695
58,070,832
Python tkinter downsizing widgets
<p>I've looked at all the other questions and answers and couldn't find one that fit what I'm trying to do. </p> <p>Code:</p> <pre><code>class GameWin: def __init__(self, master): self.master = master self.master.title("Title") self.main_frame = Frame(self.master, bd = 10, bg = uni_bg) ...
<p>If you want widgets to shrink down to the size of the column, the strategy that has worked best for me is to make the widget very small and then use the layout manager (<code>pack</code>, <code>place</code>, or <code>grid</code>) make them bigger to fit. You can either make the widget 1x1 if that's truly a minimum s...
python|tkinter|widget|resize|downsize
1
2,696
54,363,043
pickling lru_cached function on object
<p>As part of parallellizing some existing code (with multiprocessing), I run into the situation that something similar to the class below needs to be pickled.</p> <p>Starting from:</p> <pre><code>import pickle from functools import lru_cache class Test: def __init__(self): self.func = lru_cache(maxsize=...
<p>Use <code>methodtools.lru_cache</code> not to create a new cache function in <code>__init__</code></p> <pre class="lang-py prettyprint-override"><code>import pickle from methodtools import lru_cache class Test: @lru_cache(maxsize=None) def func(self, x): # In reality this will be slow-running ...
python|serialization|pickle|lru
0
2,697
9,285,365
django can't import in installed apps and can't import function
<p>In Django, I have a "fbsurvey" project, with a "canvas" application.</p> <p>I have another "cblib" project, with a "survey" app and a "graphs" app.</p> <p>In the "survey" app, there are models and some functions. In the "graphs" app, there is just a "utils" folder with 2 .py files in it-- a file "get_chart_info" w...
<p>The answer was something to do with my .pyc files... I don't know how or why, but running</p> <p>find . -name "*.pyc" -delete</p> <p>(which then presumably regenerated my pyc files) in both of my project directories fixed the problem.</p>
python|django
7
2,698
52,545,529
Sphinx using Python3 interpreter instead of Python2
<p>I installed Sphinx lately for python 2.x based on the instructions: <a href="http://www.sphinx-doc.org/en/master/usage/installation.html" rel="nofollow noreferrer">http://www.sphinx-doc.org/en/master/usage/installation.html</a>.</p> <p>After I generate all the .rst files, I did a "make html" to generate the html fi...
<p>Easy fix would be to create a new virtual environment of python 2.7. Then, do <code>pip install sphinx</code>. I would suggest using <code>sphinx_apidoc.exe</code> and <code>sphinx_build.exe</code> instead of <code>make html</code>. Those exes can be run with various options which is really helpful. </p>
pycharm|python-sphinx
0
2,699
52,699,913
How to preserve the original string format with jinja template
<p>looking for a tip.</p> <p>I have a random string generated elsewhere in format:</p> <pre><code>string = """[TAG1] Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas commodo diam ac sollicitudin vestibulum. Nunc ac dignissim elit. [TAG2] Lorem ipsum d...
<p>both seems good.. hope this helps </p> <pre><code>&lt;p style="white-space: pre-wrap;"&gt;{{ string }}&lt;/p&gt; </code></pre> <p>OR</p> <pre><code>&lt;p style="white-space: pre-line;"&gt;{{ string }}&lt;/p&gt; </code></pre> <p>Update</p> <p>main.py</p> <pre><code>from flask import Flask, render_template, requ...
python|html|jinja2
0