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
1,200
67,843,528
Searching in JSON list
<p>I have this JSON code:</p> <pre><code>{&quot;intents&quot;: [ {&quot;tag&quot;: &quot;greeting&quot;, &quot;patterns&quot;: [&quot;Hi&quot;, &quot;How are you&quot;, &quot;Is anyone there?&quot;, &quot;Hello&quot;, &quot;Good day&quot;], &quot;responses&quot;: [&quot;Hello, thanks for visit...
<p>You can use <code>random.choice</code> to select a random value from a list.</p> <p>Here you go:</p> <pre><code>import json import random inp = input() with open('Python\intents.json') as file: data = json.load(file) for intent in data['intents']: if inp in intent['patterns']: print(ra...
python
3
1,201
67,671,263
Why does the Gmail API returns 401 error?
<p>The response after I sent out my batch request to the gmail is the same as described in the documentation (<a href="https://developers.google.com/gmail/api/guides/handle-errors#exponential-backoff" rel="nofollow noreferrer">https://developers.google.com/gmail/api/guides/handle-errors#exponential-backoff</a>):</p> <p...
<p>As mentioned in <a href="https://stackoverflow.com/questions/67671263/why-does-the-gmail-api-returns-401-error#comment119636583_67671263">comments</a>, you were providing an instance of <code>credentials</code> in the <code>Authorization</code> header:</p> <pre><code>&quot;Authorization&quot;: f&quot;Bearer {creds}&...
python|google-api|gmail-api
1
1,202
30,185,834
Pytest - Error No Module Named Sqlalchemy
<p>I tried to import sqlalchemy to my pytest file but when I tried to run it shows this error, even though I have already installed sqlalchemy. </p> <pre><code> new.py:1: in &lt;module&gt; import sqlalchemy E ImportError: No module named sqlalchemy </code></pre> <p>my code :</p> <pre><code>import pytest imp...
<p>I had the same, and fixed by running tests with:</p> <pre><code>python -m pytest . </code></pre>
python|python-2.7|sqlalchemy|pytest
0
1,203
57,170,626
python script output to be saved in different folder
<p>I'm trying to build a keyword tool. For this, I built a python script that when you run it, it outputs a CSV file with the keyword, the ranking, the URL and the date.</p> <p>I want to run more than one keyword and I want to save the output in different folders.</p> <p>I created 5 different folders with my python ...
<p>Use an absolute path when opening file for writing...</p> <pre><code>import os.path # PRETEND YOU 'example' folder under C:\ save_to_path = 'C://example//' name_of_file = input("What is the name of the file: ") complete_name = os.path.join(save_to_path, name_of_file+".txt") with open(complete_name, 'w+') as f: ...
python|linux|python-3.x|bash|csv
2
1,204
57,030,977
Cython Basics: How to speed up common c functions like random and math functions?
<p>I am working on learning Cython (See <a href="https://stackoverflow.com/questions/57024070/how-to-cythonize-a-python-class-with-an-attribute-that-is-a-function?noredirect=1#comment100580388_57024070">How to Cythonize a Python Class with an attribute that is a function?</a>)</p> <p>I have the following function that...
<p>For anyone that follows me, here were the final answers:</p> <p>Many common functions, including len() are already built in. If you switch it to use carrays it automatically compiles to C. <a href="https://cython.readthedocs.io/en/latest/src/userguide/language_basics.html" rel="nofollow noreferrer">See this link.</...
python|python-3.x|cython
2
1,205
57,143,822
How to extract text between two substrings from a Python file
<p>I want to read the text between two characters (<code>“#*”</code> and <code>“#@”</code>) from a file. My file contains thousands of records in the above-mentioned format. I have tried using the code below, but it is not returning the required output. My data contains thousands of records in the given format. </p> ...
<p>Use the following regex:</p> <p><code>#\*([\s\S]*?)#@ /g</code></p> <p>This regex captures all whitespace and non-whitespace characters between <code>#*</code> and <code>#@</code>.</p> <p><a href="https://regex101.com/r/i2GJ0M/1" rel="nofollow noreferrer">Demo</a></p>
regex|python-3.x|text-manipulation
2
1,206
72,311,511
Python random number loop with different outcomes each time
<p>I’ve been working on a school project and need to do a loop consisting of a couple random numbers but I need them to output a different number each time. The code I’ve been using for the random numbers is this.</p> <p>import random</p> <p>a=random.randint(1,9)</p> <p>I’m new to coding and just starting getting into ...
<p>You have not created any loop yet. You're generating random integer only once. In order to generate more of them you have to use something like a <code>for</code> loop.</p> <p>If you're familiar with the concept of <code>range</code> then this is a simple example of generating x-number of random integers.</p> <pre><...
python
1
1,207
4,646,089
python algorithm: how to efficiently find if two integer sets are intersected?
<p>Given a set [2004, 2008], what is the fastest way to find if this set is intersected with other sets?</p> <p>Actually I am dealing a problem with database, the table has 2 columns, one is the lower bound, the other one is the higher bound. The task is to find all the intersected rows with the given 2 tuple(like [20...
<p>I don't know MongoDB at all, but you're basically looking for </p> <p><code>SELECT * from the_table where not (lower_bound &gt; 2008 or upper_bound &lt; 2004)</code>.</p>
python|algorithm|data-structures|mongodb
4
1,208
69,344,058
How do I create font style and font size in my notepad?
<p>I have created a notepad using python. I want to create a feature which can change the font size and also the font style. I have tried various options but they have failed. My notepad is fully made up with python's tkinter module. I have also tried methods like file handling but it doesn't work. Please help me out. ...
<p>Creating fonts, colors with various styles is achieved by creating tag names and defining tag attributes to them, then using those tag names when inserting text into <code>Text</code> object.</p> <p>Here is an example.</p> <pre class="lang-py prettyprint-override"><code>import tkinter as tk master = tk.Tk() text =...
python|tkinter|notepad
0
1,209
69,364,743
How to perform an operation with two columns in the same dataframe in Python Pandas?
<p>I'm trying to apply the operation <code>'x-y/y'</code>, being <code>x</code> the column <code>'Faturamento'</code> and <code>y</code> column <code>'Custo'</code> from the dataframe called <code>'df'</code>, and store the results in a new column called <code>'Roi'</code>.</p> <p>My attempt to use the apply function:<...
<p>I think you mean:</p> <pre><code>df['Roi'] = df.apply(lambda x: (x['Faturamento']-x['Custo'])/x['Custo'], axis=1) </code></pre> <p><code>x</code> refers to the dataframe</p>
python|pandas|dataframe|lambda|apply
1
1,210
48,392,514
Issues processing JSON API response
<p>I am trying to process the results of this API in Python:</p> <p><a href="https://www.cryptopia.co.nz/api/GetMarkets/BTC/12" rel="nofollow noreferrer">https://www.cryptopia.co.nz/api/GetMarkets/BTC/12</a></p> <p>When I assign the results of the API call to a variable I cannot seem to iterate over it or even call o...
<p>You haven't provided much detail, however, you probably need to decode the JSON response. Use the <a href="https://docs.python.org/3/library/json.html#module-json" rel="nofollow noreferrer"><code>json</code></a> module for that. Something like this should help, but it depends on what the actual response is:</p> <pr...
python|json|api
2
1,211
70,449,191
Error locating div aria label with xpath Selenium
<p>So I'm trying to find a way to make sure my bot doesn't get confused and click on the <strong>Following</strong> button again (it uses span to detect text) when it has already followed that particular user. I am trying to detect that if a user is already followed, the bot should skip him through another method, whic...
<p>To locate the <em>visible</em> element with text as <em><strong>Turn on Tweet notifications</strong></em> you need to induce <a href="https://stackoverflow.com/questions/59130200/selenium-wait-until-element-is-present-visible-and-interactable/59130336#59130336">WebDriverWait</a> for the <a href="https://stackoverflo...
python|selenium|xpath|css-selectors|webdriverwait
2
1,212
55,647,606
How to calculate rolling average over each product?
<p>I have the first three columns in a dataframe in pandas. I want to calculate the 3 days moving average with respect to each product as shown in the 4th column.</p> <p>Data</p> <pre><code>print (df) Date Product Demand mov Avg 0 1-Jan-19 Product-01 3 NaN 1 2-Jan-19 Product-01 4 ...
<p>Use:</p> <pre><code>df['Date'] = pd.to_datetime(df['Date'], format='%d-%b-%y') </code></pre> <p>Your solution should be changed by <code>rolling(3, freq='d')</code>:</p> <pre><code>#sorting if not sorted DataFrame by both columns df = df.sort_values(['Date','Product']).reset_index(drop=True) df['mov_avg'] = (df....
python|pandas|pandas-groupby
1
1,213
73,262,943
How Can I get Sum Total of Django Model Column through a Queryset
<p>I am working on an Event App where I want to get the Total Amount of Pin Tickets that has been activated and I don't know how to do it.</p> <p>Below is what I have tried and I am getting this error: <strong>'QuerySet' object has no attribute 'ticket'</strong></p> <p>Here are my Models</p> <pre><code>class Ticket(mod...
<p>To get the total price of tickets with pin status activated, use this.</p> <pre><code>Ticket.objects.filter(pin__status=&quot;Activated&quot;).aggregate( total=Sum('price') )['total'] </code></pre> <p>If is just how many tickets has a pin status activated.</p> <pre><code>Ticket.objects.filter(pin__status=&quot;A...
python|django
0
1,214
73,198,441
how can i multiply each index of a list by the next?
<p>So, I have this array:</p> <pre><code>numbers = [5, 9, 3, 19, 70, 8, 100, 2, 35, 27] </code></pre> <p>What I want to do is to create another array from this one, but now each value of this new array must be equal to the corresponding value in the <code>numbers</code> array multiplied by the following.</p> <p>For exa...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>numbers = [5, 9, 3, 19, 70, 8, 100, 2, 35, 27] out = [a * b for a, b in zip(numbers, numbers[1:] + [2])] print(out) </code></pre> <p>Prints:</p> <pre class="lang-py prettyprint-override"><code>[45, 27, 57, 1330, 560, 800, 200, 70, 945, 54] </code></pre>
arrays|python-3.x
1
1,215
73,336,725
why function' object has no attribute 'user' showing up?
<p>I tried to create 2 users in my project.</p> <blockquote> <p>models.py</p> </blockquote> <pre><code>class CustomUser(AbstractUser): user_type_choices = ((1, &quot;Admin&quot;), (2, &quot;NotesUser&quot;)) user_type = models.CharField(max_length=10, choices=user_type_choices, default=1) class Admin(models.Mo...
<p>According to the <a href="https://docs.djangoproject.com/en/4.1/topics/http/middleware/#process-view" rel="nofollow noreferrer">documentation</a> the first parameter to the process view is the request object please change the function as below:</p> <pre class="lang-py prettyprint-override"><code>def process_view(sel...
python|django|django-settings|django-middleware
2
1,216
64,624,047
Updating a record with a value from another table - MySQL (Python)
<p>I am trying to update a value in one table (csms) in MySQL from another table (serviceppl). I have attached the query I wrote and both tables, but the query does not work. It does not produce any error, but the record doesn't get updated. Help!</p> <pre><code>query = &quot;select*from csms where feedback in('null', ...
<p>If you want to update the column <code>serviceman</code> of the table <code>csms</code> then you must fix your <code>SET</code> clause:</p> <pre><code>set csms.serviceman = serviceppl.name </code></pre>
python|mysql|join
0
1,217
64,007,764
Change monthly data to daily data and spread out values over each day of that month
<p>I have a df with monthly data:</p> <pre><code>date | type | value1 | value2 2020-04-01 | &quot;a&quot; | 30 | 60 2020-04-01 | &quot;b&quot; | 60 | 120 2020-04-01 | &quot;c&quot; | 45 | 180 ... | ... | ... | ... 2021-02-01 | &quot;a&quot; | 28 | 56 ...
<p>First add days by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>DataFrame.reindex</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html" rel="nofollow noreferrer"><code>date_range</...
python|pandas|datetime|converters
1
1,218
71,791,818
How to bulild a null notnull matrix in pandas dataframe
<p>Here's my dataset</p> <pre><code>Id Column_A Column_B Column_C 1 Null 7 Null 2 8 7 Null 3 Null 8 7 4 8 Null 8 </code></pre> <p>Here's my expected output</p> <pre><code> Column_A Column...
<p>Assuming <code>Null</code> is NaN, here's one option. Using <code>isna</code> + <code>sum</code> to count the NaNs, then find the difference between <code>df</code> length and number of NaNs for <code>Notnulls</code>. Then construct a DataFrame.</p> <pre><code>nulls = df.drop(columns='Id').isna().sum() notnulls = nu...
python-3.x|pandas|dataframe
2
1,219
62,694,581
WebDriverException: Message: 'chromedriver.exe' executable may have wrong permissions using Google Colaboratory through Selenium Python
<p>I am using Google Chrome version 83.0.4103.116 and ChromeDriver 83.0.4103.39. I am trying to use chrome driver in google colab. I use the path of chromedriver after uploading it in google colab. Could you please point out where i m getting error. This is the code</p> <pre><code>import selenium from selenium import w...
<h2>Google Colaboratory</h2> <p><a href="https://colab.research.google.com/drive/16pBJQePbqkz3QFV54L4NIkOn1kwpuRrj#scrollTo=DO6Z47v1bO-w" rel="nofollow noreferrer">Colaboratory</a> is a free Jupyter notebook environment that requires no setup and runs entirely in the cloud which enables us to write and execute code, sa...
python|selenium|google-chrome|selenium-chromedriver|google-colaboratory
2
1,220
61,776,714
Get specific value BeautifulSoup (parsing)
<p>I'm trying to extract information from a website.</p> <p>Using Python (<strong>BeautifulSoup</strong>) </p> <p>I want to extract the following data (<em>just the figures</em>)</p> <p><strong>EPS (Basic)</strong> </p> <p>from: <em><a href="https://www.marketwatch.com/investing/stock/aapl/financials/income/quarter...
<p>Try following <code>css</code> selector which check td tag contains <code>EPS (Basic)</code> text .</p> <pre><code>import urllib.request as ur url_is = 'https://www.marketwatch.com/investing/stock/aapl/financials/income/quarter' read_data = ur.urlopen(url_is).read() soup_is=BeautifulSoup(read_data, 'lxml') row = s...
python|python-3.x|parsing|beautifulsoup
1
1,221
61,809,209
I am having hard time understanding the BCEWITHLOGITLOSS
<p>Hello everyone recently i am working on a assignment where i have to predict mask of image using foreground_background image,background image.I used bcewithlogitloss bcz i changed my target value as combination of 1 and 0 where 1 is for foreground and 0 is for background.So my results are pretty good but i am not st...
<p>The task you're describing is semantic segmentation, where the model predicts a mask for the image.</p> <p><a href="https://i.stack.imgur.com/srDWS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/srDWS.jpg" alt="enter image description here"></a></p> <p>In the mask, for every input pixel, there ...
pytorch
0
1,222
60,501,986
Why does the inpaint method not remove the text from IC image?
<p>I am trying to mask out the marking on an IC but the <code>inpaint</code> method from OpenCV does not work correctly.</p> <p><a href="https://i.stack.imgur.com/RW4sT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RW4sT.png" alt="inpainting dies"></a></p> <p>The left image is the original image ...
<p>Mainly, dilate the <code>mask</code> used for the inpainting. Also, enlarging the inpaint radius will give slightly better results.</p> <p>That'd be my suggestion:</p> <pre class="lang-py prettyprint-override"><code>import cv2 from matplotlib import pyplot as plt # Read image img = cv2.imread('ic.png', cv2.IMREAD...
python|opencv|image-processing|image-preprocessing
3
1,223
60,615,012
Most generic way to Substitute all the occurrences of a string with different values Python
<p>I have text file (FILE) which internally is a combination of 4 files( file_f1,file_f2,file_f3,file_f4). </p> <p>The delimiter to separate different files from one another is the string "stackoverflow" which appears depending on the count of files (eg: if FILE is combination of 3 files then the string appears 3 time...
<p>Use <code>iter</code></p> <p><strong>Ex:</strong></p> <pre><code>vals = iter(['f1','f2','f3','f4']) with open(os.path.join(file),'r') as fh: for line in fh: if "stackoverflow" in line: line= re.sub('stackoverflow',next(vals), line) </code></pre>
python-3.x
1
1,224
63,450,441
load a python trained xgboost in c++ api, the predict result is empty
<p>i am training a 13 category classification on python xgboost, my feature dim is 3207, the model is saved after python xgbsoot training, and i checked some case, the result is normal. but when i load the model in c++ xgboost, and do predict, the result is nothing. here is my c++ code demo:</p> <pre><code> BoosterHan...
<p>I found the reason,my python xgboost is trained anaconda, the xgboost is different from c++ xgboost source code version.</p>
python|c++|xgboost
1
1,225
68,364,605
Discord Bot Commands not working with on_message
<p>I have a few commands that worked perfectly, but when I add on_message they don't. I read that you need to add the await bot.process_commands(message) line, but it still doesn't work for me. Why?</p> <pre class="lang-py prettyprint-override"><code>@bot.event async def on_message(message): if message.content.lowe...
<p>A function ends as soon as it encounters a <code>return</code> statement, with your current logic it will only process the commands if the <code>if</code> statement is <code>True</code>. Simply remove that <code>else</code> part.</p> <pre class="lang-py prettyprint-override"><code>@bot.event async def on_message(mes...
python|discord.py|command
3
1,226
59,139,646
Address generation for bitcoin with Python error
<p>I am trying to understand bitcoin with python and trying to create my own vanity address generator.</p> <p>Below is a snippet of the while loop. I keep getting an error after the loop runs about 10 times. Any help would be highly appreciated. i have searched the forum and have found answers. </p> <p>But they don't...
<p>You have to encode your <code>hex_compressed_public_key</code> to generate the address. </p> <pre><code>compressed_address_base58check = bitcoin.pubkey_to_address(hex_compressed_public_key.encode('utf-8')) </code></pre>
python-3.x|bitcoin
-1
1,227
35,593,724
Group by one column and iterate the ranking from 1 to 5 for whole file
<p>Total recs: 50 records</p> <p>Rec id is the unique id in the file.</p> <p>Input file will be as follows:</p> <pre><code>rec id1 rec id1 rec id1 rec id2 rec id3 rec id3 rec id4 rec id6 rec id6 rec id7 rec id7 Output file should have A RANKS rec id1 1 rec id1 1 rec id1 1 rec id2 2 rec id3 3 rec ...
<p>You can try <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html" rel="nofollow"><code>factorize</code></a> and divide by <code>modulo</code> <code>%</code> with <code>5</code>. Last you need add <code>1</code>:</p> <pre><code>print df A 0 rec id1 1 rec id1 2 rec id1 ...
python-2.7|pandas|dataframe
1
1,228
58,706,952
Writing xls from python row wise using pandas
<p>I have sucessfully created .xlsx files using pandas</p> <blockquote> <p>df = pd.DataFrame([list of array])</p> </blockquote> <pre><code>''' :param data: Data Rows :param filename: name of the file :return: ''' df = pd.DataFrame(data) # my "Excel" file, which is an in-memory output file (buffer) # for the new wo...
<p>You can take reference from this <a href="https://medium.com/better-programming/using-python-pandas-with-excel-d5082102ca27" rel="nofollow noreferrer">https://medium.com/better-programming/using-python-pandas-with-excel-d5082102ca27</a> post of medium for this. </p>
python|django|pandas|xls|xlsxwriter
1
1,229
60,254,855
Pexpect - Read from constantly outputting shell
<p>I'm attempting to have pexpect begin running a command which basically continually outputs some information every few milliseconds until cancelled with Ctrl + C.</p> <p>I've attempted getting pexpect to log to a file, though these outputs are simply ignored and are never logged.</p> <pre><code>child = pexpect.spaw...
<p>Managed to get it working by using Python Subprocess for this, not sure of a way to do it with Pexpect, but this got what I described.</p> <pre><code>def echo(self, n_lines): output = [] if self.running is False: # start shell self.current_shell = Popen(cmd, stdout=PIPE, shell=True) ...
python-3.x|pexpect
0
1,230
42,934,712
python matplotlib plot datetime index
<p>I am trying to create a simple line graph based on a datetime index. But I get an error message. </p> <pre><code>#standard packages import numpy as np import pandas as pd #visualization %matplotlib inline import matplotlib.pylab as plt #create weekly datetime index edf = pd.read_csv('C:\Users\j~\raw.csv', parse_d...
<p>You're getting a <code>KeyError</code> because your <code>'DATESENT'</code> is the index and NOT a column in <code>edf3</code>. You can do this instead:</p> <pre><code>#linegraph edf3.plot(x=edf3.index,y='Sales') </code></pre>
python|pandas|matplotlib
2
1,231
42,657,894
BeautifulSoup scrape itemprop="name" in Python
<p>I have some python 3.5 code that I want to scrape part of a web page with but instead of printing "Thick and Chewy Peanut Butter Chocolate Chip Bars" it prints "None". Do you know why? Thanks. </p> <pre><code>import requests, bs4 import tkinter as tk from tkinter import * import pymysql import pymysql.cursors res ...
<p>Change <code>instructions = recipeSoup.find("div", itemprop="name")</code> to <code>instructions = recipeSoup.find("span", itemprop="name")</code> to get the recipe title.</p> <p>For the instructions you'll have to search for <code>li</code> tags with <code>itemprop=ingredients</code>.</p>
python|python-3.x|web-scraping|beautifulsoup
11
1,232
65,654,756
Blocking unwanted users from access another users profile data with function based view in Django
<p>I am working with some function-based views in <code>Django</code>. I have a custom build decorator named <code>industry_required</code> which allows passing by verifying a user is authenticated from an <code>Industrial</code> account or not.</p> <p>I have some functions in <code>views.py</code> and their particular...
<p>In your function based view, you need to fetch the industry using a similiar filter to what you had specified in <code>industryDetails.get_queryset</code>.</p> <pre><code>def function_based_view(request, pk): industry = get_object_or_404(Industry.objects.filter(user=self.request.user), pk=pk) </code></pre>
python|django
1
1,233
50,885,201
Error with **args and *kwargs
<p>I'm learning *args and **kwargs and had a question. What happens when we instead use ** on a list and * on a dictionary? I know it doesn't work but was wondering if it's a syntax issue or if there's something going on that has a more intuitive explanation.</p>
<p>Let's find out:</p> <pre><code>&gt;&gt;&gt; def f(arg): ... print(arg) ... &gt;&gt;&gt; f(**[]) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: f() argument after ** must be a mapping, not list &gt;&gt;&gt; f(*{}) Traceback (most recent call last): File "&lt;stdi...
python|arguments
2
1,234
45,212,378
Python - how to split a string using regex but preserving pattern that contains the split separator?
<p>Starting from <code>"param1=1-param2=1.e-01-param3=A"</code>, how to get <br><code>["param1=1", "param2=1.e-01", "param3=A"]</code> ? The problem is that the separator "-" may be contained in the value of a parameter.</p> <p>Franck</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.split("-", "param1=1-param2=1...
<p>By using non-capturing group and positive lookahead, capture <code>'-'</code> only if it is followed by <code>'param'</code>:</p> <pre><code>import re string = "param1=1-param2=1.e-01-param3=A" print(re.split(r"(?:-)(?=param)", string)) # ['param1=1', 'param2=1.e-01', 'param3=A'] </code></pre> <p><a href="https:/...
python|regex
2
1,235
45,115,219
how to print arduino accelerometer real time data to file
<p>The program below compiles but doesn't print data to file. I also tried while(1) but didn't get the right output (no data). I am still trying to learn python embedded and file programming. Can anybody take a look and point me in the right direction?</p> <p>Code below:</p> <pre><code> import logging import seri...
<p>try to write csv file <code></p> <pre>import csv while(1): with open(r'log.csv', 'a') as f: writer = csv.writer(f) writer.writerow((getvalues())) </code></pre>
python
0
1,236
58,018,049
Counting most common combination of values in dataframe column
<p>I have DataFrame in the following form:</p> <pre><code>ID Product 1 A 1 B 2 A 3 A 3 C 3 D 4 A 4 B </code></pre> <p>I would like to count the most common combination of two values from <code>Product</code> column grouped by <code>ID</code>. So for this example expected result would be:</p> <pre>...
<p>We can <code>merge</code> within ID and filter out duplicate merges (I assume you have a default <code>RangeIndex</code>). Then we sort so that the grouping is regardless of order:</p> <pre><code>import pandas as pd import numpy as np df1 = df.reset_index() df1 = df1.merge(df1, on='ID').query('index_x &gt; index_y...
python|pandas
5
1,237
56,411,436
Why function shows none for more output when using insert() method in lists in Python?
<p>I am using function to insert method to add a value in list as given below: 1. insert_value.py file as given below:</p> <pre><code>def insert_value(my_list, value, insert_position): str_list3 = ['one','three','four', 'five', 'six'] str_list4 = ['i', 't'] if my_list == str_list3: front = my_list[:in...
<p>Neither of the conditionals in insert_value evaluate to True after the first two calls, so insert_value has no return (returns None) for the last two calls. </p>
python|python-3.x
0
1,238
55,558,483
Fetching data from json file, using python3. How to printspesific parts from datapool?
<p>So Ive been trying to get data from this json file containing stock info. Im completely new to python, and json is almost foreign. But I do understand the concepts, and I could need a little push in the right direction. Ive been doing beginners guides on python, and have spent lots of time to figure this out on my o...
<p><a href="https://i.stack.imgur.com/0LbQN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0LbQN.png" alt="enter image description here"></a> </p> <p>The entire json file is loaded into cont.You just need to filter the required values. </p>
json|python-3.x
0
1,239
28,493,771
Making pattern in Python using nested loop
<p> I was trying to making a simple pattern that allows the user to decide the numer of rows and columns, for example:</p> <pre><code>How many rows: 5 How many columns: 5 &gt;&gt;&gt; ***** ***** ***** ***** ***** </code></pre> <p>So my code is like this:</p> <pre><code>row = int(input('How many rows: ')) col = int(...
<p>This loops <code>col</code> times and then results in <code>col</code> being set to <code>col - 1</code></p> <pre><code>for col in range(col): </code></pre> <p>Due to <code>range(col)</code> looping over <code>0</code> to <code>col - 1</code> and due to the fact that after a loop finishes the loop variable is at t...
python|for-loop
2
1,240
56,916,876
How to set a user-selected background colour in tkinter?
<p>How to take user-selected colour and use it as the background colour of the tkinter frame?</p> <pre><code>list2 = ["red", "red", "red", "red", "blue", "yellow"]; droplist = OptionMenu(root, c, *list2) droplist.config(width=15) c.set('select your colour') droplist.place(x=240, y=320) root.configure(bg=c) </code></pr...
<p>Let's make this work by filling in some missing pieces:</p> <pre><code>import tkinter as tk COLORS = ["red", "blue", 'green', 'cyan', 'magenta', "yellow"] def change_color(*args): root.configure(bg=color.get()) root = tk.Tk() root.minsize(width=200, height=200) color = tk.StringVar(root) color.trace('w', ch...
python|python-3.x|tkinter
3
1,241
23,689,635
PyMongo sort with metadata
<p>I wondering how to convert the follow mongodb query to pymongo syntax</p> <pre><code>db.articles.find( { $text: { $search: "cake" } }, { score: { $meta: "textScore" } } ).sort( { score: { $meta: "textScore" } } ).limit(3) </code></pre> <p>I tried this:</p> <pre><code>results = \ mongo.db.products.find({...
<p>I think that the solution is here: <a href="https://github.com/mongodb/mongo-python-driver/blob/master/pymongo/cursor.py#L658" rel="noreferrer">https://github.com/mongodb/mongo-python-driver/blob/master/pymongo/cursor.py#L658</a> . To add list of (key, direction) for new approach with "new" feature '$text':</p> <pr...
python|mongodb|pymongo|mongodb-query
10
1,242
29,347,789
Install taiga on local server error
<p>I'm trying to install Taiga on my local server via this tutorial (<a href="http://taigaio.github.io/taiga-doc/dist/setup-production.html" rel="nofollow">http://taigaio.github.io/taiga-doc/dist/setup-production.html</a>)</p> <p><strong>I get stuck at the part where i have to input this code</strong></p> <pre><code>...
<p>In which command do you exactly get stuck? Can you print here your "pip freeze" command output?</p> <p>To fix that error you have to install kombu's dependency. Check again everything inside requirements.txt has been fully installed.</p> <p>This is my "pip freeze" and the commands are working for me:</p> <pre><co...
python|localhost|ubuntu-14.04
2
1,243
46,442,737
Restful security check for webpage menu items
<p>When I want to check that a user has no access to a specific menu item, I pass a value in my REST API like this:</p> <pre><code>{ menu_item1: false, menu_item2: true } </code></pre> <p>And regarding to these values, menu items will be visible/invisible.<br> Is it a security issue that a user which is not authorize...
<p>Yes , since the item is part of the page DOM , all that you are doing is just making it invisible . There are numerous ways in which the client side page rendering be changed on the fly to make the item visible again. Ideally you should not send the menu Item in the API return and do not add those items in the page...
python|rest|security|frontend|web-deployment
0
1,244
49,731,747
How can I install a PyPI package while using Anaconda dependencies?
<p>When I install a package through <code>pip</code> (since it was not available on Anaconda), it also pulls all dependencies. It seems it will use the <code>pip</code> versions of the dependencies, even if <code>conda</code> versions (same name) are available.</p> <p>How can I easily install a <code>pip</code> packag...
<p>There is no easy way, I suspect. Create a virtual environment, install all anticipated dependencies using <code>conda</code> and then install the main package using <code>pip</code> without <code>-U/--upgrade</code>. <code>pip</code> seeing dependencies installed will not install them again.</p>
python|pip|anaconda|conda
0
1,245
53,641,430
Matplotlib's get_ticklabels not working with custom string labels
<p>I would like to plot only every 50th item from "dates" as a tick on the x axis. When I comment out the line "plt.xticks(xticks, dates)", it works fine (top figure), but when I attempt to replace the numbers with the actual date strings, it puts ALL the dates instead of only every 50th ones (bottom figure). </p> <p>...
<p>The following should work:</p> <pre><code>ax = plt.axes() pos = np.arange(len(vals)) ax.bar(pos, vals) ax.set_xticks(pos[::50]) ax.set_xticklabels(np.array(dates)[::50], rotation=90) </code></pre>
python|datetime|matplotlib
2
1,246
53,548,791
Checking a DataFrame string value contains words with certain prefixes
<p>First time working with Pandas, and I'm struggling to query the DataFrame for this spec.</p> <p>Let's say I create a dataframe as follows:</p> <pre><code>df = pd.read_csv(_file, names=['UID', 'Comment', 'Author', 'Relevancy']) </code></pre> <p>Which gives:</p> <pre><code>UID . Comment . Author . ...
<p>Pandas <code>str</code> operations aren't vectorised. You can use a list comprehension:</p> <pre><code>df = pd.DataFrame({'Comment': ['motorcycles are cool', 'motorhomes are cooler', 'i love motorbikes', 'nomotor test string', 'some other test string']})...
python|string|pandas
0
1,247
52,446,339
(psycopg2.DataError) invalid input syntax for integer: importing from csv file?
<p>the data in my csv file is like this:</p> <pre><code>081299289X,China Dolls,Lisa See,2014 0345498127,Starter for Ten,David Nicholls,2003 0061053716,Imajica,Clive Barker,1991 0553262149,Emily Climbs,L.M. Montgomery,1925 </code></pre> <p>my import.py is like this:</p> <pre><code>import csv import os from sqlalchem...
<p>From the looks of it your CSV contains a header as the first row. Skip it with for example</p> <pre><code>next(reader, None) </code></pre> <p>before your for-loop.</p>
python|postgresql|sqlalchemy
5
1,248
52,845,915
Unable to print out a function
<p>Hi I'm new to programming, and ran into some problems while practicing using python.</p> <p>So basically my task is to create a simple quiz with (t/f) as the answer. So here's my code:</p> <pre><code>def quiz(question,ans): newpara = input(question) if newpara == ans: print("correct") else: ...
<p>Then you should be returning either "correct" or "incorrect". You function returns the value of the input so it's normal to get that output. Try this:</p> <pre><code>def quiz(question,ans): newpara = input(question) if newpara == ans: answer= "correct" else: answer= "incorrect" return(...
python
0
1,249
52,592,663
Unicode Characters in QT Designer for Python?
<p>I am writing a gui for an executable. My first one was written using Python and TKinter. It worked. Now I am working on version 2, and I want to do it in QT4. I found the Qt Designer which is really helpful for creating the layout etc.</p> <p>I created a QLabel, and in there I want it to display a greek Gamma Symbo...
<p><code>QLabel</code> supports HTML, for this you must right click and select the option <code>Change rich text...</code> and in the tab <code>source</code> place html code:</p> <pre><code>&lt;p&gt;&amp;gamma;&lt;/p&gt; </code></pre> <p>That is, within the tags <code>&lt;p&gt; &lt;/p&gt;</code> obtaining the followi...
python|pyqt|qt-designer
2
1,250
47,789,371
Use different configuration sources as input to waf's doxygen feature
<p>Based on the question I asked <a href="https://stackoverflow.com/q/47396160/8972161">here</a>, where I wanted to use different sources based on the build variant specified, it now appears that I have the same problem for building the doxygen documentation, as I need different configurations based on the build varian...
<p>Your problem is that you have not defined your variants for the doxygen command. You should add something like:</p> <pre class="lang-py prettyprint-override"><code>variants = ['a', 'b'] for variant in variants: dox = "doxygen" class tmp(BuildContext): __doc__ = '''executes the {} of {}'''.format(do...
python|doxygen|waf
1
1,251
37,350,892
Python3.5 Error with urlib.request library
<ul> <li>This script visits the url specified and outputs the contents into a local file. </li> <li>When ans = 1 the script works as intended.</li> <li>When ans = 2 the script always returns an error for some reason.</li> <li><p>All help is appreciated. :)</p> <pre><code>import urllib.request ans = True while ans: ...
<p>You are trying to input data twice and ignoring the first result:</p> <pre><code>input('Enter link : ') link = input() </code></pre> <p>Change that to just:</p> <pre><code>link = input('Enter link : ') </code></pre>
python|python-3.x|urllib
1
1,252
32,412,348
Structuring Flask using Blueprints error
<p>I'm attempting to break a small app into units and use the Blueprint pattern in Flask. However I seem to have trouble in getting the app running.</p> <p>Here is my structure:</p> <pre><code>\myapp login.py \upload __init__.py views.py </code></pre> <p>Here is login.py:</p> <pre><code>import sys, os...
<p>There are three problems with your code:</p> <ul> <li>You are using a relative import in <code>login.py</code> to include <code>views</code>, but given the folder structure and the fact that you use <code>login.py</code> as starting point, it cannot work here. Simply use <code>from upload import views</code> instea...
python|heroku|flask
2
1,253
28,141,279
What happens to my scipy.sparse.linalg.eigs?
<p>I use python 2.7.8 with the Anaconda distribution and I have problems with scipy. Let A be a sparse matrix; I want to calculate its eigenvalues but if I write: </p> <pre><code>import scipy scipy.sparse.linalg.eigs(A) </code></pre> <p>I get the error</p> <pre><code> Traceback (most recent call last): File "&l...
<p>Does this work for you?</p> <pre><code>from scipy import sparse import scipy.sparse.linalg as sp_linalg B = np.random.rand(10,10) A_dense = np.dot(B.T, B) A_sparse = sparse.lil_matrix(A_dense) sp_linalg.eigs(A_sparse, 3) </code></pre> <p>It seems that you have to explicitly import the submodules. <code>scipy</cod...
python|scipy|sparse-matrix|anaconda
5
1,254
23,091,450
AWS Elastic Beanstalk - Using Mongodb instead of RDS using Python and Django environment
<p>I've been following the official Amazon documentation on deplaying to the Elastic Bean Stalk.</p> <p><a href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Python.html" rel="nofollow">http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Python.html</a></p> <p>and the customizat...
<p>You can create a customize AMI to your specific needs the steps are outline in the AWS documentation below. Basically you would create a custom AMI with the packages needed to host your application and then update the Beanstalk config to use your customize AMI.</p> <p><a href="http://docs.aws.amazon.com/elasticbean...
django|mongodb|python-2.7|amazon-web-services|amazon-elastic-beanstalk
2
1,255
46,692,763
readable columns names in my CSV file that is exported from elastic search?
<p>Below is the code that is grabbing some data from elastic search and exporting that data to a csv file called ‘mycsvfile’. I want to change the column names so that it is readable by a human. Below is the code:</p> <pre><code>from elasticsearch import Elasticsearch import csv es = Elasticsearch(["9200"]) # Replac...
<p>Edit: Sorry, wrote that line out of my behind. The correct, tested, version is as follows.</p> <pre><code>with open('mycsvfile.csv', 'w') as f: # Just use 'w' mode in 3.x header_present = False for doc in res['hits']['hits']: my_dict = doc['_source'] if not header_present: fie...
python|python-3.x|csv|elasticsearch|python-3.6
1
1,256
57,076,754
How to get the posts of a user (who is currently logged in) in django?
<p>When a user logged in and went to his/her account they must see there old posts, what they have uploaded in past. If tried if statement in template by comparing current logged in user (request.user) and the users available in database. If, if condition is true than all the posts which are related to that user must b...
<p>Isn't it better to just get the current user and query all Tweets by that user? What you can do is:</p> <pre><code>def myaccount(request): current_user = request.user # Where user is whatever foreign key you specified that relates to user. user_tweets = Tweets.objects.filter(user=current_user) retu...
python|django
3
1,257
57,236,475
Why "0" and '0' are evaluated to False?
<p>I was thinking if we were checking the boolean of string or character, we were checking if they were empty. But the following code gave me unexpected outputs.</p> <pre><code>print('0'==True) print("0"==True) </code></pre> <p>Output:</p> <pre><code>False False </code></pre> <p>What is happening? What we were rea...
<p>They are true (in a boolean context):</p> <pre><code>if '0': print("you will see this") if '': # for comparison print("you will not see this") # Alternately: bool('0') # True bool('') # False </code></pre> <p>But they are not <em>equal to</em> the special value <code>True</code>.</p> <p>There is no contra...
python
5
1,258
57,242,268
How to change object once in a loop
<p>I am trying to make it so the object X is the background and A is an object to be moved up or down, but once i use loop to change the A to X, the loop finds the a in the next line and does it once again, how do i make it so it only changes once and moves on?</p> <pre><code>newlist = ['X','X','A','X','X','X','X'] f...
<p>While doing the downshift as well (just for myself) I found an even better approach than in my previous answer:</p> <p><a href="https://docs.python.org/3.3/library/collections.html#collections.deque" rel="nofollow noreferrer">deque</a> adds rotation functionality to iterables.</p> <pre><code>from collections impor...
python|loops|if-statement
1
1,259
25,831,240
Create custom field at delivery order (stock.picking.out) which gets its value from sales order
<p>I have a sales order form which contains a custom delivery date field. Now I want to pass the value from delivery date field in sales order to the commitment date field in delivery order (stock.picking.out). </p> <p>Did we make two columns in both stock.picking and stock.picking.out? And also how can I take the d...
<p>I got the answer from the following link. Thanks too much for @Sudhir Arya for helping me.</p> <p><a href="https://www.odoo.com/forum/help-1/question/how-to-create-a-custom-field-at-delivery-order-stock-picking-out-which-gets-its-value-from-sales-order-in-openerp-62669" rel="nofollow">link</a></p> <p>Here is the f...
python|openerp|openerp-7|odoo
0
1,260
25,507,534
Getting Keys Within Range/Finding Nearest Neighbor From Dictionary Keys Stored As Tuples
<p>I have a dictionary which has coordinates as keys. They are by default in 3 dimensions, like <code>dictionary[(x,y,z)]=values</code>, but may be in any dimension, so the code can't be hard coded for 3.</p> <p>I need to find if there are other values within a certain radius of a new coordinate, and I ideally need to...
<p>You say you need to determine IF there are any keys within a given radius of a particular point. Thus, you only need to scan the keys, computing the distance of each to the point until you find one within the specified radius. (And if you do comparisons to the <em>square</em> of the radius, you can avoid the squar...
python|dictionary
1
1,261
44,576,248
Django - Regroup By Date
<p>I have a model with the following fields: "Date", "Employee", and "Planned Hours". Each employee has various planned hours for various dates.</p> <p>I'm attempting to structure my template where employees are listed in rows and their planned hours are listed in columns under the correct corresponding date.</p> <p>...
<p>this can be a solution: {% for y in date_list %} if(y.list.0.date == current_date){ {{y.list.0.planned_hours|default:"0"}} {{y.list.1.planned_hours|default:"0"}} {{y.list.2.planned_hours|default:"0"}} }else{ ----- {{y.list.0.planned_hours|default:"0"}} {{y.list.1.planned_hours|default:"0"...
python|django
0
1,262
44,755,690
Increment function name in Python
<p>I apologise if there is already an answer to my question, I've searched stack overflow for a while but found nothing that I could use.</p> <p>I'm learning how to create classes at the moment and I've constructed classes for the explicit Runge-Kutta methods 1-4. The names of the classes are 'RK_1', 'RK_2', 'RK_3' an...
<p>You can simply pass the <code>RK_n()</code> function in as a parameter to avoid duplicating the other function:</p> <pre><code>def solve_Legendre(p,Tmax,init,dt=0.001, RK=RK_1): f = Legendre(p) solver = RK(init,f) while solver.now() &lt; Tmax: solver(dt) return solver.state() </code>...
python|string
7
1,263
24,424,909
Equation roots: parameter doesn't get simplified
<p>I am using Python with Sympy.</p> <p>I need to solve the following equation, finding the 4 roots (omega is my unknown):</p> <pre><code>deter= 0.6*omega**4*cos(omega*t)**2 - 229.0*omega**2*cos(omega*t)**2 + 5880.0*cos(omega*t)**2 </code></pre> <p>I tried to use solve:</p> <pre><code>eqcarr=solve(deter,omega,exclu...
<p>According to documentation <code>solve</code> will not solve for any of the free symbols passed in the <code>exclude</code>.</p> <blockquote> <p>'exclude=[] (default)' don't try to solve for any of the free symbols in exclude; if expressions are given, the free symbols in them will be extracted aut...
python|parameters|equation|sympy
2
1,264
24,114,801
Dict into Dict Python
<p>I am new in Python, Currently I am working data dictionary. I expect to create dict into dict like this:</p> <pre><code>dates = {201101:{perf:10, reli:20, qos:300}, 201102:{perf:40, reli:0, qos:30}} </code></pre> <p>I already have the keys, and I have to created default values for initialization. i.e:</p> <p><cod...
<p>First, you need to separate keys from their values with a <code>:</code>. Secondly, your keys need to be strings or numbers. Example.</p> <pre><code>dates = { 201101: {'perf': 10, 'reli':20, 'qos': 300} } </code></pre>
python|dictionary
1
1,265
24,103,795
pandas: Calculated column based on values in one column
<p>I have columns like this in a csv file (I load it using <code>read_csv('fileA.csv', parse_dates=['ProcessA_Timestamp'])</code>)</p> <pre><code>Item ProcessA_Timestamp 'A' 2014-06-08 03:32:20 'B' 2014-06-08 03:32:20 'A' 2014-06-08 03:33:19 'C' 2014-06-08 03:33:20 'B' 2014-06-08 03:33:40 'D' 2014...
<p>You can use the pandas groupby-apply combo. Group the dataframe by "Item" and apply a function that calculates the process time. Something like:</p> <pre><code>import pandas as pd def calc_process_time(row): ts = row["ProcessA_Timestamp].values if len(ts) == 1: return pd.NaT else: retur...
python|pandas|data-analysis
1
1,266
20,651,317
NetworkX multi-directed graph possible?
<p>I have a network for which I'm trying to figure out the best possible graph representation. I'm no graph theorist, but a biologist, so please pardon my lack of technicality here.</p> <p>Currently, the network can be thought of as follows: "n" layers of networks, each layer holding a different set of edges between t...
<p>There is a MultiDiGraph() object in NetworkX that might work in your case. You can store multiple directed edges, each with arbitrary attributes. The nodes can also have arbitrary attributes. </p> <pre><code>In [1]: import networkx as nx In [2]: G = nx.MultiDiGraph() In [3]: G.add_edge(1,2,color='green') In [4]...
python|algorithm|csv|graph|networkx
6
1,267
71,790,788
Why pandas fillna function turns non empty values to empty values?
<p>I'm trying to fill empty values with the element with max count after grouping the dataframe. Here is my code.</p> <pre><code>def fill_with_maxcount(x): try: return x.value_counts().index.tolist()[0] except Exception as e: return np.NaN df_all[&quot;Surname&quot;] = df_all.groupby(['HomePla...
<p>Finally found it after some testings with code.</p> <pre><code> df_all.groupby(['HomePlanet','CryoSleep','Destination']).Surname.apply(lambda x : x.fillna(fill_with_maxcount(x))) </code></pre> <p>The above part returns a series with filled values. But however in the rows where the fields used for grouping are empty,...
pandas|dataframe|apply|nan|fillna
0
1,268
15,216,972
Python generator yields same value each call
<p>I want this generator to yield the cosine of each successive value from a list, but am getting the same value each time.</p> <pre><code>import math angles = range(0,361,3) # calculate x coords: def calc_x(angle_list): for a in angle_list: yield round(radius * cos(radians(a)), 3) </code></pre>...
<p>Every time you call <code>calc_x</code> you create a <em>new</em> generator. What you need to do is create one and then keep using it:</p> <pre><code>calc = calc_x(angles) next(calc) next(calc) # etc. </code></pre>
python|generator
8
1,269
15,301,190
How to use the "__str__" method?
<p>I'm diving into some Object Oriented Programming. Unfortunately, I can't even get up to the first step: Converting classes to strings using <code>__str__</code>.</p> <p>Here's my code:</p> <pre><code>class Time: def __init__(self, hours = 0, minutes = 0, seconds = 0): self.hours = hours self.min...
<p>you need an <em>instance</em> of <code>Time</code>. e.g. <code>time1 = Time()</code> (Notice the parenthesis). </p> <p>As it is, you are modifying the <em>class</em>, not an <em>instance</em> of the class -- And <code>__str__</code> only tells python how to create strings from instances of the class, not the cla...
python
9
1,270
29,589,941
Detect changes to a file in Git
<p>I've looked <a href="https://stackoverflow.com/questions/3882838/whats-an-easy-way-to-detect-modified-files-in-a-git-workspace">here</a> but my question wasn't answered. I have a script that keeps a number of files up-to-date. The repository consists of a number of bash and python scripts. One of the scripts runs o...
<pre><code>git diff --name-only </code></pre> <p>gives the name of files which have changed. To avoid <code>python -m compileall</code> issue, you need to compare against <em>local branch</em>, as opposed to <em>working directory</em>, as in:</p> <pre><code>git diff --name-only dev..origin/dev </code></pre> <p>if yo...
python|git
3
1,271
29,340,765
API Test Case - 'module' object has no attribute
<pre><code>$ python manage.py test homepage.shortlistedlist </code></pre> <p>When i run above django rest framework testcase file, i met below error, kindly help me to solve this problem,</p> <pre><code>(py3.4)testuser@testuser-To:~/projects/testfile/testfile$ python manage.py test homepage.compareproperties --settin...
<p>I was able to solve this by adding an empty <code>__init__.py</code> to the root of my project.</p> <p>I think the clue is the <code>get_directory_containing_module()</code> call - without <code>__init__.py</code>, it doesn't see the directory as a module.</p>
django|python-3.x|django-rest-framework
2
1,272
46,307,880
Find the top n values per row in one data frame, and use these indices to obtain values in another data frame to perform a pair-wise operation
<p>In this case, I have two data frames A and B.</p> <pre><code> c1 c2 c3 c1 c2 c3 r0 7 6 4 r0 0 0 1 r1 6 2 5 r1 1 1 0 r2 3 5 9 r2 1 0 1 </code></pre> <p>A is the data frame on the left, and B o...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rank.html" rel="nofollow noreferrer"><code>rank</code></a> to get top 2 values and use that as mask for <code>B</code>.</p> <pre><code>In [1311]: (A*B.where(A.rank(axis=1) &gt;= 2)).sum(axis=1) Out[1311]: r0 0.0 r1 6.0 r2 ...
python|pandas|numpy|dataframe
2
1,273
49,441,372
How to iterate rows of dataframe in Content-Type: application/x-www-form-urlencoded format into API POST request?
<p>I have a dataframe that looks like this:</p> <pre><code>email p[1]: a@a.com 1 b@b.com 2 </code></pre> <p>the <code>p[1]</code> field is the list ID. </p> <p>How do I pass rows of this dataframe one at a time into the a API post request in the <code>Content-Type: application/x-www-form-urlencod...
<p>If you want to do this one at a time, you want <code>DataFrame.iterrows</code></p> <pre><code>import pandas as pd df = pd.DataFrame({'email': ['a@a.com', 'b@b.com'], 'p[1]': [1,2]}) for index, row in df.iterrows(): params = {'email': row.email, 'p[1]': row['p[1]']} print(params) {'email': 'a@a.com', 'p[1...
python|pandas|python-requests|api-design
1
1,274
49,601,259
Setup.py---nosetests: command not found
<p>I successfully installed nose on my laptop and try to run nosestest. However, terminal reminds me that: "bash: nosetests: command not found."</p> <p>What's strange is that, when I open up the Python interpreter in Terminal, and do something like:</p> <pre><code>import nose nose.main() </code></pre> <p>I get the...
<p>For ubuntu (Unix) if you do a <code>pip install nose</code> it installs nose in this folder <code>/usr/local/bin</code></p> <p>to check this do <code>echo $PATH</code> for a unix system</p> <p>it should you return a ":" separated list of folders. In this list of folders the folder with the nosetests executable nee...
python|nose|setup.py
0
1,275
21,078,836
Is there an easy way to store/view changes made to a Django Database?
<p>I've been looking around and solutions (that I can find) seem to deal mostly with general events (such as logging that a user logged into the system), or alike. Maybe my search skills have failed me, but I tried to research this and failed before asking.</p> <p><strong>Looking for:</strong> Due to the requirements ...
<p>Check out <a href="http://django-reversion.readthedocs.org/" rel="nofollow">Django-reversion</a>. I have the feeling it's exactly what you're looking for.</p>
python|database|django
0
1,276
20,981,936
python Dictread of CSV file with NUL bytes in data
<p>I have a CSV file which has NUL byte embedded within some data.</p> <p>That is given columns A B C D one of the fields in column C would have data like</p> <p>, quote character"Some Data" NUL "More Data" NUL "End of data" quote character,</p> <p>When I open it with LIBRE Office Calc, the NUL characters do not app...
<p>So this is a bit ugly, but it seems to work. You can read a line like normal, clean the offending bytes, then use a StringIO object to pass it to DictReader. Here's the code, assuming your csv has a header record (it should be more simple if you don't):</p> <pre><code>#!/usr/bin/env python import StringIO import...
python|design-patterns|csv
1
1,277
53,585,041
How to split a text file in python using the amount of words per line without using modules
<p>so I'm writing this script where a text file is to be split into lists based on the amount of words per line, I need to generate a dictionary but no need to worry about it; I'm having trouble trying to split this text:</p> <p>So let's say that I have:</p> <pre><code>word1: word word more words word2: another word...
<p>You are doing a series of operations that do not make sense – possibly they were leftovers from earlier attempts. You don't have any data with comma's in them, so <code>.split(',')</code> is obsolete. I also do not see what appending to <code>indexes</code> ought to be doing.</p> <p>Instead, take the following appr...
python|python-3.x
1
1,278
46,166,205
Display coordinates in pyqtgraph?
<p>I'm attempting to develop a GUI that allows for tracking mouse coordinates in the PlotWidget, and displaying in a label elsewhere in the main window. I have attempted several times to emulate the crosshair example in the pyqtgraph documentation, but have not been able to get it to agree to do this. A part of the dif...
<p>I was able to get the updates to work by doing the following: </p> <p>IN THE setupUi function: </p> <pre><code>Plotted = self.plot vLine = pg.InfiniteLine(angle=90, movable=False) hLine = pg.InfiniteLine(angle=0, movable=False) Plotted.addItem(vLine, ignoreBounds=True) Plotted.addItem(hLine, ignoreBounds=True) Plo...
python-3.x|pyqt5|pyqtgraph
3
1,279
45,840,789
where does the python start the code execution from?
<p>I am trying to understand that when we execute a .py file, then from which part of that code the python start the execution from? E.g.when we execute a Java program, the "public static void main(String[] args)" is the location where the java start the code execution. So, when we talk about python, how does it work?...
<p>If the Python code is in a method, no code will be executed unless you explicitly call the method (e.g. after checking <code>__name__ == '__main__'</code>). It is convention to call <code>main</code> method, but you can call any method as the starting point of execution.</p> <p>If the Python code is <em>not</em> in...
python
1
1,280
33,244,497
How can I create a SQLAlchemy query containing only instances related to a specific instance of a model?
<p>I am given an instance of a SQLAlchemy model <code>instance</code> and the name of a relationship <code>relation</code> on that instance. I can access all related instances by doing <code>getattr(instance, relation)</code>. How can I construct a <em>query</em> that contains all instances of that relationship, or in ...
<p>My solution was as follows. Assume <code>instance</code> is an instance of a model, <code>relation</code> is a string representing the relationship attribute of that model, <code>'id'</code> is the primary key for the related model, and <code>related_model</code> is the related model. This solution filters the relat...
python|sqlalchemy|introspection
0
1,281
33,234,089
What is the idiomatic way to compute values based on neighboring values, in NumPy?
<p>I am asked to experiment with numpy calculating values in a two-dimensinal array/matrix (rows, columns) where these values depend on neighboring values. This is not just multiplying the matrix with a scalar or anything like that, even though it may be reduced to a series of such steps, I admit.</p> <p>Even though t...
<p>What you're describing is very common in image processing -- there it's called <em>applying a kernel to do two-dimensional filtering</em> (just to give you something to google). From the <a href="http://docs.scipy.org/doc/scipy/reference/tutorial/ndimage.html#filter-functions" rel="nofollow noreferrer">Numpy ndimage...
python|arrays|numpy|vectorization
2
1,282
24,468,667
What's the difference between tp_clear, tp_dealloc and tp_free?
<p>I have a custom python module for fuzzy string search, implementing Levenshtein distance calculation, it contains a python type, called levtree which has two members a pointer to a wlevtree C type (called tree) which does all the calculations and a PyObject* pointing to a python-list of python-strings, called wordli...
<p><code>tp_clear</code> is only needed if you implement <a href="https://docs.python.org/2/c-api/gcsupport.html" rel="noreferrer">cyclic garbage collection</a>. It appears that this is not needed because you only maintain references to Python unicode objects.</p> <p><code>tp_dealloc</code> is called when the referenc...
python|c|python-extensions
6
1,283
24,563,303
Binary file (Labview .DAT file) conversion using Python
<p>I work in a lab where we acquire electrophysiological recordings (across 4 recording channels) using custom Labview VIs, which save the acquired data as a .DAT (binary) file. The analysis of these files can then be continued in more Labview VIs, however I would like to analyse all my recordings in Python. First, I n...
<p>Based on <a href="http://www.shocksolution.com/2008/06/reading-labview-binary-files-with-python/" rel="nofollow">this link</a> it looks like the following should do the trick:</p> <pre><code>binaryFile = open('Measurement_4.bin', mode='rb') (data.offset,) = struct.unpack('&gt;d', binaryFile.read(8)) </code></pre> ...
python|numpy|binary|labview|file-conversion
1
1,284
41,009,119
TensorFlow on Windows: "pip install tensorflow" fails
<p>I am using Visual Studio 2015, Python 3.5.2, Windows 10, and have recently upgraded pip to 9.0.1. I am trying to install Tensorflow 0.12 on my system. I tried to use VS's built in "Install Python Package" function, as well as command prompting</p> <pre><code>pip install python </code></pre> <p>Both ways I get the ...
<p>According to your Python version string, you are running the 32-bit version of the Python interpreter. We have only made PIP packages for the <strong>64-bit</strong> version of the Python 3.5, which can be downloaded and installed separately from Python.org or Anaconda.</p>
visual-studio-2015|pip|tensorflow|windows-10|python-3.5
2
1,285
38,193,959
Python: Can't turn string into JSON
<p>For the past few hours, I've been fighting to get a string into a JSON dict. I've tried everything from json.loads(... which throws an error:</p> <pre><code>requestInformation = json.loads(entry["request"]["postData"]["text"]) //throws this error json.decoder.JSONDecodeError: Expecting property name enclosed in do...
<p>the <code>json</code> module wants a string where the keys are also wrapped in double quotes</p> <p>so the string below would work:</p> <pre><code>mystring = '{"items":[{"n":"PackageChannel.GetUnitsInConfigurationForUnitType", "ps":[{"n":"unitType","v":"ActionTemplate"}]}]}' myjson = json.loads(mystring) </code></...
python|json|decode
0
1,286
31,149,781
Grouping data by value in first column
<p>I'm trying to group data from a 2 column object based on the value of a first column. I need this data in a list so I can sort them afterwards. I am fetching interface data with snmp on large number of machines. In the example I have 2 interfaces. I need data grouped by interface preferably in a list.</p> <p>Data i...
<p>Not sure I follow your sorting as I don't see any order but to group you can use a dict grouping by <code>oid</code> using a <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow">defaultdict</a> for the repeating keys:</p> <pre><code>data = """ifDescr lo ifDescr eth0 if...
python|sorting|grouping
2
1,287
30,821,808
Python list comprehension - need elements skipped combinations
<p>For this input list </p> <pre><code>[0, 1, 2, 3, 4, 5] </code></pre> <p>I need this output </p> <pre><code>[[0, 2], [0, 3], [0, 4], [0, 5], [1, 3], [1, 4], [1, 5], [2, 4], [2, 5], [3, 5], [0, 2, 3], [0, 3, 4], [0, 4, 5], [1, 3, 4], [1, 4, 5], [2, 4, 5], [0, 2, 3, 4], [0, 3, 4, 5], [1, 3, 4, 5]] ...
<p>Try to describe with words your problem.</p> <p>From what I understand from your example:</p> <pre><code>def good(x): return x[0]+1!=x[1] and all(i+1==j for i,j in zip(x[1:],x[2:])) from itertools import combinations [i for j in range(2,5) for i in filter(good, combinations(l,j))] </code></pre> <blockquote> <p...
python|list|list-comprehension
5
1,288
30,856,133
irregular slicing/copying in numpy array
<p>Suppose I have an array with 10 elements, e.g. <code>a=np.arange(10)</code>. If I want to create another array with the 1st, 3rd, 5th, 7th, 9th, 10th elements of the original array, i.e. <code>b=np.array([0,2,4,6,8,9])</code>, how can I do it efficiently?</p> <p>thanks</p>
<pre><code>a[[0, 2, 4, 6, 8, 9]] </code></pre> <p>Index <code>a</code> with a list or array representing the desired indices. (Not <code>1, 3, 5, 7, 9, 10</code>, because indexing starts from 0.) It's a bit confusing that the indices and the values are the same here, so have a different example:</p> <pre><code>&gt;&g...
arrays|numpy|copy|scipy|slice
1
1,289
40,247,825
Using Python ARMA model fit
<p>I have a time series data and I am trying to fit ARMA(p,q) model to it but I am not sure what 'p' and 'q' to use. I came across this link <a href="http://statsmodels.sourceforge.net/devel/generated/statsmodels.tsa.arima_model.ARMA.fit.html" rel="nofollow">enter link description here</a></p> <p>The usage for this mo...
<p>You'll have to do a bit of reading outside of the statsmodel package documentation. </p> <p>See some of the content in this answer: <a href="https://stackoverflow.com/a/12361198/6923545">https://stackoverflow.com/a/12361198/6923545</a></p> <p>There's a guy named Rob Hyndman who wrote a great book on forecasting a...
python|statsmodels
1
1,290
29,102,415
Artifactory PyPi repo layout with build promotion
<p><strong>Q1:</strong> I have an Artifactory PyPi enabled repo <em>my-pypi-repo</em> where I can publish my packages. When uploading via python <code>setup.py -sdist</code>, I get a structure like this:</p> <pre><code>my-pypi-repo| |my_package| |x.y.z| |...
<p>I am running into the same issue in regards to your first question/problem. When configuring my system to publish to artifactory using pip, it uses the format you described.</p> <p>As you mentioned, the <code>[org]</code> or <code>[orgPath]</code> is mandatory and this basically breaks all the REST API functionali...
python|artifactory
3
1,291
52,304,492
Error: Could not find or load main class net.minecraft.launchwrapper.Launch when launching Minecraft 1.12.2 with Forge
<p>I've written a launcher for Minecraft 1.12.2 in Python, which just prepares a command and runs it using subprocess.</p> <p>This is the command formed on Linux Ubuntu:</p> <pre><code>#!/usr/bin/env bash java -Xmx4G -XX:+UnlockExperimentalVMOptions -XX:+UseG1GC -XX:G1NewSizePercent=20 -XX:G1ReservePercent=20 -XX:Ma...
<p>Ok, actually, on Windows the classpath separator is ; not : Replacing separator fixes this issue</p>
java|python|windows|ubuntu|minecraft
2
1,292
62,407,058
Merge rows from multiple CSV files into one CSV file and keep same number of columns
<p>I have 3 CSV files (separated by ',') with no headers and need to concat them into one file:</p> <p>file1.csv</p> <pre><code>United Kingdom John </code></pre> <p>file2.csv </p> <pre><code>France Pierre </code></pre> <p>file3.csv </p> <pre><code>Italy Marco </code></pre> <p>expected result:</p> <pre><c...
<p>Pandas usually infer the column name from the first row when reading CSV file. One thing you can do here is to check each data frame's header, which you should expect to see the sample data is treated as header.</p> <p>In order to override this default behaviour, you can use <code>names</code> field to explicitly s...
python|pandas|csv
1
1,293
67,522,690
Reshaping NumPy Array with Index Locations in Columns
<p>I have a 3 column numpy array, as follows</p> <pre><code>[0 0 'a' 0 1 'b' 1 0 'c' 1 1 'd'] </code></pre> <p>The first column contains the row index for the 3rd columns value, and the second column the column index. That is, the final output should be</p> <pre><code>['a' 'b' 'c' 'd'] </code></pre> <p>How can I us...
<p>You can use <a href="https://numpy.org/doc/stable/reference/arrays.indexing.html#advanced-indexing" rel="nofollow noreferrer">numpy advanced indexing</a> to place the values in an empty instantiated array. Here's an example assuming the third column is actually numeric, with the values <code>[1, 3, 5, 7]</code>, and...
python|arrays|numpy
0
1,294
19,631,993
What is an efficient way to check if a name exists in sqlalchemy, python
<p>currently I'm using a for loop to check if a record exists,</p> <pre><code>def IsUserPrivileged(name): namequery = Ops.query.all() for names in namequery: if name == namequery.name: return True else: return False </code></pre> <p>So theres a database of ops with an Id field and a name field...
<p>You were almost there:</p> <pre><code>def is_user_privileged(name): namequery = Ops.query.filter(name==name) if namequery.count(): return True else: return False </code></pre> <p>But you can optimize your function further:</p> <pre><code>def is_user_privileged(name): namequery = Ops....
python|sqlalchemy
2
1,295
19,489,132
Python: Passing value of a string variable as argument in Popen
<p>What is the proper way to pass values of string variables to Popen function in Python? I tried the below piece of code</p> <pre><code>var1 = 'hello' var2 = 'universe' p=Popen('/usr/bin/python /apps/sample.py ' + '"' + str(eval('var1')) + ' ' + '"' + str(eval('var2')), shell=True) </code></pre> <p>and in sample.py,...
<p>This should work:</p> <pre><code>p = Popen('/usr/bin/python /apps/sample.py {} {}'.format(var1, var2), shell=True) </code></pre> <p>Learn about <a href="http://docs.python.org/2/library/string.html#format-examples" rel="nofollow">string formatting </a>.</p> <p>Second, passing arguments to scripts has its quirks: ...
python
1
1,296
13,289,291
Python: subprocess.communicate(): ValueError with print() function but not "print" builtin
<p>I'm trying to run a C program from Python with the subprocess module, capturing its output in a variable. the code looks like this:</p> <pre><code>process = Popen(["myprog", str(length), filename], stdout=PIPE, stderr=PIPE) #wait for the process result = process.communicate() end=time() print result </code></pre> ...
<p>This is <em>not</em> a Python problem. You have a problem with <code>myprog</code>, not Python.</p> <p>In Python 2, the difference between <code>print something</code> and <code>print(something)</code> is null and void. There is <em>no</em> difference at all because the Python compiler sees the parenthesis as a no-...
python|printing|subprocess|popen
4
1,297
13,244,212
Prevent duplicate of multiple constraint sqlite3 python
<p>Suppose I have a table :</p> <pre><code>Table A: Id Name Movie Comment 1 Foo Bar anything 2 Foo Bar anything </code></pre> <p>Here I want to make sure that the user cannot insert Foo and Bar twice , but he is allowed to insert Foo , foobar . One solution to prevent this duplication was to add ...
<pre><code>CREATE UNIQUE INDEX IDX_Movies ON table(Name, Movie) </code></pre> <p>This is standard SQL, and documented at <a href="http://sqlite.org/lang_createindex.html" rel="nofollow">http://sqlite.org/lang_createindex.html</a>. (SQLite's on-line documentation is pretty comprehensive)</p>
python|sqlite
1
1,298
22,247,904
How to style (rich text) in QListWidgetItem and QCombobox items? (PyQt/PySide)
<p>I have found similar questions being asked, but without answers or where the answer is an alternative solution.</p> <p>I need to create a breadcrumb trail in both QComboBoxes and QListWidgets (in PySide), and I'm thinking making these items' text bold. However, I have a hard time finding information on how to achie...
<p>You could use html/css-likes styles, i.e just wrap your text inside tags:</p> <pre><code>item.setData( QtCore.Qt.UserRole, "&lt;b&gt;{0}&lt;/b&gt;".format('data to store for this QListWidgetItem')) </code></pre> <p>Another option is setting a font-role:</p> <pre><code>item.setData(0, QFont("myFontFamily",italic=...
python|pyqt|pyside
6
1,299
54,671,706
specify data type of columns in a dataframe returned from SQL server
<p>I am retrieving data from a SQL Server database using pandas with the line below.</p> <pre><code>df = pd.read_sql_query(query, cnxn) </code></pre> <p>So a dataframe is returned which is want I want. However I have noticed that the columns are not always the correct data type, for example sometimes a number will b...
<p>By default you have <code>coerce_float=True</code>, and you can feed a list of date columns into <code>parse_dates</code>. You don't have explicit <code>dtypes</code> support as in <code>read_csv</code> and other IO methods. There's a discussion about it <a href="https://github.com/pandas-dev/pandas/issues/6798" rel...
python|pandas|dataframe
1