title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
What are built-in identifiers in Python? | 38,364,868 | <p>I was reading <a href="https://docs.python.org/2/tutorial/errors.html#exceptions" rel="nofollow">Python tutorial</a> and came across this line which I couldn't understand:</p>
<blockquote>
<p>Standard exception names are built-in identifiers (not reserved
keywords).</p>
</blockquote>
<p>What is meant by <code>... | 1 | 2016-07-14T03:10:30Z | 38,364,922 | <p>In Python, an identifier is the name given to a particular entity, be it a class, variable, function etc. For example, when I write:</p>
<pre><code>some_variable = 2
try:
x = 6 / (some_variable - 2)
except ZeroDivisionError:
x = None
</code></pre>
<p>both <code>some_variable</code> and <code>x</code> are i... | 1 | 2016-07-14T03:20:03Z | [
"python",
"python-2.7"
] |
What are built-in identifiers in Python? | 38,364,868 | <p>I was reading <a href="https://docs.python.org/2/tutorial/errors.html#exceptions" rel="nofollow">Python tutorial</a> and came across this line which I couldn't understand:</p>
<blockquote>
<p>Standard exception names are built-in identifiers (not reserved
keywords).</p>
</blockquote>
<p>What is meant by <code>... | 1 | 2016-07-14T03:10:30Z | 38,364,952 | <p>Identifiers are 'variable names'. Built-ins are, well, built-in objects that come with Python and don't need to be imported. They are associated with identifiers in the same way we can associate 5 with <code>foo</code> by saying <code>foo = 5</code>.</p>
<p>Keywords are special tokens like <code>def</code>. Identif... | 1 | 2016-07-14T03:23:25Z | [
"python",
"python-2.7"
] |
What are built-in identifiers in Python? | 38,364,868 | <p>I was reading <a href="https://docs.python.org/2/tutorial/errors.html#exceptions" rel="nofollow">Python tutorial</a> and came across this line which I couldn't understand:</p>
<blockquote>
<p>Standard exception names are built-in identifiers (not reserved
keywords).</p>
</blockquote>
<p>What is meant by <code>... | 1 | 2016-07-14T03:10:30Z | 38,364,955 | <p>It is exactly what you think it is, a name of a thing which isn't a function, and isn't a command like "while", and comes built-in to Python. e.g.</p>
<p>A function is something like <code>open()</code>, a keyword is something like <code>while</code> and an identifier is something like <code>True</code>, or <code>I... | 3 | 2016-07-14T03:23:47Z | [
"python",
"python-2.7"
] |
What are built-in identifiers in Python? | 38,364,868 | <p>I was reading <a href="https://docs.python.org/2/tutorial/errors.html#exceptions" rel="nofollow">Python tutorial</a> and came across this line which I couldn't understand:</p>
<blockquote>
<p>Standard exception names are built-in identifiers (not reserved
keywords).</p>
</blockquote>
<p>What is meant by <code>... | 1 | 2016-07-14T03:10:30Z | 38,365,627 | <p>You can get all the builtins using following command ...</p>
<pre><code>dir(__builtins__)
</code></pre>
<p>it will give following output</p>
<pre><code>>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'Byte... | 0 | 2016-07-14T04:42:19Z | [
"python",
"python-2.7"
] |
why python need to open file every time when we use the data? | 38,364,923 | <p>The code below have two same lines, but I think fr is already opened by the first line. I try to remove the second lines, but the code failed. So why we need to the open file everytime when we use it?</p>
<pre><code>def file2matrix(filename):
fr = open(filename) #<-------------------------
numberOfLines ... | 0 | 2016-07-14T03:20:12Z | 38,365,081 | <p>You don't need to reopen the file, but you do need to go back to the beginning.</p>
<p>The readline() function reads a line in a file. Each time you call readline(), the pointer will move to the next line.</p>
<p>readlines() calls readline() until it gets to the end of the file. If you want to move back to the beg... | 1 | 2016-07-14T03:41:19Z | [
"python",
"function",
"built-in"
] |
Why are python static/class method not callable? | 38,364,980 | <p>Why are python instance methods callable, but static methods and class methods not callable?</p>
<p>I did the following:</p>
<pre><code>class Test():
class_var = 42
@classmethod
def class_method(cls):
pass
@staticmethod
def static_method():
pass
def instance_method(self... | 5 | 2016-07-14T03:27:37Z | 39,714,862 | <p>The instance is the container where the object's data is stored (in the self) variable.</p>
| 1 | 2016-09-27T01:54:33Z | [
"python",
"oop",
"methods"
] |
render django tag inside textfield written in html | 38,364,998 | <p>im a beginner in django and general programming and would like to ask a questions regarding how to render django model field in html save inside textfield.</p>
<p>my code snippet as per below: </p>
<p>models.py </p>
<pre><code>class Recipe(models.Model):
recipe_name = models.CharField(max_length=128)
reci... | 0 | 2016-07-14T03:31:20Z | 38,365,204 | <p>You need to link Recipe to Ingredients:</p>
<pre><code>class Ingredient(models.Model):
ingredient_name = models.CharField(max_length=200)
ingredient_text = models.TextField()
def __str__(self):
return self.ingredient_name
class Recipe(models.Model):
recipe_name = models.CharField(max_lengt... | 0 | 2016-07-14T03:56:20Z | [
"python",
"html",
"django"
] |
How to increase all the prices which is dict values by 10% | 38,365,106 | <p>How do we increase all prices in menu which the values by 10%.</p>
<p><strong>Code:</strong></p>
<pre><code>burger = {'Fiery Pepper' : 5.65,'McSpicy':'4.85','Quarter Pounder':'4.20','Cheeseburger':'2.35'}
beverages = {'Hot Tea':2.60,'McCafe':2.70,'Coca-Cola':2.65}
menu ={}
menu.update(burger)
menu.update(beverages... | 1 | 2016-07-14T03:43:43Z | 38,365,142 | <p>Multiply them by <strong><code>1.1</code></strong> (or <strong>110%</strong> of original):</p>
<pre><code>burgers = {k: float(v) * 1.1 for k, v in burgers.items()}
beverages = {k: float(v) * 1.1 for k, v in beverages.items()}
</code></pre>
| 3 | 2016-07-14T03:48:15Z | [
"python",
"dictionary"
] |
Selenium webdriver could not perform button click | 38,365,294 | <p>I faced a problem of the button click issue by using selenium webdriver.
I'm trying to click the "like button" but it did not work.</p>
<p>Here is my selenium source code:</p>
<pre><code>driver = webdriver.Chrome(executable_path=cwd+'chromedriver', chrome_options=chrome_options)
driver.get('https://tw.carousell.co... | 0 | 2016-07-14T04:06:08Z | 38,366,026 | <p>"Like" button is not visible initially, so you cannot just click on it- you should make if visible first, so try following code:</p>
<pre><code>number = 0
driver.execute_script('document.querySelectorAll("button.btn.btn-default.pdt-card-like")[number].style.display="block";')
driver.execute_script('document.querySe... | 1 | 2016-07-14T05:20:02Z | [
"python",
"selenium",
"selenium-webdriver",
"automation"
] |
Selenium webdriver could not perform button click | 38,365,294 | <p>I faced a problem of the button click issue by using selenium webdriver.
I'm trying to click the "like button" but it did not work.</p>
<p>Here is my selenium source code:</p>
<pre><code>driver = webdriver.Chrome(executable_path=cwd+'chromedriver', chrome_options=chrome_options)
driver.get('https://tw.carousell.co... | 0 | 2016-07-14T04:06:08Z | 38,366,122 | <p>I believe you need to hover to the thumbnail before the like button will appear. Try to separate move_to_element and click into 2 separate methods and give a sleep in between.
Sorry, I don't know Python, but it should look like this.</p>
<pre><code>webdriver.ActionChains(driver).move_to_element(like_button).perform... | 0 | 2016-07-14T05:29:57Z | [
"python",
"selenium",
"selenium-webdriver",
"automation"
] |
Get city polygon from name | 38,365,324 | <p>In python. I have the name of the city/postal address and I wish to find out the coordinates of a polygon around it. I did read about it at a lot of places but couldn't get the concrete guidance.</p>
<pre><code>import json
import requests
from urllib.parse import urlencode
import pprint
base_url="https://maps.goog... | 0 | 2016-07-14T04:09:44Z | 38,365,466 | <p>I'm not sure quite what your question is. But given your export, you can get the coordinates out of it with:</p>
<pre><code>export = """{
"type": "FeatureCollection",
[..]
}"""
import json
results = json.loads(export)
print results['features'][0]['geometry']['coordinates'][0]
</code></pre>
<p>Try it online:... | 0 | 2016-07-14T04:24:04Z | [
"python",
"python-2.7"
] |
Logistic regression does not work after update to v.0.17 | 38,365,341 | <p>I had something similar to this:</p>
<pre><code>linear_model.LogisticRegression(penalty='l2').fit(X_train, y_train)
</code></pre>
<p>where X_train</p>
<pre><code>array([[ 2500. , 5000. , 5000. , ..., 4697.2, 3. , 10600. ],
...,
[ 2500. , 3500. , 3500. , ..., 3072. , 3. , 1... | 0 | 2016-07-14T04:11:16Z | 38,365,579 | <p>I think you want a <code>LinearRegression</code>; logistic regression is actually a classification model (despite the misleading name). Not sure what your code was doing in the previous version, maybe it was treating each of the float values as a label?</p>
| 3 | 2016-07-14T04:36:57Z | [
"python",
"machine-learning",
"scikit-learn"
] |
Beautiful soup strategy for splitting data | 38,365,344 | <p>I want to parse through a webpage like this and gather only the names of starters:</p>
<p><a href="http://espn.go.com/nba/boxscore?gameId=400827888" rel="nofollow">http://espn.go.com/nba/boxscore?gameId=400827888</a></p>
<p>My script grabs all the names on the page, but I cannot discriminate when the starters for ... | 1 | 2016-07-14T04:11:48Z | 38,365,716 | <p>If you use pandas instead of beautiful soup it will parse out the tables separately. it only gets the starters, not the bench players though, so hopefully this isn't an issue.</p>
<pre><code>import pandas as pd
pd.read_html('http://www.espn.com.au/nba/boxscore?gameId=400827888')
[ Unnamed: 0 1 2 3 4 T... | 0 | 2016-07-14T04:51:00Z | [
"python",
"osx",
"beautifulsoup",
"iteration"
] |
Beautiful soup strategy for splitting data | 38,365,344 | <p>I want to parse through a webpage like this and gather only the names of starters:</p>
<p><a href="http://espn.go.com/nba/boxscore?gameId=400827888" rel="nofollow">http://espn.go.com/nba/boxscore?gameId=400827888</a></p>
<p>My script grabs all the names on the page, but I cannot discriminate when the starters for ... | 1 | 2016-07-14T04:11:48Z | 38,383,876 | <p>If all you want are the starters it is pretty straight forward, just pull the first tbody inside the <em>div.content.hide-bench</em> and extract the text from the <em>td.name</em> tags:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
teams = {}
page = requests.get('http://espn.go.com/nba/boxscore?gameI... | 1 | 2016-07-14T20:39:11Z | [
"python",
"osx",
"beautifulsoup",
"iteration"
] |
Remove nth row in groupby | 38,365,363 | <p>I want to remove the nth row of a groupby object, say the last row. I can extract this row using <code>groupby.nth</code></p>
<p>Is there a similar method to remove the nth row, or equivalently get all the rows except the nth row?</p>
| 3 | 2016-07-14T04:13:50Z | 38,365,605 | <p>Assume <code>df</code> is your dataframe.</p>
<pre><code>df.groupby(something_to_group_by).apply(lambda x: x.iloc[:-1, :]).reset_index(0, drop=True).sort_index()
</code></pre>
| 0 | 2016-07-14T04:39:34Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
Remove nth row in groupby | 38,365,363 | <p>I want to remove the nth row of a groupby object, say the last row. I can extract this row using <code>groupby.nth</code></p>
<p>Is there a similar method to remove the nth row, or equivalently get all the rows except the nth row?</p>
| 3 | 2016-07-14T04:13:50Z | 38,365,744 | <p>You can find index of all <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.nth.html" rel="nofollow"><code>nth</code></a> rows and then select <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.difference.html" rel="nofollow"><code>Index.difference</c... | 3 | 2016-07-14T04:53:34Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
Compare similarity between names | 38,365,389 | <p>I have to make a cross-validation for some data based on names.</p>
<p>The problem I'm facing is that depending on the source, names have slight variations, for example:</p>
<pre><code>L & L AIR CONDITIONING vs L & L AIR CONDITIONING Service
BEST ROOFING vs ROOFING INC
</code></pre>
<p>I have several t... | 1 | 2016-07-14T04:16:49Z | 38,365,913 | <p>You're going to need to figure out what it means for names to be similar.
Slight spelling differences will be hard - I wouldn't focus on that.</p>
<p>Let's say you have three variations:<br>
- uppercase/lowercase<br>
- additional words<br>
- punctuations vs spaces </p>
<p>I would suggest splitting eac... | 0 | 2016-07-14T05:09:27Z | [
"python",
"machine-learning",
"nlp"
] |
Compare similarity between names | 38,365,389 | <p>I have to make a cross-validation for some data based on names.</p>
<p>The problem I'm facing is that depending on the source, names have slight variations, for example:</p>
<pre><code>L & L AIR CONDITIONING vs L & L AIR CONDITIONING Service
BEST ROOFING vs ROOFING INC
</code></pre>
<p>I have several t... | 1 | 2016-07-14T04:16:49Z | 38,365,964 | <p>I would use cosine similarity to achieve the same. It will give you a matching score of how close the strings are.</p>
<p>Here is the code to help you with the same (I remember getting this code from Stackoverflow itself, some months ago - couldn't find the link now)</p>
<pre><code>import re, math
from collections... | 3 | 2016-07-14T05:14:01Z | [
"python",
"machine-learning",
"nlp"
] |
Compare similarity between names | 38,365,389 | <p>I have to make a cross-validation for some data based on names.</p>
<p>The problem I'm facing is that depending on the source, names have slight variations, for example:</p>
<pre><code>L & L AIR CONDITIONING vs L & L AIR CONDITIONING Service
BEST ROOFING vs ROOFING INC
</code></pre>
<p>I have several t... | 1 | 2016-07-14T04:16:49Z | 38,365,994 | <p>You might be able to just use the <a href="https://en.wikipedia.org/wiki/Levenshtein_distance" rel="nofollow">Levenshtein distance</a>, which is a good way to calculate difference between two strings. </p>
| 2 | 2016-07-14T05:16:41Z | [
"python",
"machine-learning",
"nlp"
] |
Compare similarity between names | 38,365,389 | <p>I have to make a cross-validation for some data based on names.</p>
<p>The problem I'm facing is that depending on the source, names have slight variations, for example:</p>
<pre><code>L & L AIR CONDITIONING vs L & L AIR CONDITIONING Service
BEST ROOFING vs ROOFING INC
</code></pre>
<p>I have several t... | 1 | 2016-07-14T04:16:49Z | 38,435,085 | <p>You could probably try using <code>Fuzzy String Matching</code>. You can use <a href="https://github.com/seatgeek/fuzzywuzzy" rel="nofollow">this</a> Python Library.</p>
<p>It internally uses the Levenshtein Distance(as suggested by @user3080953) to calculate the similarity between two words/phrases.</p>
<pre><cod... | 1 | 2016-07-18T11:04:01Z | [
"python",
"machine-learning",
"nlp"
] |
In Python, can I define a named tuple using typename? | 38,365,514 | <p>I wonder why the third line in <strong>Snippet B</strong> would trigger an error. My understanding is in the second line in Snippet B (and A), I created a class variable (not a class instance) <code>cls_obj</code> whose type/class name is <code>Duck</code>. It's like </p>
<pre><code>class Duck(...):
...Code goe... | 0 | 2016-07-14T04:29:36Z | 38,376,041 | <p>In Python, a class is just a special kind of value.</p>
<pre><code>class Duck(object):
pass
# 'Duck' is just a variable, you can change it
Duck = 3
x = Duck() # Fails!
</code></pre>
<p>You can do things like this:</p>
<pre><code>>>> class Goat(object):
... def __repr__(self):
... return... | 1 | 2016-07-14T13:49:09Z | [
"python",
"class",
"tuples",
"namedtuple"
] |
How can I open a CSV file in iPython? | 38,365,570 | <p>I'm a newbie to Python. I downloaded a csv file to use. I use the Anaconda package in Python 2.7 on Windows 8.1. I can open and read the file in Spyder perfectly, but when I try to open it in the iPython shell, i get the following error message:</p>
<pre><code> [Errno 2] No such file or directory: 'C:/Users/User/D... | 0 | 2016-07-14T04:35:56Z | 38,366,726 | <p>The issue is one of finding and properly naming the file. I would suggest using</p>
<pre><code>%pwd
</code></pre>
<p>to find out what the current directory is.</p>
<pre><code>%ls
</code></pre>
<p>to see what is in that directory</p>
<p>and </p>
<pre><code>%cd ...
</code></pre>
<p>to change to the right subdi... | 1 | 2016-07-14T06:13:23Z | [
"python",
"python-2.7",
"csv",
"ipython",
"spyder"
] |
How can I open a CSV file in iPython? | 38,365,570 | <p>I'm a newbie to Python. I downloaded a csv file to use. I use the Anaconda package in Python 2.7 on Windows 8.1. I can open and read the file in Spyder perfectly, but when I try to open it in the iPython shell, i get the following error message:</p>
<pre><code> [Errno 2] No such file or directory: 'C:/Users/User/D... | 0 | 2016-07-14T04:35:56Z | 38,367,309 | <p>I am not aware of working with python in windows but Here I am giving the solution to the problem opening the csv file in ipython notebook.</p>
<p>Before using this code please check the path of the csv file.</p>
<p><strong>Loading csv file in ipython notebook</strong></p>
<pre><code>import pandas as pd
DSI_data_... | 0 | 2016-07-14T06:49:14Z | [
"python",
"python-2.7",
"csv",
"ipython",
"spyder"
] |
Beautiful Soup won't return full table in from HTML object | 38,365,799 | <p>I have this web page: <a href="http://waterdata.usgs.gov/nwis/wys_rpt?dd_parm_cds=002_00060&wys_water_yr=2015&site_no=06935965" rel="nofollow">http://waterdata.usgs.gov/nwis/wys_rpt?dd_parm_cds=002_00060&wys_water_yr=2015&site_no=06935965</a></p>
<p>That I was hoping to scrape this information from... | 2 | 2016-07-14T04:58:39Z | 38,365,824 | <p>You just need to <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser" rel="nofollow">change the parser</a> to a more lenient one:</p>
<pre><code>soup = BeautifulSoup(r.text, 'html5lib')
</code></pre>
<p><code>lxml</code> would handle this case as well:</p>
<pre><code>soup = Beautif... | 2 | 2016-07-14T05:00:34Z | [
"python",
"web-scraping",
"beautifulsoup",
"html-parsing",
"python-requests"
] |
matplotlib Venn diagram, 6 circles | 38,365,860 | <p>I can make 2 and 3 circles with matplotlib_venn. Any possible to plot Venn diagram more than 3?</p>
<p>In my case I have 6 set of data and try to plot Venn diagram with 6 circles</p>
| 1 | 2016-07-14T05:03:47Z | 38,365,961 | <p>I don't think so. The <a href="https://pypi.python.org/pypi/matplotlib-venn" rel="nofollow">matplotlib-venn documentation</a> says:</p>
<blockquote>
<p>The package provides four main functions: venn2, venn2_circles, venn3 and venn3_circles.</p>
</blockquote>
<p>Where <strong>venn2</strong> is used to "draw a two... | 1 | 2016-07-14T05:13:54Z | [
"python",
"matplotlib",
"plot",
"venn-diagram",
"matplotlib-venn"
] |
Python 3.5 sqlite3 passing parameter of string - Incorrect number of bindings supplied | 38,365,902 | <p>Error:</p>
<blockquote>
<p>c = dbConnection.execute("SELECT compid FROM " + tableToUse + " WHERE
id = ?", id)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 2 supplied.</p>
</blockquote>
<p>When I do:</p>
<pre><code>def getcompid (dbConnectio... | 0 | 2016-07-14T05:07:59Z | 38,365,942 | <p>The bindings need to be in a list or tuple. Try this:</p>
<pre><code>c = dbConnection.execute(
"SELECT compid FROM " + tableToUse + " WHERE id = ?", [id])
</code></pre>
| 1 | 2016-07-14T05:12:33Z | [
"python",
"sqlite3"
] |
Making an list of dictionary unique is not working in python | 38,366,060 | <p>I have duplicates in list of dictionary but i could not make it unqiue when i use set in python</p>
<pre><code>>>> b = [
{"email_address": "aaa", "verify_score": "75"},
{"email_address": "bbb", "verify_score": "75"},
{"email_address": "Emailjcb.ab.baseball@gmail.com", "verify_score": "10"},
... | 1 | 2016-07-14T05:22:55Z | 38,366,159 | <p>As suggested by Julien in the comments, you can convert to a hashable type like tuple, and then do your unique over that:</p>
<pre><code>>>> set(tuple(d.items()) for d in b)
set([(('verify_score', '10'), ('email_address', 'carolpaterick@gmail.com')), (('verify_score', '10'), ('email_address', '37a11ce00909... | 0 | 2016-07-14T05:33:13Z | [
"python",
"dictionary",
"set",
"duplicates",
"unique"
] |
Making an list of dictionary unique is not working in python | 38,366,060 | <p>I have duplicates in list of dictionary but i could not make it unqiue when i use set in python</p>
<pre><code>>>> b = [
{"email_address": "aaa", "verify_score": "75"},
{"email_address": "bbb", "verify_score": "75"},
{"email_address": "Emailjcb.ab.baseball@gmail.com", "verify_score": "10"},
... | 1 | 2016-07-14T05:22:55Z | 38,366,187 | <p>Python dictionaries are <em>unhashable</em> which means they are mutable containers. They are not integers or strings that are always the same; the order of contents can change but semantically be the same.</p>
<p>What you could do is try to change the dictionaries into frozensets, or some other hashable type.</p>
... | 0 | 2016-07-14T05:35:40Z | [
"python",
"dictionary",
"set",
"duplicates",
"unique"
] |
Why would one use binary integer literals instead of integers or floats in python? | 38,366,081 | <p>Shouldn't we keep code as simple and easy to understand as possible? What are the advantages of binary over floats and integers in python and is it possible to create floats with binary. Also, when would you use it?</p>
| -5 | 2016-07-14T05:25:34Z | 38,366,240 | <p>Assuming that you mean:</p>
<blockquote>
<p>Why does Python have binary <a href="https://docs.python.org/3/reference/lexical_analysis.html#integer-literals" rel="nofollow">integer literals</a>?</p>
</blockquote>
<p>e.g. allowing <code>0b1010</code> as well as <code>10</code>, then the answer is that sometimes t... | 2 | 2016-07-14T05:39:46Z | [
"python",
"binary"
] |
Insert a value in the middle of iterating value in template tag | 38,366,140 | <p>I am using for loop in django template to iterate the list and my goal is to display a string every after 3 values.</p>
<p>this is my list</p>
<pre><code>myList = [1,2,3,4,5,6,7,8,9]
</code></pre>
<p>This is my code</p>
<pre><code>{% for a in myList %}
{{a}}
{% if forloop.counter == 3%}
<div>String</di... | 0 | 2016-07-14T05:32:00Z | 38,366,425 | <p>You can do as advised Kapil Sachdev</p>
<pre><code>{% for a in myList %}
{{ a }}
{% if forloop.counter|divisibleby:3 %}
<div>String</div>
{% endif %}
{% endfor %}
</code></pre>
<p>or you can use <a href="https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#cycle" rel="nofol... | 1 | 2016-07-14T05:52:43Z | [
"python",
"django"
] |
How to read text file's key, value pair using pandas? | 38,366,494 | <p>I want to parse one text file which contains following data.</p>
<p><strong>Input.txt-</strong></p>
<pre><code>1=88|11=1438|15=KKK|45=7.7|45=00|21=66|86=a
4=13|4=1388|49=DDD|8=157.73|67=00|45=08|84=b|45=k
6=84|41=18|56=TTT|67=1.2|4=21|45=78|07=d
</code></pre>
<p>In this input text file no columns are fixed it may... | 1 | 2016-07-14T05:57:10Z | 38,366,743 | <p>You can first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a> with separator which is not in data e.g. <code>;</code>, then double <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow">... | 3 | 2016-07-14T06:14:52Z | [
"python",
"pandas",
"dataframe",
"key",
"value"
] |
Run exe with python script which is called by web browser | 38,366,745 | <p>I am running an exe with python script which is called by the web browser.</p>
<p>Exe file is stored on server side.
Exe file takes an input file and in output returns several text files. The python script running the exe is as follows:</p>
<pre><code>import subprocess
print ("Hello I am in python script")
args =... | 2 | 2016-07-14T06:14:54Z | 38,366,961 | <p>You have the redirect the output to the page, doing something like this before printing stuff out.</p>
<pre><code>sys.stdout.write("Content-Type: text/html\r\n\r\n")
</code></pre>
<p>Maybe this can help you:
<a href="http://stackoverflow.com/questions/1873735/display-the-result-on-the-webpage-as-soon-as-the-data-i... | 0 | 2016-07-14T06:28:12Z | [
"python",
"c",
"subprocess",
"cgi",
"exe"
] |
How does Python interpreter work in dynamic typing? | 38,366,857 | <p>I read this question, but it didn't give me a clear answer:
<a href="http://stackoverflow.com/questions/25363034/how-does-python-interpreter-look-for-types">How does Python interpreter look for types?</a></p>
<p>How does python interpreter know the type of a variable? I'm not looking how do get the type. I'm here l... | 3 | 2016-07-14T06:21:18Z | 38,366,927 | <p>The concept "type" of a variable is "implemented" by using objects of a specific class.</p>
<p>So in</p>
<p><code>a=float()</code></p>
<p>an object of type <code>float</code>, as defined by the class <code>float</code> is returned by <code>float()</code>. Python knows what type it is because that's how objects ... | 0 | 2016-07-14T06:26:06Z | [
"python",
"python-internals",
"dynamic-typing"
] |
How does Python interpreter work in dynamic typing? | 38,366,857 | <p>I read this question, but it didn't give me a clear answer:
<a href="http://stackoverflow.com/questions/25363034/how-does-python-interpreter-look-for-types">How does Python interpreter look for types?</a></p>
<p>How does python interpreter know the type of a variable? I'm not looking how do get the type. I'm here l... | 3 | 2016-07-14T06:21:18Z | 38,367,112 | <blockquote>
<p>how does it associate the class int or string to my variable</p>
</blockquote>
<p>Python doesn't. <em>Variables have no type</em>. Only the object that a variable references has a type. Variables are simply <em>names pointing to objects</em>.</p>
<p>For example, the following also shows the type of ... | 6 | 2016-07-14T06:38:39Z | [
"python",
"python-internals",
"dynamic-typing"
] |
How does Python interpreter work in dynamic typing? | 38,366,857 | <p>I read this question, but it didn't give me a clear answer:
<a href="http://stackoverflow.com/questions/25363034/how-does-python-interpreter-look-for-types">How does Python interpreter look for types?</a></p>
<p>How does python interpreter know the type of a variable? I'm not looking how do get the type. I'm here l... | 3 | 2016-07-14T06:21:18Z | 38,367,680 | <p>Python variables have no type, they are just references to objects. The size of a reference is the same regardless of what it is referring to. In the C implementation of Python it is a pointer, and <em>does</em> have a type, it a pointer to a Python object: <code>PyObject *</code>. The pointer is the same type re... | 0 | 2016-07-14T07:08:52Z | [
"python",
"python-internals",
"dynamic-typing"
] |
Python - how to make BMP into JPEG or PDF? so that the file size is not 50MB but less? | 38,366,911 | <p>I have a scanner when i scan the page it makes a BMP file but the size per page is 50MB. How do i tell Python, make it JPEG and small size.</p>
<pre><code>rv = ss.XferImageNatively()
if rv:
(handle, count) = rv
twain.DIBToBMFile(handle,'imageName.bmp')
</code></pre>
<p>how do you tell him to make it JPEG or PDF? (... | 0 | 2016-07-14T06:24:57Z | 38,367,016 | <p>You can use something like PIL (<a href="http://www.pythonware.com/products/pil/" rel="nofollow">http://www.pythonware.com/products/pil/</a>) or Pillow (<a href="https://github.com/python-pillow/Pillow" rel="nofollow">https://github.com/python-pillow/Pillow</a>), which will save the file in the format you specify ba... | 1 | 2016-07-14T06:32:23Z | [
"python",
"windows",
"pdf",
"jpeg",
"scanning"
] |
Python CSV find string and pass column number to variable | 38,367,022 | <p>I just joined here after reading a ton of info over the last few months as I get grounds with Python.</p>
<p>Anyway, I'm very new and have been researching as much as possible but most of the answers are a bit out of my reach in understanding and don't seem to do exactly what I need.</p>
<p>From the reading I've d... | 2 | 2016-07-14T06:32:56Z | 38,367,194 | <p>Looks like what you need is <code>numpy.genfromtxt()</code> with <code>delimiter='\t'</code> and <code>names=True</code></p>
<p>Look <a href="http://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html" rel="nofollow">here</a></p>
<p>You can set the generator to return strings and then reformat column-wise base... | 0 | 2016-07-14T06:43:24Z | [
"python",
"csv",
"spreadsheet",
"timecodes"
] |
Python CSV find string and pass column number to variable | 38,367,022 | <p>I just joined here after reading a ton of info over the last few months as I get grounds with Python.</p>
<p>Anyway, I'm very new and have been researching as much as possible but most of the answers are a bit out of my reach in understanding and don't seem to do exactly what I need.</p>
<p>From the reading I've d... | 2 | 2016-07-14T06:32:56Z | 38,367,373 | <p>If all you need is columnHeader along with respective columnValue, you can read 1st line (header) before the loop from file, and inside the loop use zip(header, row) to get tuple of (columnHeader, columnValue).</p>
<p><code>https://docs.python.org/2/library/functions.html#zip</code></p>
| 0 | 2016-07-14T06:53:02Z | [
"python",
"csv",
"spreadsheet",
"timecodes"
] |
csv.QUOTE_NONNUMERIC does not work with float in python | 38,367,091 | <p>I have a dataframe in Python that I want to save as a CSV with this line:</p>
<pre><code>df.to_csv(PATH, quoting = csv.QUOTE_NONNUMERIC, index = False)
</code></pre>
<p>The dataframe has this form:</p>
<pre><code>date timeOfDay GridID score
2015-12-31 Morning 1445 0.0000... | 1 | 2016-07-14T06:37:50Z | 38,367,230 | <p>There is a bug already on <a href="https://github.com/pydata/pandas/issues/12922" rel="nofollow">github</a>. So you're actually not doing anything wrong.</p>
<p>Quoting the relevant part from the bug description:</p>
<blockquote>
<p>The problem is that <code>pandas.core.internals.FloatBlock.to_native_types</code... | 1 | 2016-07-14T06:45:01Z | [
"python",
"csv"
] |
python lambda list filtering with multiple conditions | 38,367,118 | <p>My understanding about filtering lists with lambda is that the filter will return all the elements of the list that return True for the lambda function. In that case, for the following code,</p>
<pre><code>inputlist = []
inputlist.append(["1", "2", "3", "a"])
inputlist.append(["4", "5", "6", "b"])
inputlist.append(... | 1 | 2016-07-14T06:39:04Z | 38,367,191 | <p>Well, <code>['1', '2', '4', 'c']</code> doesn't satisfy the condition that <code>x[0] != "1"</code>, nor does it satisfy the condition that <code>x[1] != "2"</code>.</p>
| 1 | 2016-07-14T06:43:10Z | [
"python",
"list",
"lambda",
"filter",
"multiple-conditions"
] |
python lambda list filtering with multiple conditions | 38,367,118 | <p>My understanding about filtering lists with lambda is that the filter will return all the elements of the list that return True for the lambda function. In that case, for the following code,</p>
<pre><code>inputlist = []
inputlist.append(["1", "2", "3", "a"])
inputlist.append(["4", "5", "6", "b"])
inputlist.append(... | 1 | 2016-07-14T06:39:04Z | 38,367,198 | <p><code>x = ['1', '2', '4', 'c']</code>, so <code>x[1]=='2'</code>, which makes the expression <code>(x[0] != "1" and x[1] != "2" and x[2] != "3")</code> be evaluated as <code>False</code>.</p>
<p>When conditions are joined by <code>and</code>, they return <code>True</code> only if all conditions are <code>True</code... | 2 | 2016-07-14T06:43:35Z | [
"python",
"list",
"lambda",
"filter",
"multiple-conditions"
] |
python lambda list filtering with multiple conditions | 38,367,118 | <p>My understanding about filtering lists with lambda is that the filter will return all the elements of the list that return True for the lambda function. In that case, for the following code,</p>
<pre><code>inputlist = []
inputlist.append(["1", "2", "3", "a"])
inputlist.append(["4", "5", "6", "b"])
inputlist.append(... | 1 | 2016-07-14T06:39:04Z | 38,367,250 | <pre><code>['1', '2', '4', 'c']
</code></pre>
<p>Fails for condition </p>
<pre><code>x[0] != "1"
</code></pre>
<p>as well as</p>
<pre><code>x[1] != "2"
</code></pre>
<p>Instead of using <code>or</code>, I believe the more natural and readable way is:</p>
<pre><code>lambda x: (x[0], x[1], x[2]) != ('1','2','3')
</... | 2 | 2016-07-14T06:46:01Z | [
"python",
"list",
"lambda",
"filter",
"multiple-conditions"
] |
python lambda list filtering with multiple conditions | 38,367,118 | <p>My understanding about filtering lists with lambda is that the filter will return all the elements of the list that return True for the lambda function. In that case, for the following code,</p>
<pre><code>inputlist = []
inputlist.append(["1", "2", "3", "a"])
inputlist.append(["4", "5", "6", "b"])
inputlist.append(... | 1 | 2016-07-14T06:39:04Z | 38,367,290 | <p>The filter is acting exactly like it should. In the first case</p>
<pre><code>lambda x: (x[0] != "1" and x[1] != "2" and x[2] != "3")
</code></pre>
<p>the filter only "accepts" lists whose first element is not 1 AND whose second element is not 2 AND whose third element is not 3. Thus the list <code>['1', '2', '4... | 1 | 2016-07-14T06:48:38Z | [
"python",
"list",
"lambda",
"filter",
"multiple-conditions"
] |
required field difference in python file and xml file | 38,367,206 | <p>What is the difference between giving required field in python file and xml file in <code>openerp</code>?</p>
<p>In xml file :field name="employee_id" required="1"</p>
<p>In python file: 'employee_id' : fields.char('Employee Name',required=True),</p>
| 0 | 2016-07-14T06:44:07Z | 38,368,546 | <p>The difference is that in the python <code>.py</code> when you set a fields required argument to <code>True</code>, it's creates a <code>NOT NULL</code> constraint directly on the database, this means that no matter what happens (Provided data didn't already exist in the table) you can never insert data into that ta... | 0 | 2016-07-14T07:55:14Z | [
"python",
"openerp"
] |
Scrapy feed output contains the expected output several times instead of just once | 38,367,216 | <p>I've written a spider of which the sole purpose is to extract one number from <a href="http://www.funda.nl/koop/amsterdam/" rel="nofollow">http://www.funda.nl/koop/amsterdam/</a>, namely, the maximum number of pages from the pager at the bottom (e.g., the number 255 in the example below).</p>
<p><a href="http://i.s... | 0 | 2016-07-14T06:44:34Z | 38,367,293 | <ol>
<li>Your spider goes to first start_url. </li>
<li>Uses LinkExtractor to extract 7 urls. </li>
<li>Downloads every one of those 7 urls and calls <code>get_max_page_number</code> on every one of those. </li>
<li>For every url <code>get_max_page_number</code> returns a dictionary.</li>
</ol>
| 3 | 2016-07-14T06:48:42Z | [
"python",
"scrapy"
] |
Scrapy feed output contains the expected output several times instead of just once | 38,367,216 | <p>I've written a spider of which the sole purpose is to extract one number from <a href="http://www.funda.nl/koop/amsterdam/" rel="nofollow">http://www.funda.nl/koop/amsterdam/</a>, namely, the maximum number of pages from the pager at the bottom (e.g., the number 255 in the example below).</p>
<p><a href="http://i.s... | 0 | 2016-07-14T06:44:34Z | 38,371,053 | <p>As a workaround, I've written the output to a text file to be used instead of the JSON feed output:</p>
<pre><code>import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.crawler import CrawlerProcess
class FundaMaxPagesSpider(CrawlSpider):
name = ... | 0 | 2016-07-14T09:54:16Z | [
"python",
"scrapy"
] |
Python 3: my argparse method isn't working correct | 38,367,292 | <p>I've just started learning Python 3, and my argparse method isn't working as it should. I already tried different examples from this website but nothing is working like I want it to.</p>
<p>My code looks like this:</p>
<pre><code>import argparse
class CommandlineArguments():
def __init__(self, number, duplica... | 0 | 2016-07-14T06:48:40Z | 38,367,370 | <p>If you want an argument to be required, you have to pass <code>required=True</code>.</p>
<p>Here's working code that requires all arguments. (I also changed your single dashes to double dashes, which is more typical, and I set <code>type=int</code> for <code>--number</code>, since I assume that's what you want.)</p... | 0 | 2016-07-14T06:52:52Z | [
"python"
] |
Python 3: my argparse method isn't working correct | 38,367,292 | <p>I've just started learning Python 3, and my argparse method isn't working as it should. I already tried different examples from this website but nothing is working like I want it to.</p>
<p>My code looks like this:</p>
<pre><code>import argparse
class CommandlineArguments():
def __init__(self, number, duplica... | 0 | 2016-07-14T06:48:40Z | 38,367,465 | <p>The problem with your programme is that the argument names are prefixed with dash <code>-</code>.</p>
<p>If you just use <code>number</code>, <code>duplicates</code> and <code>databases</code> in <code>add_argument</code>, these three arguments become required. By default prefixing the argument name with dash or do... | 0 | 2016-07-14T06:58:05Z | [
"python"
] |
Python subprocess for queries with quotes | 38,367,382 | <p>I need to fire this query which runs perfectly on the terminal:</p>
<pre><code>sed -i '' '/default\]/a\'$'\n'' Hello world'$'\n' <PATH_TO_FILE>
</code></pre>
<p>This adds a line below where I find "default]" string.</p>
<p>Using the python code:</p>
<pre><code>query = r""" sed -i '' '/default\]/a\'$'\n'' ... | 0 | 2016-07-14T06:53:18Z | 38,367,484 | <p>You <code>split</code> on <em>every</em> whitespace. This causes <code>query.split()</code> to be</p>
<pre><code>['sed',
'-i',
"''",
"'/default\\]/a\\'$'\\n''",
'Hello',
"world'$'\\n'",
'/tmp/foo']
</code></pre>
<p>which is not what you want. Build up the parameters for <code>subprocess.Popen</code> by ha... | 2 | 2016-07-14T06:58:52Z | [
"python",
"subprocess"
] |
Is there a module can be used as FindWindow API in python | 38,367,414 | <p>On Windows there is a WinAPI: FindWindow that you can use to get window handle of a existing window and use this handle to send message to it. Is there a python module can do that too? Find a window & communicate with it?</p>
<p>If this module do exist, could the same mechainsm be able applied on Ubuntu too?
Th... | 0 | 2016-07-14T06:55:11Z | 38,369,455 | <p>You can execute your commands with a subprocess:</p>
<pre><code>import subprocess
import time
process = subprocess.Popen("echo 'start' & sleep 60 & echo 'stop'", shell=True)
time.sleep(60) # Maybe you want a timer...
</code></pre>
<p>The you have two options of closing, use terminate or kill methods in th... | 0 | 2016-07-14T08:42:52Z | [
"python",
"ipc"
] |
Python: Unable to perform multiple adb commands based operation | 38,367,466 | <p>I am running this on Windows m/c. While trying to automate fetching network logs to local m/c, there are multiple commands that I need to send. I am able to club most of them, but now got stuck where I have to stop the execution and copy the file back(using adb pull). </p>
<p>I am using tcpdump executable for captu... | 0 | 2016-07-14T06:58:06Z | 38,368,591 | <p>You need to send the <code>SIGINT</code> signal to the <code>tcpdump</code> process.</p>
<p>Depending on busybox/toolbox/toybox versions available the following would make all running <code>tcpdump</code> instances to stop capturing and dump the log:</p>
<pre><code>adb shell su -c killall -q -2 tcpdump
</code></pr... | 1 | 2016-07-14T07:57:42Z | [
"android",
"python",
"automation",
"subprocess",
"adb"
] |
How to create a singleton? | 38,368,044 | <p>I was wondering if this approach for creating a singleton was correct.</p>
<p><code>my_class.py</code></p>
<pre><code>class MyClass(object):
def a_method(self):
print("Hello World")
...
MY_CLASS_SINGLETON = MyClass()
</code></pre>
<p>another module:</p>
<pre><code>from my_class import MY_CLASS_S... | 0 | 2016-07-14T07:27:23Z | 38,368,196 | <p>I would assume that your implementation is not a save singleton as far as you can easily create new instances of MyClass. A singleton should avoid this by holding this instance by itself and just returning this instance - your instance is hold outside of the class.
(But I am myself new to Python and a the moment I j... | 0 | 2016-07-14T07:35:21Z | [
"python",
"import",
"scope",
"singleton"
] |
Sybpydb error 5701 ignored sometimes | 38,368,072 | <p>I have come across a very strange behavior when developing an application in Python (2.7.11) using a Sybase ASE 15.7 database and the sybpydb library.</p>
<p>When selecting data from the database there is always an error 5701 thrown that isn´t an error but just a informational message taht the client has logged on... | 0 | 2016-07-14T07:28:49Z | 38,377,876 | <p>I never get such message when using sybpydb , I don't print cur.connection.errors() , which is not one of the documented <a href="http://infocenter.sybase.com/help/topic/com.sybase.infocenter.dc01692.1570/doc/html/car1309464785662.html" rel="nofollow">methods</a> (I even got an error when I tried to use it ) </p>
<... | 0 | 2016-07-14T15:09:51Z | [
"python",
"sybase",
"sybase-ase"
] |
how to store/save and restore tensorflow DNNClassifier(No variables to save) | 38,368,096 | <p>I trained a deep neural network on tensorflow and used to predict some examples but, when I try to save it using <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/state_ops.html#Saver" rel="nofollow"><code>train.Saver()</code></a> I get the error:
"No variables to save"</p>
<p>Already tried <code>tr... | 0 | 2016-07-14T07:30:04Z | 38,401,873 | <p>Here's a code sample from the <a href="https://www.tensorflow.org/versions/r0.9/how_tos/variables/index.html" rel="nofollow">tf.variable docs</a> that might clarify:</p>
<pre><code># Create some variables.
v1 = tf.Variable(..., name="v1")
v2 = tf.Variable(..., name="v2")
...
# Add an op to initialize the variables.... | 0 | 2016-07-15T17:20:08Z | [
"python",
"machine-learning",
"tensorflow"
] |
how to store/save and restore tensorflow DNNClassifier(No variables to save) | 38,368,096 | <p>I trained a deep neural network on tensorflow and used to predict some examples but, when I try to save it using <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/state_ops.html#Saver" rel="nofollow"><code>train.Saver()</code></a> I get the error:
"No variables to save"</p>
<p>Already tried <code>tr... | 0 | 2016-07-14T07:30:04Z | 38,465,157 | <p>So I ran into the same issue (Estimators don't have save/restore functions yet). I tried savers and <a href="https://github.com/tensorflow/tensorflow/blob/614d4c19fb22df501ba16a3f580f4e3ac1a9df1a/tensorflow/contrib/learn/python/learn/monitors.py#L260" rel="nofollow"><code>CheckpointSaver</code></a> to try and save c... | 1 | 2016-07-19T17:42:18Z | [
"python",
"machine-learning",
"tensorflow"
] |
wxpython bitmap adding textctrl/combobox top of it? | 38,368,223 | <p>I was trying to find if its possible to add textctrl/combobox top of GenStaticBitmap in wxpython. </p>
<p>Did not find anything with the fast searches i did. Its not first in the priorities, but i feel like it would make the program usage better. </p>
<p>In this case i have screenshot taken from webpage and user c... | 1 | 2016-07-14T07:37:45Z | 38,369,528 | <p>Are you searching for something like a background bitmap (controls on top of a user-defined bitmap)?</p>
<p><a href="http://www.blog.pythonlibrary.org/2010/03/18/wxpython-putting-a-background-image-on-a-panel/" rel="nofollow">Mike Driscoll has described a solution for this in his Blog.</a></p>
| 0 | 2016-07-14T08:46:25Z | [
"python",
"bitmap",
"wxpython"
] |
Installing a pip package from within a Jupyter Notebook not working | 38,368,318 | <p>When I run <code>!pip install geocoder</code> in Jupyter Notebook I get the same output as running <code>pip install geocoder</code> in the terminal but the geocoder package is not available when I try to import it.</p>
<p>I'm using Ubuntu 14.04, Anaconda 4.0.0 and pip 8.1.2</p>
<p>Installing geocoder:</p>
<pre><... | 2 | 2016-07-14T07:42:48Z | 38,750,900 | <p>Try using some shell magic: %%sh
<code>%%sh pip install geocoder</code>
let me know if it works, thanks</p>
| 0 | 2016-08-03T18:14:31Z | [
"python",
"ipython",
"anaconda",
"jupyter",
"jupyter-notebook"
] |
How to efficiently decode a large number of small JSON data chunks? | 38,368,380 | <p>I'm going to write a parser for a log file where each line is one JSON record.</p>
<p>I could decode each line in a loop:</p>
<pre><code>logs = [json.loads(line) for line in lines]
</code></pre>
<p>or I could decode the whole file in one go:</p>
<pre><code>logs = json.loads('[' + ','.join(lines) + ']')
</code></... | 0 | 2016-07-14T07:46:03Z | 38,368,541 | <p>You can just make the log as a JSON dictionary.
Like </p>
<pre><code>{
"log":{
"line1":{...}
"line2":{...}
...
}
}
</code></pre>
<p>And then do <a href="http://stackoverflow.com/questions/19483351/converting-json-string-to-dictionary-not-list-python">this</a> that explains how to convert and ... | 0 | 2016-07-14T07:55:02Z | [
"python",
"json"
] |
How to efficiently decode a large number of small JSON data chunks? | 38,368,380 | <p>I'm going to write a parser for a log file where each line is one JSON record.</p>
<p>I could decode each line in a loop:</p>
<pre><code>logs = [json.loads(line) for line in lines]
</code></pre>
<p>or I could decode the whole file in one go:</p>
<pre><code>logs = json.loads('[' + ','.join(lines) + ']')
</code></... | 0 | 2016-07-14T07:46:03Z | 38,368,580 | <p>You can easily test it with <a href="https://docs.python.org/3.5/library/timeit.html#timeit-command-line-interface" rel="nofollow"><code>timeit</code></a>:</p>
<pre><code>$ python -m timeit -s 'import json; lines = ["{\"foo\":\"bar\"}"] * 1000' '[json.loads(line) for line in lines]'
100 loops, best of 3: 2.22 msec ... | 3 | 2016-07-14T07:57:00Z | [
"python",
"json"
] |
how can I use remove for this code(2)? | 38,368,434 | <p>In the <a href="http://stackoverflow.com/questions/38356276/how-can-i-use-remove-for-this-code/38356363?noredirect=1#comment64125658_38356363">last code</a> , I tried to use one array to remove information.</p>
<p>In this one, I used three arrays to remove information as below:</p>
<pre><code>class student(object)... | -2 | 2016-07-14T07:48:54Z | 38,374,417 | <p>Your problem is that you're iterating over a loop and making changes to the list you're looping over while doing so. The impulse to do so is understandable, but unless you know what you're doing you should just avoid that. Anyway, lets take a look at what you're doing and how it impacts the loop and the list. Removi... | 0 | 2016-07-14T12:37:39Z | [
"python"
] |
Pandas DataFrame select the specific columns with NaN values | 38,368,490 | <p>I have a two-column DataFrame, I want to select the rows with <code>NaN</code> in either column. </p>
<p>I used this method <code>df[ (df['a'] == np.NaN) | (df['b'] == np.NaN) ]</code><br>
However it returns an empty answer. I don't know what's the problem</p>
| 1 | 2016-07-14T07:52:15Z | 38,368,514 | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isnull.html" rel="nofollow"><code>isnull</code></a> for finding <code>NaN</code> values:</p>
<pre><code>df[ (df['a'].isnull()) | (df['b'].isnull()) ]
</code></pre>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/missing_d... | 1 | 2016-07-14T07:53:44Z | [
"python",
"pandas",
"dataframe",
null
] |
Pandas DataFrame select the specific columns with NaN values | 38,368,490 | <p>I have a two-column DataFrame, I want to select the rows with <code>NaN</code> in either column. </p>
<p>I used this method <code>df[ (df['a'] == np.NaN) | (df['b'] == np.NaN) ]</code><br>
However it returns an empty answer. I don't know what's the problem</p>
| 1 | 2016-07-14T07:52:15Z | 38,368,593 | <p>You could apply <code>isnull()</code> to the whole dataframe then check if the rows have any nulls with <code>any(1)</code></p>
<pre><code>df[df.isnull().any(1)]
</code></pre>
<hr>
<h3>Timing</h3>
<pre><code>df = pd.DataFrame(np.random.choice((np.nan, 1), (1000000, 2), p=(.2, .8)), columns=['A', 'B'])
</code></p... | 0 | 2016-07-14T07:57:43Z | [
"python",
"pandas",
"dataframe",
null
] |
What's the most efficient way to sum up an ndarray in numpy while minimizing floating point inaccuracy? | 38,368,500 | <p>I have a big matrix with values that vary greatly in orders of magnitude. To calculate the sum as accurate as possible, my approach would be to reshape the ndarray into a 1-dimensional array, sort it and then add it up, starting with the smallest entries. Is there a better / more efficient way to do this?</p>
| 4 | 2016-07-14T07:52:51Z | 38,368,970 | <p>I think that, given floating point precision problems, the best known algorithm for your task is <a href="https://en.wikipedia.org/wiki/Kahan_summation_algorithm">Kahan summation</a>. For practical purposes, Kahan summation has an error bound that is independent of the number of summands, while naive summation has ... | 5 | 2016-07-14T08:18:25Z | [
"python",
"numpy",
"precision"
] |
Does a big class impact performance by any significance? | 38,368,720 | <p>I constructed a class <em>Vector</em> some time ago which I use quite frequently. As time goes by I'm adding more and more methods that are fun and useful, such as normalize, projection et cetera. The class starts to get quite big and will presumably get even bigger.</p>
<p>As I'm using this class to calculate posi... | 1 | 2016-07-14T08:04:59Z | 38,369,024 | <p>The (code) size of a class does not has a (direct) performance consequence.</p>
<p>Also, as long as you don't have or expect performance problems, don't focus on optimization (mostly optimization results in more work, and sometimes more unreadable/maintainable code). Only optimize for performance if needed. Initial... | 2 | 2016-07-14T08:21:05Z | [
"python",
"performance",
"python-3.x",
"optimization"
] |
Pandas: group by column and count repetitions | 38,368,759 | <p>I'm having some problems obtaining a dataframe from another one.</p>
<p>Summarizing, I have this dataframe:</p>
<pre><code>Word | ... | ... | Code
w1 | ... | ... | 1234
w1 | ... | ... | 2345
...
w1 | ... | ... | 5678
w2 | ... | ... | 5678
w2 | ... | ... | 1234
...
wXX | ... | ... | YYYY
</code></pre>
<p>I... | 1 | 2016-07-14T08:07:06Z | 38,368,816 | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a> with <code>aggfunc=len</code>:</p>
<pre><code>print (df)
Word Code
0 w1 1234
1 w1 2345
2 w1 5678
3 w2 5678
4 w2 1234
df = df.pivot_table(index='Code', colum... | 0 | 2016-07-14T08:10:15Z | [
"python",
"pandas",
"group-by"
] |
x and y coordinates are not correct when trying to read a matrix (python) | 38,368,866 | <p>I am trying to read a matrix (from another file) and check if the numbers are 1,2,3,4 or 5. But when i check I check the coordinates (code below) the x and y is not correct.</p>
<pre><code>with open('/directory/to/file', 'r') as f:
for index,row in enumerate([line.split() for line in f]):
for i,num in e... | 0 | 2016-07-14T08:12:42Z | 38,369,821 | <p>The problem is that <code>enumerate</code> starts enumerating with 0. You want it to start with one. It has an optional second parameter that allows you to do this:</p>
<pre><code>class enumerate(object)
| enumerate(iterable[, start]) -> iterator for index, value of iterable
|
| Return an enumerate object... | 1 | 2016-07-14T08:59:07Z | [
"python",
"matrix",
"coordinates"
] |
Perl's __DATA__ equivalent in Python | 38,368,956 | <p>When writing code in perl I often read data in from the filehandle <code>__DATA__</code> at the end of the script:</p>
<pre><code>while (<DATA>) {
chomp;
say;
}
__DATA__
line1
line2
</code></pre>
<p>I find this quicker for testing code etc than reading in a file, as it means I can edit its contents ... | 7 | 2016-07-14T08:17:37Z | 38,369,018 | <p>No, there is no direct equivalent in Python. Put your data in a multi-line variable:</p>
<pre><code>DATA = '''\
line1
line2
'''
</code></pre>
<p>You can then use <code>DATA.splitlines()</code> if you must have access to separate lines. You can put this at the end of your Python file provided you only use the name ... | 8 | 2016-07-14T08:20:38Z | [
"python",
"perl",
"filehandle"
] |
Scatter plot with a slider in python | 38,368,990 | <p>Hey I am trying to create a scatter plot with a slider that updates the plot as I slide across. This is my code so far. It draws a scatter plot and a slider but as I move it around, nothing happens. I suspect that the problem is with the <code>.set_ydata</code>bit but I can't seem to find how to do it otherwise on t... | 0 | 2016-07-14T08:19:26Z | 38,369,750 | <p>You need to use <code>set_offsets</code> and <code>set_array</code> in stead:</p>
<pre><code># make sure you get the right dimensions and direction of arrays here
xx = np.vstack ((x, y))
scat.set_offsets (xx.T)
# set colors
scat.set_array (y)
</code></pre>
<p>Probably duplicate of: <a href="http://stackoverflow.c... | 0 | 2016-07-14T08:56:08Z | [
"python",
"plot",
"slider",
"interactive",
"scatter"
] |
Django: Define URL for media file | 38,369,013 | <p>I would like to define a custom URL to a folder of files, that can be managed by ftp (I will grant ftp access to this folder 'repository').</p>
<p>e.g. </p>
<pre><code>File on disk:
var/www/djangoproject/media/repository/logo.png
</code></pre>
<p>I want this image to have the URL:</p>
<pre><code>/abc/def/logo.pn... | 0 | 2016-07-14T08:20:29Z | 38,369,546 | <p>Surely this is possible in <code>urls.py</code> and <code>views.py</code>. However, using a web server (e.g. nginx) to <a href="https://www.nginx.com/resources/admin-guide/serving-static-content/" rel="nofollow">serve static content</a> is apparently a better solution.</p>
| 0 | 2016-07-14T08:46:59Z | [
"python",
"django",
"django-urls"
] |
Django: Define URL for media file | 38,369,013 | <p>I would like to define a custom URL to a folder of files, that can be managed by ftp (I will grant ftp access to this folder 'repository').</p>
<p>e.g. </p>
<pre><code>File on disk:
var/www/djangoproject/media/repository/logo.png
</code></pre>
<p>I want this image to have the URL:</p>
<pre><code>/abc/def/logo.pn... | 0 | 2016-07-14T08:20:29Z | 38,372,272 | <p>You can make an ordinary view as you would do with any other view; then in that view, redirect to the actual URL.</p>
<pre><code>from django.shortcuts import redirect
def my_view(request):
return redirect('/media/repository/logo.png')
</code></pre>
<p>Use <code>permanent=True</code> to make browsers cache the... | 1 | 2016-07-14T10:52:28Z | [
"python",
"django",
"django-urls"
] |
Flask passing in query string | 38,369,133 | <p>Fairly new to flask. Don't know how it works properly. However what I'm trying to do is using dryscrape module I'm trying to query a webpage. Using flask for my own front end.
However I am having trouble passing in my query string.
So what I'm trying to do is.</p>
<pre><code>@app.route("/", methods=['GET', 'POST'])... | 0 | 2016-07-14T08:27:09Z | 38,371,136 | <p>In order for the query string to be available across requests you need to store it somewhere on either the client side or server side. <a href="https://pythonhosted.org/Flask-Session/" rel="nofollow" title="Flask-Session">Flask-Session</a> will handle this for you on the server side and is probably the simplest solu... | 0 | 2016-07-14T09:58:19Z | [
"python",
"function",
"flask"
] |
Flask passing in query string | 38,369,133 | <p>Fairly new to flask. Don't know how it works properly. However what I'm trying to do is using dryscrape module I'm trying to query a webpage. Using flask for my own front end.
However I am having trouble passing in my query string.
So what I'm trying to do is.</p>
<pre><code>@app.route("/", methods=['GET', 'POST'])... | 0 | 2016-07-14T08:27:09Z | 38,371,720 | <p>Your concept of HTTP request and respond is not clear. Let me assume some usecase to explain.</p>
<ol>
<li><p>When you request <code>your.domain/search_info</code>, flask will run <code>search_info()</code> function</p></li>
<li><p>And then, flask will run another function <code>getIndex()</code> in <code>search_i... | 0 | 2016-07-14T10:25:18Z | [
"python",
"function",
"flask"
] |
Set size of ticks in all subplots | 38,369,188 | <p>I have a plt.figure(...) with several subplots, my code looks essentially like this:</p>
<pre><code>num_plots = 2
my_dpi = 96
fig_size = (1440 / my_dpi, 900 / my_dpi)
fig = plt.figure(figsize=fig_size, dpi=my_dpi, frameon=False)
# Subplot 1
fig.add_subplot(num_plots, 1, 1)
# plot fancy stuff
# Subplot 2
fig.ad... | 2 | 2016-07-14T08:29:39Z | 38,369,691 | <p>There a two things you can do here. If you want to change the tick size for all figures in the script you are running, you need to add the following at the top of your code:</p>
<pre><code>import matplotlib
matplotlib.rc('xtick', labelsize=20)
matplotlib.rc('ytick', labelsize=20)
</code></pre>
<p>This will be s... | 1 | 2016-07-14T08:53:27Z | [
"python",
"python-2.7",
"matplotlib"
] |
Are python packages version specific? | 38,369,233 | <p>I ma trying to install <a href="https://pypi.python.org/pypi/python-epo-ops-client" rel="nofollow">https://pypi.python.org/pypi/python-epo-ops-client</a>
I tried installing it from pip from both latest version.</p>
<p>python 2.7.12 and
python 3.5.2</p>
<p>for both of the version it says</p>
<pre><code>C:\Users\m... | 1 | 2016-07-14T08:31:52Z | 38,369,425 | <p>You are having space between <strong>python-epo-ops-client</strong> & <strong>2.1.0</strong>, so it is trying to install two packages. </p>
<p>(1) python-epo-ops-client and
(2) 2.1.0, but there isn't any package named "2.1.0"</p>
<p>To install specific version you need to mention <strong>==</strong>.</p>
<pr... | 4 | 2016-07-14T08:41:12Z | [
"python"
] |
What is the pythonic way to alternate between two functions in a loop | 38,369,250 | <p>It seems like a simple question to me, but a search yielded nothing useful.</p>
<p>I have code like below:</p>
<pre><code> for key, v in enumerate(ranges):
### Used to switch between voltage steps
second_iter = 0
for step in v:
### Set voltage sources to differential volta... | 0 | 2016-07-14T08:32:27Z | 38,369,368 | <p>I would do it like this:</p>
<pre><code>for key, v in enumerate(range(0, 100)):
[fun_call1() if key % 2 else fun_call2()]
</code></pre>
| 1 | 2016-07-14T08:38:18Z | [
"python"
] |
What is the pythonic way to alternate between two functions in a loop | 38,369,250 | <p>It seems like a simple question to me, but a search yielded nothing useful.</p>
<p>I have code like below:</p>
<pre><code> for key, v in enumerate(ranges):
### Used to switch between voltage steps
second_iter = 0
for step in v:
### Set voltage sources to differential volta... | 0 | 2016-07-14T08:32:27Z | 38,369,374 | <p>If v is a 2 element list, I'd write it like this:</p>
<pre><code>for key, (step1, step2) in enumerate(ranges):
self.tf.institf.dcm.vsource1(step1)
self.measure_something()
self.tf.institf.dcm.vsource2(step2)
self.measure_something()
</code></pre>
<p>Pythonic doesn't always mean to use the most adv... | 0 | 2016-07-14T08:38:36Z | [
"python"
] |
What is the pythonic way to alternate between two functions in a loop | 38,369,250 | <p>It seems like a simple question to me, but a search yielded nothing useful.</p>
<p>I have code like below:</p>
<pre><code> for key, v in enumerate(ranges):
### Used to switch between voltage steps
second_iter = 0
for step in v:
### Set voltage sources to differential volta... | 0 | 2016-07-14T08:32:27Z | 38,369,414 | <p>Your code is very little intuitive... Is this not enough to do that, without abusing loops?</p>
<pre><code>vsource1 = self.tf.institf.dcm.vsource1
vsource2 = self.tf.institf.dcm.vsource2
for key, (v1, v2) in enumerate(ranges):
vsource1(v1)
# Do some other stuff
vsource2(v2)
# Do some other stuff ... | 6 | 2016-07-14T08:40:47Z | [
"python"
] |
What is the pythonic way to alternate between two functions in a loop | 38,369,250 | <p>It seems like a simple question to me, but a search yielded nothing useful.</p>
<p>I have code like below:</p>
<pre><code> for key, v in enumerate(ranges):
### Used to switch between voltage steps
second_iter = 0
for step in v:
### Set voltage sources to differential volta... | 0 | 2016-07-14T08:32:27Z | 38,369,466 | <p>Simple indexing into second list can help avoid loop and second_iter variable</p>
<pre><code>for key, v in enumerate(ranges):
self.tf.institf.dcm.vsource1(v[0])
self.measure_something()
self.tf.institf.dcm.vsource2(v[1])
self.measure_something()
</code></pre>
| 0 | 2016-07-14T08:43:37Z | [
"python"
] |
What is the pythonic way to alternate between two functions in a loop | 38,369,250 | <p>It seems like a simple question to me, but a search yielded nothing useful.</p>
<p>I have code like below:</p>
<pre><code> for key, v in enumerate(ranges):
### Used to switch between voltage steps
second_iter = 0
for step in v:
### Set voltage sources to differential volta... | 0 | 2016-07-14T08:32:27Z | 38,369,478 | <p>This reduces the amount of code and reduces the need of conditional evaluation to 1 for each iteration.</p>
<pre><code>for key, v in enumerate(ranges):
if key % 2 == 0:
self.tf.institf.dcm.vsource1(v[0])
else:
self.tf.institf.dcm.vsource2(v[1])
</code></pre>
| 1 | 2016-07-14T08:44:07Z | [
"python"
] |
What is the pythonic way to alternate between two functions in a loop | 38,369,250 | <p>It seems like a simple question to me, but a search yielded nothing useful.</p>
<p>I have code like below:</p>
<pre><code> for key, v in enumerate(ranges):
### Used to switch between voltage steps
second_iter = 0
for step in v:
### Set voltage sources to differential volta... | 0 | 2016-07-14T08:32:27Z | 38,369,499 | <p>You could use <code>itertools.cycle</code> and <code>zip</code>:</p>
<pre><code>from itertools import cycle
vsources = [self.tf.institf.dcm.vsource1, self.tf.institf.dcm.vsource2]
for key, v in enumerate(ranges):
for (step, vsource) in zip(v, cycle(vsources)):
### Set voltage sources to differential ... | 0 | 2016-07-14T08:44:57Z | [
"python"
] |
What is the pythonic way to alternate between two functions in a loop | 38,369,250 | <p>It seems like a simple question to me, but a search yielded nothing useful.</p>
<p>I have code like below:</p>
<pre><code> for key, v in enumerate(ranges):
### Used to switch between voltage steps
second_iter = 0
for step in v:
### Set voltage sources to differential volta... | 0 | 2016-07-14T08:32:27Z | 38,369,622 | <p>Not strictly pythonic, but you can use the remainder operator to switch between the two functions:</p>
<pre><code>funcs = [func1, func2]
for i, voltage in enumerate(ranges):
for step in voltage:
func = funcs[i % 2]
func(step)
</code></pre>
<p><strong>OR</strong></p>
<p>This one's not DRY, but... | 0 | 2016-07-14T08:50:21Z | [
"python"
] |
Maybe a bug in DataFrame.reindex ? | 38,369,291 | <p>python 2.7.11</p>
<p>pandas 0.18.1 </p>
<p>when i try to do like this:</p>
<pre><code>idx = pd.MultiIndex.from_product([['Ia','Ib'],['i1','i2','i3']])
df = pd.DataFrame({'A':['c','b','b','a','b','a'],'B':[10,-20,50,40,None,50],'C':[100,50,-30,-50,70,40]},index=idx)
print df.reindex(index=['Ib','Ia'],columns=['B',... | 1 | 2016-07-14T08:34:36Z | 38,370,835 | <p>To answer the question: No, that is not OK! And it's not a bug... really.</p>
<p>Consider the dataframe <code>df</code>:</p>
<pre><code>df = pd.DataFrame(np.arange(8).reshape(4, 2),
pd.MultiIndex.from_product([['a', 'b'], ['C', 'D']]),
['One', 'Two'])
df
</code></pre>
<p><a hr... | 0 | 2016-07-14T09:44:47Z | [
"python",
"pandas"
] |
Lambdas from a list comprehension are returning a lambda when called | 38,369,470 | <p>I am trying to iterate the lambda func over a list as in <code>test.py</code>, and I want to get the call result of the lambda, not the function object itself. However, the following output really confused me. </p>
<pre><code>------test.py---------
#!/bin/env python
#coding: utf-8
a = [lambda: i for i in range(5)... | 51 | 2016-07-14T08:43:46Z | 38,370,058 | <p>Closures in Python are <a href="http://docs.python-guide.org/en/latest/writing/gotchas/#late-binding-closures">late-binding</a>, meaning that each lambda function in the list will only evaluate the variable <code>i</code> when invoked, and <em>not</em> when defined. That's why all functions return the same value, i.... | 17 | 2016-07-14T09:09:30Z | [
"python",
"lambda"
] |
Lambdas from a list comprehension are returning a lambda when called | 38,369,470 | <p>I am trying to iterate the lambda func over a list as in <code>test.py</code>, and I want to get the call result of the lambda, not the function object itself. However, the following output really confused me. </p>
<pre><code>------test.py---------
#!/bin/env python
#coding: utf-8
a = [lambda: i for i in range(5)... | 51 | 2016-07-14T08:43:46Z | 38,370,176 | <p><code>lambda: i</code> is an anonymous function with no arguments that returns i. So you are generating a list of anonymous functions, which you can later (in the second example) bind to the name <code>t</code> and invoke with <code>()</code>. Note you can do the same with non-anonymous functions:</p>
<pre><code>&g... | 4 | 2016-07-14T09:14:24Z | [
"python",
"lambda"
] |
Lambdas from a list comprehension are returning a lambda when called | 38,369,470 | <p>I am trying to iterate the lambda func over a list as in <code>test.py</code>, and I want to get the call result of the lambda, not the function object itself. However, the following output really confused me. </p>
<pre><code>------test.py---------
#!/bin/env python
#coding: utf-8
a = [lambda: i for i in range(5)... | 51 | 2016-07-14T08:43:46Z | 38,370,271 | <p>In Python 2 list comprehension 'leaks' the variables to outer scope:</p>
<pre><code>>>> [i for i in xrange(3)]
[0, 1, 2]
>>> i
2
</code></pre>
<p>Note that the behavior is different on Python 3:</p>
<pre><code>>>> [i for i in range(3)]
[0, 1, 2]
>>> i
Traceback (most recent cal... | 46 | 2016-07-14T09:18:35Z | [
"python",
"lambda"
] |
Scope of variable when passed to another function in python decorators | 38,369,575 | <p>So I was reading this <a href="https://jeffknupp.com/blog/2013/11/29/improve-your-python-decorators-explained/" rel="nofollow">wonderful piece</a> which tries to explain decorators in python.</p>
<p>My question is specific to this code snippet.</p>
<pre><code>def surround_with(surrounding):
"""Return a functio... | 0 | 2016-07-14T08:48:24Z | 38,369,831 | <p>I think I understood it, </p>
<p>When we call <code>surround_with('*')</code>, it returns the function <code>surround_with_value()</code> which is then returning the value <code>'{}{}{}'.format('*', word, '*')</code>.</p>
<p>Now the very same function takes an argument (<code>word</code> here) which is then passed... | 0 | 2016-07-14T08:59:33Z | [
"python",
"scope",
"decorator"
] |
Scope of variable when passed to another function in python decorators | 38,369,575 | <p>So I was reading this <a href="https://jeffknupp.com/blog/2013/11/29/improve-your-python-decorators-explained/" rel="nofollow">wonderful piece</a> which tries to explain decorators in python.</p>
<p>My question is specific to this code snippet.</p>
<pre><code>def surround_with(surrounding):
"""Return a functio... | 0 | 2016-07-14T08:48:24Z | 38,369,860 | <p>The <code>surround_with()</code> function returns another function object with a <em>closure</em>:</p>
<pre><code>def surround_with(surrounding):
"""Return a function that takes a single argument and."""
def surround_with_value(word):
return '{}{}{}'.format(surrounding, word, surrounding)
return... | 1 | 2016-07-14T09:00:46Z | [
"python",
"scope",
"decorator"
] |
Scope of variable when passed to another function in python decorators | 38,369,575 | <p>So I was reading this <a href="https://jeffknupp.com/blog/2013/11/29/improve-your-python-decorators-explained/" rel="nofollow">wonderful piece</a> which tries to explain decorators in python.</p>
<p>My question is specific to this code snippet.</p>
<pre><code>def surround_with(surrounding):
"""Return a functio... | 0 | 2016-07-14T08:48:24Z | 38,404,156 | <p>Closure can be very confusing and this example might not be the best to show <strong>why</strong> surround_with_value() <strong>remembers</strong> surround with(surrounding) event if it's not in its scope.</p>
<p>I strongly advice you to read this excellent blog showing all concept you need to understand to underst... | 0 | 2016-07-15T19:55:28Z | [
"python",
"scope",
"decorator"
] |
Merging data frame with overlapping columns | 38,369,638 | <p>I have following DataFrames:</p>
<pre><code> stores = [['AA', 12, 'Red'], ['BB', 13, 'Red'], ['BB', 14, 'Red'], ['BB', 15, 'Red']]
visits = [['BB', 13, 'Green'], ['BB', 14, 'Blue']]
stores_df = pd.DataFrame(data=stores, columns=['retailer', 'store', 'color'])
stores_df.set_index(['retailer', 'store'... | 2 | 2016-07-14T08:51:15Z | 38,369,732 | <p>You can use <code>update</code>:</p>
<pre><code>In [41]: stores_df.update(visits_df)
In [42]: stores_df
Out[42]:
color
retailer store
AA 12 Red
BB 13 Green
14 Blue
15 Red
</code></pre>
| 3 | 2016-07-14T08:55:26Z | [
"python",
"pandas",
"dataframe"
] |
Merging data frame with overlapping columns | 38,369,638 | <p>I have following DataFrames:</p>
<pre><code> stores = [['AA', 12, 'Red'], ['BB', 13, 'Red'], ['BB', 14, 'Red'], ['BB', 15, 'Red']]
visits = [['BB', 13, 'Green'], ['BB', 14, 'Blue']]
stores_df = pd.DataFrame(data=stores, columns=['retailer', 'store', 'color'])
stores_df.set_index(['retailer', 'store'... | 2 | 2016-07-14T08:51:15Z | 38,369,882 | <p>You want to use <code>combine_first</code></p>
<pre><code>visits_df.combine_first(stores_df)
</code></pre>
<p><a href="http://i.stack.imgur.com/sjpH4.png" rel="nofollow"><img src="http://i.stack.imgur.com/sjpH4.png" alt="enter image description here"></a></p>
| 3 | 2016-07-14T09:01:50Z | [
"python",
"pandas",
"dataframe"
] |
How to add 2 random numbers from a list together? | 38,369,740 | <p>For example:
<code>list1 = [1,2,3,4,5,6]</code></p>
<p>I want to get 2 random numbers from this list and add them together:</p>
<p><code>3 + 2</code> for example.</p>
| 3 | 2016-07-14T08:55:49Z | 38,369,798 | <p>Here you have the solution, but what I'd like to tell you is that you wont go too far in programming by asking that kind of questions. </p>
<p>What you need to do before asking is to do some reflexion. for example, if I were you, I would have searched:</p>
<p>On google "<code>python get random number list</code>" ... | 1 | 2016-07-14T08:58:15Z | [
"python",
"list"
] |
How to add 2 random numbers from a list together? | 38,369,740 | <p>For example:
<code>list1 = [1,2,3,4,5,6]</code></p>
<p>I want to get 2 random numbers from this list and add them together:</p>
<p><code>3 + 2</code> for example.</p>
| 3 | 2016-07-14T08:55:49Z | 38,369,850 | <p><strong>For unique selections</strong> (sampling <em>without</em> replacement), you can make use of <a href="https://docs.python.org/3/library/random.html#random.sample" rel="nofollow"><code>random.sample</code></a> for selecting multiple random elements from the list and use the built-in <a href="https://docs.pytho... | 4 | 2016-07-14T09:00:08Z | [
"python",
"list"
] |
How to add 2 random numbers from a list together? | 38,369,740 | <p>For example:
<code>list1 = [1,2,3,4,5,6]</code></p>
<p>I want to get 2 random numbers from this list and add them together:</p>
<p><code>3 + 2</code> for example.</p>
| 3 | 2016-07-14T08:55:49Z | 38,369,854 | <p>I guess that if you want distinct elements, you can use:</p>
<pre><code>import random
sum(random.sample(list1, 2))
</code></pre>
| 1 | 2016-07-14T09:00:31Z | [
"python",
"list"
] |
How to add 2 random numbers from a list together? | 38,369,740 | <p>For example:
<code>list1 = [1,2,3,4,5,6]</code></p>
<p>I want to get 2 random numbers from this list and add them together:</p>
<p><code>3 + 2</code> for example.</p>
| 3 | 2016-07-14T08:55:49Z | 38,369,879 | <p>For taking random numbers from the list you can use </p>
<pre><code>import random
random.choice()
</code></pre>
<p>In your case use</p>
<pre><code>import random
list1 = [1,2,3,4,5,6]
sum=random.choice(list1)+random.choice(list1)
</code></pre>
| 1 | 2016-07-14T09:01:36Z | [
"python",
"list"
] |
How to add 2 random numbers from a list together? | 38,369,740 | <p>For example:
<code>list1 = [1,2,3,4,5,6]</code></p>
<p>I want to get 2 random numbers from this list and add them together:</p>
<p><code>3 + 2</code> for example.</p>
| 3 | 2016-07-14T08:55:49Z | 38,370,052 | <p>You should use the function:</p>
<pre><code>from random import choice
a=(random.choice(list1))
</code></pre>
<p>'a' will now be a random number from the list</p>
| 0 | 2016-07-14T09:09:18Z | [
"python",
"list"
] |
Calculate euclidean distance from dicts (sklearn) | 38,369,742 | <p>I have two <code>dictionaries</code> already calculated in my code, which look like this:</p>
<pre><code>X = {'a': 10, 'b': 3, 'c': 5, ...}
Y = {'a': 8, 'c': 3, 'e': 8, ...}
</code></pre>
<p>Actually they contain words from wiki texts, but this should serve to show what I mean. They don't necessarily contain the s... | 0 | 2016-07-14T08:55:52Z | 38,370,159 | <p>Why don't you just do it directly from your sparse representation?</p>
<pre><code>In [1]: import math
In [2]: Y = {'a': 8, 'c':3,'e':8}
In [3]: X = {'a':10, 'b':3, 'c':5}
In [4]: math.sqrt(sum((X.get(d,0) - Y.get(d,0))**2 for d in set(X) | set(Y)))
Out[4]: 9.0
</code></pre>
| 1 | 2016-07-14T09:13:54Z | [
"python",
"numpy",
"dictionary",
"scikit-learn",
"euclidean-distance"
] |
Calculate euclidean distance from dicts (sklearn) | 38,369,742 | <p>I have two <code>dictionaries</code> already calculated in my code, which look like this:</p>
<pre><code>X = {'a': 10, 'b': 3, 'c': 5, ...}
Y = {'a': 8, 'c': 3, 'e': 8, ...}
</code></pre>
<p>Actually they contain words from wiki texts, but this should serve to show what I mean. They don't necessarily contain the s... | 0 | 2016-07-14T08:55:52Z | 38,372,675 | <p>Seems like you'd want to use <code>X.get(search_string,0)</code>, which would output the value or 0 if not found. If you have a lot of search strings you could do <code>[X.get(s,0) for s in list_of_strings]</code> which will push a list of output.</p>
| 0 | 2016-07-14T11:12:33Z | [
"python",
"numpy",
"dictionary",
"scikit-learn",
"euclidean-distance"
] |
Calculate euclidean distance from dicts (sklearn) | 38,369,742 | <p>I have two <code>dictionaries</code> already calculated in my code, which look like this:</p>
<pre><code>X = {'a': 10, 'b': 3, 'c': 5, ...}
Y = {'a': 8, 'c': 3, 'e': 8, ...}
</code></pre>
<p>Actually they contain words from wiki texts, but this should serve to show what I mean. They don't necessarily contain the s... | 0 | 2016-07-14T08:55:52Z | 38,372,795 | <p>You could start by creating a list with all the keys of your dictionaries (it is important to note that this list has to be sorted):</p>
<pre><code>X = {'a': 10, 'b': 3, 'c': 5}
Y = {'a': 8, 'c': 3, 'e': 8}
data = [X, Y]
words = sorted(list(reduce(set.union, map(set, data))))
</code></pre>
<p>This works fine in Py... | 2 | 2016-07-14T11:18:50Z | [
"python",
"numpy",
"dictionary",
"scikit-learn",
"euclidean-distance"
] |
pyyaml and using quotes for strings only | 38,369,833 | <p>I have the following YAML file:</p>
<pre><code>---
my_vars:
my_env: "dev"
my_count: 3
</code></pre>
<p>When I read it with PyYAML and dump it again, I get the following output:</p>
<pre><code>---
my_vars:
my_env: dev
my_count: 3
</code></pre>
<p>The code in question:</p>
<pre><code>with open(env_file) a... | 1 | 2016-07-14T08:59:38Z | 38,370,522 | <p>Right, so borrowing heavily from <a href="http://stackoverflow.com/questions/8640959/how-can-i-control-what-scalar-form-pyyaml-uses-for-my-data">this answer</a>, you can do something like this:</p>
<pre><code>import yaml
# define a custom representer for strings
def quoted_presenter(dumper, data):
return dumpe... | 1 | 2016-07-14T09:29:18Z | [
"python",
"pyyaml"
] |
pyyaml and using quotes for strings only | 38,369,833 | <p>I have the following YAML file:</p>
<pre><code>---
my_vars:
my_env: "dev"
my_count: 3
</code></pre>
<p>When I read it with PyYAML and dump it again, I get the following output:</p>
<pre><code>---
my_vars:
my_env: dev
my_count: 3
</code></pre>
<p>The code in question:</p>
<pre><code>with open(env_file) a... | 1 | 2016-07-14T08:59:38Z | 38,582,476 | <p>I suggest you update to using YAML 1.2 (released in 2009) with the backwards compatible <a href="https://pypi.python.org/pypi/ruamel.yaml/" rel="nofollow"><code>ruamel.yaml</code></a> package instead of using PyYAML which implements most of YAML 1.1 (2005). (Disclaimer: I am the author of that package).</p>
<p>Then... | 0 | 2016-07-26T06:28:19Z | [
"python",
"pyyaml"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.