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 list |
|---|---|---|---|---|---|---|---|---|---|
When will python while loop break? | 39,312,493 | <p>I'm new to python or coding in general. And encountered some while loop question in the following code.</p>
<hr>
<pre><code>a = int(input('input a number here: '))
def largest_factor(x):
factor = x - 1
while factor > 0:
if x % factor == 0:
return factor
factor -= 1
... | -1 | 2016-09-04T00:24:15Z | 39,312,671 | <p>There are two ways to leave this loop, waiting until the while statement terminates or by returning the factor.</p>
| 0 | 2016-09-04T01:03:52Z | [
"python",
"python-3.x"
] |
When will python while loop break? | 39,312,493 | <p>I'm new to python or coding in general. And encountered some while loop question in the following code.</p>
<hr>
<pre><code>a = int(input('input a number here: '))
def largest_factor(x):
factor = x - 1
while factor > 0:
if x % factor == 0:
return factor
factor -= 1
... | -1 | 2016-09-04T00:24:15Z | 39,313,354 | <p>Your assumption is correct. Once the loop hits the return statement, the function will end. Since 100 is divisible by 50, the loop ends with the function ending.</p>
| 0 | 2016-09-04T03:45:33Z | [
"python",
"python-3.x"
] |
Mock property return value gets overridden when instantiating mock object | 39,312,530 | <h2>Background</h2>
<p>I'm trying to set up a test fixture for an application I'm writing in which one of my classes is replaced with a mock. I'm happy to leave most of the attributes of the mock class as the default <code>MagicMock</code> instances (where I'm only interested in making assertions about their usage), b... | 1 | 2016-09-04T00:31:31Z | 39,312,746 | <p>The following line:</p>
<pre><code>type(mock_foo).bar = mock_bar
</code></pre>
<p>mocks <code>mock_foo</code> which, at that point, is the return value of <code>enter_context</code>. If I understand <a href="https://docs.python.org/3/library/contextlib.html#contextlib.ExitStack.enter_context" rel="nofollow">the do... | 1 | 2016-09-04T01:24:57Z | [
"python",
"python-3.x",
"mocking",
"python-mock"
] |
Get "super(): no arguments" error in one case but not a similar case | 39,312,553 | <pre><code>class Works(type):
def __new__(cls, *args, **kwargs):
print([cls,args]) # outputs [<class '__main__.Works'>, ()]
return super().__new__(cls, args)
class DoesNotWork(type):
def __new__(*args, **kwargs):
print([args[0],args[:0]]) # outputs [<class '__main__.doesNotWork... | 1 | 2016-09-04T00:35:54Z | 39,313,448 | <p>The zero-argument form of <code>super</code> requires that the method containing it have an explicit (i.e., non-varargs) first argument. This is suggested by <a href="https://docs.python.org/3.1/library/functions.html?#super" rel="nofollow">an older version of the docs</a> (emphasis added):</p>
<blockquote>
<p>T... | 2 | 2016-09-04T04:04:01Z | [
"python",
"super"
] |
Python: Properly formatting JSON parameters into a proper http request with markit on demand api | 39,312,560 | <p>I am having trouble formatting my request properly in order to use the markitondemand InteractiveChart API. How can I properly do this?</p>
<p>reference: <a href="http://dev.markitondemand.com/MODApis/" rel="nofollow">http://dev.markitondemand.com/MODApis/</a></p>
<p>Here is an example of a proper request:</p>
<... | 1 | 2016-09-04T00:37:09Z | 39,312,597 | <p>Your url end point (by the looks of it) should just be:</p>
<pre><code>url2 = 'http://dev.markitondemand.com/MODApis/Api/v2/InteractiveChart
</code></pre>
<p>Then, make your request:</p>
<pre><code>resp = requests.get(url2, params=json.dumps({'parameters': req_obj}))
</code></pre>
<p>Then <code>requests</code> w... | 0 | 2016-09-04T00:46:58Z | [
"python",
"json"
] |
Python: Properly formatting JSON parameters into a proper http request with markit on demand api | 39,312,560 | <p>I am having trouble formatting my request properly in order to use the markitondemand InteractiveChart API. How can I properly do this?</p>
<p>reference: <a href="http://dev.markitondemand.com/MODApis/" rel="nofollow">http://dev.markitondemand.com/MODApis/</a></p>
<p>Here is an example of a proper request:</p>
<... | 1 | 2016-09-04T00:37:09Z | 39,312,724 | <p>Your <em>url</em>, <em>params</em> and logic are wrong, what you want is:</p>
<pre><code>url2 = 'http://dev.markitondemand.com/MODApis/Api/v2/InteractiveChart/json'
elements = [
{
'Symbol': 'GOOG',
'Type': 'price',
"Params":["c"] # not 'Params': {'price': ['c']}
}... | 0 | 2016-09-04T01:18:18Z | [
"python",
"json"
] |
Large table access from c++ functions with boost::python | 39,312,595 | <p>I'm generating a very large lookup table in C++ and using it from a variety of C++ functions. These functions are exposed to python using boost::python. </p>
<p>When not used as part of a class the desired behaviour is achieved. When I try and use the functions as part of a class written in just python I run in to ... | 0 | 2016-09-04T00:45:38Z | 39,316,248 | <p>Missing a self in a definition. Used key word arguments where I should probably have used keyword only arguments so got no error when running.</p>
| 0 | 2016-09-04T11:09:08Z | [
"python",
"c++",
"boost-python"
] |
Python Syntax Non-ASCII character 'xe6' in file (added #-*-coding:utf-8 -*- ) | 39,312,596 | <p>I want to use Python to read the .csv.</p>
<p>At start I search the answer to add the </p>
<pre><code>#!/usr/bin/python
#-*-coding:utf-8 -*-
</code></pre>
<p>so that can avoid the problem of encoding, but it is still wrong, giving the syntax error:</p>
<blockquote>
<p>SyntaxError: Non-ASCII character 'xe6' in... | -1 | 2016-09-04T00:46:00Z | 39,313,862 | <p>You've got two different errors here. This answer relates to the <code>with</code> warning. The other error is the ascii encoding error.</p>
<p>You appear to be using a very old version of python (2.5). The <code>with</code> statement is not enabled by default in python 2.5. Instead you have to declare a the top of... | 0 | 2016-09-04T05:40:44Z | [
"python"
] |
SVM; training data doesn't contain target | 39,312,609 | <p>I'm trying to predict whether a fan is going to turn out to a sporting event or not. My data (pandas DataFrame) consists of fan information (demographic's, etc.), and whether or not they attended the last 10 matches (g1_attend - g10_attend).</p>
<pre><code>fan_info age neighborhood g1_attend g2_attend ... g1_neigh... | 1 | 2016-09-04T00:49:48Z | 39,312,747 | <p>You are correct, you can't just add a new category (ie output class) to a classifier -- this requires something that does time series.</p>
<p>But there is a fairly standard technique for using a classifier on times-series. Asserting (conditional) Time Independence, and using windowing.</p>
<p>In short we are going... | 2 | 2016-09-04T01:25:04Z | [
"python",
"pandas",
"scikit-learn",
"modeling"
] |
Changing values of indexes by magnitude | 39,312,677 | <p>I'm trying to make a flexible algorithm that will take values out of a 50 by 50 array (which contains pixel values from a fits image) if they are too high.
they are too high (in python). The first thing I tried to do was this:</p>
<pre><code>file = pf.open('/Users/Vofun/desktop/file.fits')
data = np.array(file[0].... | 0 | 2016-09-04T01:04:27Z | 39,313,380 | <p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#boolean-array-indexing" rel="nofollow">boolean indexing</a> to change your data.</p>
<pre><code>import numpy as np
a = np.random.random_integers(40, 60, (5,5))
>>> a
array([[58, 58, 43, 56, 54],
[59, 40, 42, 52, 45]... | 1 | 2016-09-04T03:51:19Z | [
"python",
"python-2.7",
"numpy",
"multidimensional-array"
] |
I have a list of a part of a filename, for each one I want to go through the files in a directory that matches that part and return the filename | 39,312,704 | <p>So, let's say I have a directory with a bunch of filenames.
for example:</p>
<p>Scalar Product or Dot Product (Hindi)-fodZTqRhC24.m4a<br>
AP Physics C - Dot Product-Wvhn_lVPiw0.m4a<br>
An Introduction to the Dot Product-X5DifJW0zek.m4a </p>
<p>Now let's say I have a list, of only the keys, which are at the end ... | -1 | 2016-09-04T01:12:09Z | 39,312,763 | <p>Here is an example: </p>
<p>ls: list of files in a given directory</p>
<p>names: list of strings to search for</p>
<pre><code>import os
ls=os.listdir("/any/folder")
n=['Py', 'sql']
for file in ls:
for name in names:
if name in file:
print(file)
</code></pre>
<p>Results :</p>
<pre><code>.PyCharm50... | 0 | 2016-09-04T01:28:41Z | [
"python"
] |
I have a list of a part of a filename, for each one I want to go through the files in a directory that matches that part and return the filename | 39,312,704 | <p>So, let's say I have a directory with a bunch of filenames.
for example:</p>
<p>Scalar Product or Dot Product (Hindi)-fodZTqRhC24.m4a<br>
AP Physics C - Dot Product-Wvhn_lVPiw0.m4a<br>
An Introduction to the Dot Product-X5DifJW0zek.m4a </p>
<p>Now let's say I have a list, of only the keys, which are at the end ... | -1 | 2016-09-04T01:12:09Z | 39,312,774 | <p>Assuming you know which directory that you will be looking in, you could try something like this:</p>
<pre><code>import os
to_find = ['word 1', 'word 2'] # list containing words that you are searching for
all_files = os.listdir('/path/to/file') # creates list with files from given directory
for file in a... | 0 | 2016-09-04T01:30:40Z | [
"python"
] |
I have a list of a part of a filename, for each one I want to go through the files in a directory that matches that part and return the filename | 39,312,704 | <p>So, let's say I have a directory with a bunch of filenames.
for example:</p>
<p>Scalar Product or Dot Product (Hindi)-fodZTqRhC24.m4a<br>
AP Physics C - Dot Product-Wvhn_lVPiw0.m4a<br>
An Introduction to the Dot Product-X5DifJW0zek.m4a </p>
<p>Now let's say I have a list, of only the keys, which are at the end ... | -1 | 2016-09-04T01:12:09Z | 39,312,865 | <p>Here's a way to do it that allows for a selection of weather to match based on placement of text.</p>
<pre><code>import os
def scan(dir, match_key, bias=2):
'''
:0 startswith
:1 contains
:2 endswith
'''
matches = []
if not isinstance(match_key, (tuple, list)):
ma... | 0 | 2016-09-04T01:48:47Z | [
"python"
] |
I have a list of a part of a filename, for each one I want to go through the files in a directory that matches that part and return the filename | 39,312,704 | <p>So, let's say I have a directory with a bunch of filenames.
for example:</p>
<p>Scalar Product or Dot Product (Hindi)-fodZTqRhC24.m4a<br>
AP Physics C - Dot Product-Wvhn_lVPiw0.m4a<br>
An Introduction to the Dot Product-X5DifJW0zek.m4a </p>
<p>Now let's say I have a list, of only the keys, which are at the end ... | -1 | 2016-09-04T01:12:09Z | 39,312,900 | <p>Thanks a lot guys, Once I thought about it, I think I was making it harder than I had to with regex. Sorry about not trying it first. Thank you all once again. I think I have it. </p>
<pre><code>audio = ['Scalar Product or Dot Product (Hindi)-fodZTqRhC24.m4a',
'An Introduction to the Dot Product-X5DifJW0zek.m4a',... | 1 | 2016-09-04T01:57:02Z | [
"python"
] |
Python 2.7- fastest way to apply function to 2 columns of a pandas data frame | 39,312,737 | <p>I need to check if a string that is in one column of a pandas data frame is in another.
Example data:</p>
<pre><code>aa=['mma', 'sdas', 'asdsad']*1000
t=pd.DataFrame(aa)
a=['m', 'f', 'n']*1000
t1=pd.DataFrame(a)
t2=pd.concat([t,t1], axis=1)
t2.columns=['texto', 'textito']
</code></pre>
<p>With a lambda function I... | 2 | 2016-09-04T01:22:04Z | 39,313,328 | <p>If space is plentiful, you could create a new DataFrame by applying <code>set</code> to the original. Then the membership test would be much faster than using <code>in</code> with the strings.</p>
<pre><code># setup
aa=['mma', 'sdas', 'asdsad']*1000
t=pd.DataFrame(aa)
a=['m', 'f', 'n']*1000
t1=pd.DataFrame(a)
df=p... | 1 | 2016-09-04T03:39:29Z | [
"python",
"string",
"performance",
"function",
"pandas"
] |
Python 2.7- fastest way to apply function to 2 columns of a pandas data frame | 39,312,737 | <p>I need to check if a string that is in one column of a pandas data frame is in another.
Example data:</p>
<pre><code>aa=['mma', 'sdas', 'asdsad']*1000
t=pd.DataFrame(aa)
a=['m', 'f', 'n']*1000
t1=pd.DataFrame(a)
t2=pd.concat([t,t1], axis=1)
t2.columns=['texto', 'textito']
</code></pre>
<p>With a lambda function I... | 2 | 2016-09-04T01:22:04Z | 39,313,959 | <p>Use a comprehension and <code>zip</code></p>
<pre><code>t2['veo1'] = [int(a in b) for a, b in zip(t2.textito, t2.texto)]
</code></pre>
<p><strong><em>Better answer per @Ninja Puppy</em></strong></p>
<pre><code>t2['veo1'] = pd.Series([a in b for a, b in zip(t2.textito, t2.texto)], dtype=int)
</code></pre>
<p><str... | 2 | 2016-09-04T05:55:20Z | [
"python",
"string",
"performance",
"function",
"pandas"
] |
Find all combination that sum to N when multiplies by index | 39,312,764 | <p>Given a number of items (<em>n</em>), what is the most efficient way to generate all possible lists [a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub>] of non-negative integers under the condition that:</p>
<p>1*a<sub>1</sub> + 2*a<sub>2</sub> + 3*a<sub>3</sub> + ... + n*a<sub>n</sub> = n </p>
<p>using Python?</p>
... | -1 | 2016-09-04T01:28:48Z | 39,312,998 | <p>A "greedy" algorithm works well for this. I'm using Python 3 here:</p>
<pre><code>def pick(total):
def inner(highest, total):
if total == 0:
yield result
return
if highest == 1:
result[0] = total
yield result
result[0] = 0
... | 2 | 2016-09-04T02:18:53Z | [
"python",
"algorithm",
"permutation",
"combinatorics"
] |
Create dictionary from multi-dimensional list without duplicating keys | 39,312,794 | <p>I'd like to take a list of tuples with multiple elements and turn it into a multi-dimensional dictionary without repeating keys. So if the following is my original list:</p>
<pre><code>myList = [('jeep', 'red', 2002, 4), ('jeep', 'red', 2003, 6), ('jeep', 'blue', 2003, 4), ('bmw', 'black', 2015, 8)]
</code></pre>
... | 2 | 2016-09-04T01:34:50Z | 39,312,820 | <p>Using a lot of <code>dict.setdefault</code>...</p>
<pre><code>myList = [('jeep', 'red', 2002, 4), ('jeep', 'red', 2003, 6), ('jeep', 'blue', 2003, 4), ('bmw', 'black', 2015, 8)]
d = {}
for model, colour, year, month in myList:
d.setdefault(model, {}).setdefault(colour, []).append([year, month])
</code></pre>
... | 4 | 2016-09-04T01:38:38Z | [
"python",
"dictionary",
"defaultdict"
] |
Create dictionary from multi-dimensional list without duplicating keys | 39,312,794 | <p>I'd like to take a list of tuples with multiple elements and turn it into a multi-dimensional dictionary without repeating keys. So if the following is my original list:</p>
<pre><code>myList = [('jeep', 'red', 2002, 4), ('jeep', 'red', 2003, 6), ('jeep', 'blue', 2003, 4), ('bmw', 'black', 2015, 8)]
</code></pre>
... | 2 | 2016-09-04T01:34:50Z | 39,313,069 | <p>Since what you want is essentially a tree data structure with a certain number of levels with lists for leaves, I'd be more explicit about it all by encapsulating the details inside a custom dictionary subclass because it could make the conversion extremely simple.</p>
<p>Here's a generic version of the data struct... | 1 | 2016-09-04T02:37:16Z | [
"python",
"dictionary",
"defaultdict"
] |
Selecting data in parenthesis | 39,312,852 | <p>I have a list of movies in a csv file, 100rows x 1column that looks like this:</p>
<pre><code>1. Mulholland Drive (David Lynch, 2001)
</code></pre>
<p>I'm trying to get rid of the number in the front, put the title, director, and year in each column. I did:</p>
<pre><code>rank = pd.read_csv("/Users/...csv", heade... | 2 | 2016-09-04T01:46:26Z | 39,312,899 | <p>If they're always definitely in that format, for instance - mocking up a file with just the given example (not that if you've got brackets or commas etc... etc... that don't match the format - this'll break):</p>
<pre><code>rank = pd.read_csv('somefile.csv', header=None, names=['film'])
df = rank.film.str.extract('... | 3 | 2016-09-04T01:56:59Z | [
"python",
"pandas",
"slice",
"parentheses"
] |
Running webdriver with Firefox Python | 39,312,903 | <p>I'm writing a program that will search a website for specific entries inside of articles, I'm using selenium webdriver for Python.</p>
<p>While attempting to connect to the site I get this exception:</p>
<pre><code>Traceback (most
recent call last):
File "search.py", line 26, in <module>
test.search_f... | 0 | 2016-09-04T01:57:29Z | 39,312,915 | <p>I fixed this, I deleted the <code>egg</code> that was installed and reinstalled selenium, it works perfectly now.</p>
| 1 | 2016-09-04T02:00:29Z | [
"python",
"selenium",
"firefox",
"exception",
"selenium-webdriver"
] |
How to convert string timestamp values to datetime64 dtype | 39,312,930 | <p>The resulting DataFrame below lists the <strong>Timestamp</strong> values as the strings:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'Time':['00:00:00:19','02:11:00:07','02:00:40:23']})
</code></pre>
<p>What method to use to convert these string values to datetime64 so the sum() and mean() functions cou... | 0 | 2016-09-04T02:04:13Z | 39,313,017 | <p>It's probably not the best way, but it's functional:</p>
<pre><code>durations = (df.Time.str.split(':', expand=True).applymap(int) * [24*60*60, 60*60, 60, 1]).sum(axis=1).apply(pd.Timedelta, unit='s')
</code></pre>
<p>Gives you:</p>
<pre><code>0 0 days 00:00:19
1 3 days 08:00:07
2 2 days 00:40:23
dtype: tim... | 1 | 2016-09-04T02:22:03Z | [
"python",
"dataframe"
] |
How to get rid of multiple whitespace AND account for a newline | 39,312,939 | <p>Say I have an input of <code>"Hello my name is \\n Bill"</code></p>
<pre><code>my_str = ' '.join(my_str.split())
</code></pre>
<p>So this will join the letters and give me <code>"Hello my name is\nBill"</code> when I print it all on one line. What I want it to print is:</p>
<pre><code>Hello my name is
Bill
... | 1 | 2016-09-04T02:08:42Z | 39,313,047 | <p>You problem is you don't have a newline char, you have two <em>backslashes</em> and an <code>n</code> i.e the backslash is escaped so after splitting you need to do a replace:</p>
<pre><code>In [10]: s = "Hello my name is \\n Bill"
In [11]: print(" ".join(s.split()))
Hello my name is \n Bill
In [12]: print(... | 2 | 2016-09-04T02:32:18Z | [
"python",
"whitespace",
"removing-whitespace"
] |
How can I maximize my figure on matplotlib python using macOS? | 39,312,957 | <pre><code>fig, ax = plt.subplots(figsize=(16,8),dpi=100,subplot_kwn {'projection':nccrs.PlateCarree()})
ax.set_global()
plt.subplots_adjust(left=0.04, bottom=0.02, right=0.96, top=0.96)
# set a figure window's title
fig2 = plt.gcf()
fig2.canvas.set_window_title('Metheoros 1.0')
mng = plt.get_current_fig_manager()
... | 0 | 2016-09-04T02:11:04Z | 39,314,263 | <p>The first line should have an equals sign in place of the n in subplot_kwn:</p>
<pre><code>fig, ax = plt.subplots(figsize=(16,8),dpi=100,subplot_kw= {'projection':ccrs.PlateCarree()})
</code></pre>
<p>You might want to check what you have imported cartopy.crs as, because that may cause problems as well. </p>
<hr>... | 0 | 2016-09-04T06:44:28Z | [
"python",
"osx",
"matplotlib"
] |
How can I maximize my figure on matplotlib python using macOS? | 39,312,957 | <pre><code>fig, ax = plt.subplots(figsize=(16,8),dpi=100,subplot_kwn {'projection':nccrs.PlateCarree()})
ax.set_global()
plt.subplots_adjust(left=0.04, bottom=0.02, right=0.96, top=0.96)
# set a figure window's title
fig2 = plt.gcf()
fig2.canvas.set_window_title('Metheoros 1.0')
mng = plt.get_current_fig_manager()
... | 0 | 2016-09-04T02:11:04Z | 39,321,764 | <pre><code># -*- coding: UTF-8 -*-
'''
Created on 4 de set de 2016
@author: VladimirCostadeAlencar
'''
from numpy import arange, sin, pi
import matplotlib
matplotlib.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wx import NavigationT... | 0 | 2016-09-04T21:45:46Z | [
"python",
"osx",
"matplotlib"
] |
Mapping a list as dictionary values | 39,312,969 | <p>I have a list of strings called lst which contains name, city, and email addresses for three people in such order. I have a dictionary called data that only contains keys.</p>
<pre><code>lst = ['James','New York','[email protected]','Matt','San Francisco','[email protected]','Jessica','Los Angeles','[email protected]']
... | -1 | 2016-09-04T02:13:35Z | 39,313,032 | <p>Here it is.</p>
<pre><code>lst = ['James','New York','[email protected]','Matt','San Francisco','[email protected]','Jessica','Los Angeles','[email protected]']
newlst = []
for i in xrange( 0, len(lst), 3 ):
d = {}
d['Name'] = lst[i]
d['City'] = lst[i+1]
d['Email'] = lst[i+2]
newlst.append( d )
pr... | 4 | 2016-09-04T02:26:33Z | [
"python",
"list",
"dictionary",
"list-comprehension"
] |
Mapping a list as dictionary values | 39,312,969 | <p>I have a list of strings called lst which contains name, city, and email addresses for three people in such order. I have a dictionary called data that only contains keys.</p>
<pre><code>lst = ['James','New York','[email protected]','Matt','San Francisco','[email protected]','Jessica','Los Angeles','[email protected]']
... | -1 | 2016-09-04T02:13:35Z | 39,313,065 | <p>Here's an approach using list comprehension. The idea is that we create a dictionary based on a zip of the keys and three values of a time.</p>
<pre><code>lst = [
'James', 'New York', '[email protected]',
'Matt', 'San Francisco', '[email protected]',
'Jessica', 'Los Angeles', '[email protected]',
]
keys = [... | 5 | 2016-09-04T02:36:45Z | [
"python",
"list",
"dictionary",
"list-comprehension"
] |
Is there a Python equivalent to MATLAB 'time' function? | 39,313,045 | <p>I'm porting a MATLAB R2011b code to Python 3.5.1.
The original MATLAB code, which was written around 10 years ago, contains a 'time' function as bellow:</p>
<pre><code>t_x=time(x,fsample);
</code></pre>
<p>The output is:</p>
<pre><code>debug> x
x =
-0.067000 -0.067000 -0.068000 -0.069000 -0.069000 -0.0... | 0 | 2016-09-04T02:31:24Z | 39,313,197 | <p>It should be simple enough to implement a similar function.</p>
<p>For numpy arrays</p>
<pre><code>import numpy as np
def time(x, fsample):
return np.linspace(0, (1000/fsample)*(len(x) - 1), num=len(x))
</code></pre>
<p>For simple python lists</p>
<pre><code>def time(x, fsample):
return [i*(1000/fsample)... | 2 | 2016-09-04T03:12:02Z | [
"python",
"matlab",
"time"
] |
grouping and summing multiindex dataframe in pandas | 39,313,103 | <p>I have a dataframe like this. </p>
<pre><code>df1=pd.DataFrame({"A":np.random.randint(1,10,4),"B":np.random.randint(1,10,4),"C":list('abba')})
df1.index.name="first"
df2=pd.DataFrame({"A":np.random.randint(1,10,5),"B":np.random.randint(1,10,5),"C":list('aaabb')})
df2.index.name="second"
df=pd.concat(... | 2 | 2016-09-04T02:46:25Z | 39,313,379 | <p>One way to do this would be:</p>
<pre><code>In [126]: df1=pd.DataFrame({"A":np.random.randint(1,10,4),"B":np.random.randint(1,10,4),"C":list('abba')})
In [127]: df2=pd.DataFrame({"A":np.random.randint(1,10,5),"B":np.random.randint(1,10,5),"C":list('aaabb')})
In [128]: df1
Out[128]:
A B C
0 7 9 a
1 1 3 ... | 0 | 2016-09-04T03:50:42Z | [
"python",
"pandas"
] |
grouping and summing multiindex dataframe in pandas | 39,313,103 | <p>I have a dataframe like this. </p>
<pre><code>df1=pd.DataFrame({"A":np.random.randint(1,10,4),"B":np.random.randint(1,10,4),"C":list('abba')})
df1.index.name="first"
df2=pd.DataFrame({"A":np.random.randint(1,10,5),"B":np.random.randint(1,10,5),"C":list('aaabb')})
df2.index.name="second"
df=pd.concat(... | 2 | 2016-09-04T02:46:25Z | 39,313,798 | <p>You can use <code>groupby</code> with a list of things that look like arrays. You want to use the first level of the index and column <code>'C'</code>.</p>
<pre><code>df.groupby([df.index.get_level_values(0), df.C]).sum() \
.unstack().stack(0).T.rename_axis(None)
</code></pre>
<p><a href="http://i.stack.imgur... | 2 | 2016-09-04T05:27:41Z | [
"python",
"pandas"
] |
phantomjs + selenium in python proxy-auth not working | 39,313,109 | <p>I'm trying to set a proxy for webscraping using selenium + phantomjs. I'm using python. </p>
<p>I've seen in many places that there is a bug in phantomjs such that proxy-auth does not work. </p>
<pre><code>from selenium.webdriver.common.proxy import *
from selenium import webdriver
from selenium.webdriver.common.b... | 4 | 2016-09-04T02:48:06Z | 39,639,557 | <p>I'm compiling answers from:
<a href="http://stackoverflow.com/questions/37331684/how-to-correctly-pass-basic-auth-every-click-using-selenium-and-phantomjs-webd">How to correctly pass basic auth (every click) using Selenium and phantomjs webdriver</a>
as well as:
<a href="http://stackoverflow.com/questions/16740188/b... | 2 | 2016-09-22T12:49:37Z | [
"python",
"selenium",
"proxy",
"phantomjs"
] |
relationship between the binary executables and the rest of the python installation | 39,313,175 | <p>I have python version 3.4 installed on my computer. One part of the installation is the directory with the binary executables: </p>
<pre><code> /Library/Frameworks/Python.framework/Versions/3.4/bin/
</code></pre>
<p>As far as I understand it, these binary executables constitute the framework, which makes it possib... | 0 | 2016-09-04T03:06:21Z | 39,313,264 | <p>In simple terms, <code>python</code> and <code>pip</code> are binary executables. </p>
<p><code>numpy</code> is a module. </p>
<p>You cannot run a command called <code>numpy</code> from the terminal, therefore it is not a binary executable. </p>
<p>Some python packages are binary executables and you can execute t... | 1 | 2016-09-04T03:25:35Z | [
"python",
"binaryfiles"
] |
Calculate bytes between two hex offsets | 39,313,181 | <p>In Python, I'm trying to extract some data from a binary file. I know the offsets of my data. They are always the same. For instance, written beneath is the first 4 offsets and the converted offset as a decimal value.</p>
<ul>
<li>Offset1 - 0x00000409 - 1033</li>
<li>Offset2 - 0x0000103A - 4154</li>
<li>Offset3 - 0... | 0 | 2016-09-04T03:07:57Z | 39,313,298 | <p>use <code>file.seek()</code> to skip between locations in a file. In this case, to go to the next location in the file, you would use <code>file.seek(3121, 1)</code> which seeks 3121 bytes ahead relative to the current position.</p>
<p>EDIT: I didn't realize you were changing the file position after opening it, so ... | 1 | 2016-09-04T03:30:40Z | [
"python",
"binary",
"hex",
"offset",
"bytecode"
] |
What is the correct way to use and logical operator in python for multiple conditions? | 39,313,185 | <p>I'm trying to brute-force a projecteuler questions before I improve my code. I can't get multiple condition and logical operator working in my loop. Here is the code, editor shows no errors but it simply don't increase condition value so obviously some of the conditions are wrong. Can some one show me the correct wa... | 0 | 2016-09-04T03:08:35Z | 39,313,317 | <p>It looks like you're trying to find the smallest number which is a multiple of all integers from 1 to 20 inclusive. You're starting with 20, and you want to keep going up by 20 until your condition is met.</p>
<p>It's easier to see the problem in a smaller case. Say we only cared about 2, 3, and 4.</p>
<p>We wan... | 1 | 2016-09-04T03:36:52Z | [
"python",
"operators",
"brute-force",
"logical"
] |
Variable is not defined in the function | 39,313,224 | <pre><code>import random
def game(n):
while counter < n:
n1 = random.randrange(1,10)
n2 = random.randrange(1,10)
counter = 0
print (str(n1) + " + " + str(n1))
answer = input("Enter answer: ")
if answer == n1+n2:
print("Correct.")
else:
print("Incorrect... | -2 | 2016-09-04T03:17:27Z | 39,313,459 | <p>Here's what you need to fix:</p>
<ol>
<li>Your indentation is all over the place.</li>
<li>You were trying use <code>counter</code> as part of your condition in your loop before you even gave it a value.</li>
<li>Because you created <code>n1</code> and <code>n2</code> inside of the body of your while loop, after ev... | 0 | 2016-09-04T04:07:11Z | [
"python",
"variables",
"scope",
"definition"
] |
Slicing after convolution , -1 index does not work | 39,313,232 | <p>After going through the N-Dimensional array convolution in Python found here on <a href="http://stackoverflow.com/questions/39220929/python-convolution-with-different-dimension"> SO</a>
I now face a problem around which I cannot wrap my head.
The convolution provided by from <code>scipy.ndimage</code> does not allow... | 1 | 2016-09-04T03:19:01Z | 39,313,303 | <p>In Python the upper bound of a slice is open</p>
<pre><code>In [699]: np.arange(5)
Out[699]: array([0, 1, 2, 3, 4])
In [700]: np.arange(5)[:4]
Out[700]: array([0, 1, 2, 3])
In [701]: np.arange(5)[:-1]
Out[701]: array([0, 1, 2, 3])
In [702]: np.arange(5)[1:-1]
Out[702]: array([1, 2, 3])
</code></pre>
<p>In all Pyth... | 4 | 2016-09-04T03:32:09Z | [
"python",
"numpy",
"scipy"
] |
python lambda raises variable not defined error with multiple arguments | 39,313,318 | <p>When trying to write a one line Fibonacci sequence that I understand, I'm having an issue with <code>fib = lambda a, b: b, a + b</code> as <code>"'b' is not defined"</code></p>
<p>However, when I do <code>sum = a, b, c: a + b + c</code> I get no errors. <code>sum(1, 2, 3)</code> runs perfectly and returns <code>6<... | 0 | 2016-09-04T03:37:02Z | 39,313,353 | <p>You need to put parentheses around the lambda body:</p>
<pre><code>fib = lambda a, b: (b, a + b)
</code></pre>
<p>Otherwise Python thinks it is this:</p>
<pre><code>fib = (lambda a, b: b), a + b
</code></pre>
<p>Incidentally, there's no real purpose in using <code>lambda</code> if you're just going to assign the... | 4 | 2016-09-04T03:44:41Z | [
"python",
"python-3.x",
"lambda"
] |
Probabilistic agent traversing a 4x4 grid world with joint probability distribution | 39,313,407 | <p>Iâm trying to solve a probabilistic agent for a simple board game from the book A Modern Approach to AI, but am having some trouble with the basic math and mostly the full joint distribution, so Iâm asking for some pointers.</p>
<p>The board is 4x4 squares
There is 1 monster and 2 pits somewhere on the board
Th... | 2 | 2016-09-04T03:57:03Z | 39,316,486 | <p>The Bxy values are indicators of whether or not a breeze was observed in a cell xy. They're formally defined as:</p>
<p>Bxy = 1 if and only if a breeze was observed in (x, y),<br>
Bxy = 0 otherwise</p>
<p>So, in your example situation, we already know that<br>
B11 = 0, B12 = 1, B21 = 1</p>
<p>Similarly, the varia... | 0 | 2016-09-04T11:35:37Z | [
"python",
"artificial-intelligence",
"probability",
"agent"
] |
__init__() compared to __init__.py | 39,313,413 | <p>I am working on a game right now but I really hate having a few thousand lines to scroll through when finding a bug to fix or a new feature has stuffed up another function. I have kept everything in one main class and when I looked into writing each function into a different file, I had one problem, I couldn't find ... | 0 | 2016-09-04T03:57:56Z | 39,313,575 | <p>I was wrong in my comment, you can do as you describe, but as @Ignacio stated its not good code design. Here's an example anyway because I was curious:</p>
<pre><code>#Empty my_game 'class'
class my_game:
pass
#Function you can put in a different file and import here
#Will become set as the new init function t... | 0 | 2016-09-04T04:33:58Z | [
"python",
"filesystems",
"init"
] |
Does python have an equivalent to Javascript's 'btoa' | 39,313,421 | <p>I'm trying to find an exact equivalent to javascript's function 'btoa', as I want to encode a password as base64. It appears that there are many options however, as listed here: </p>
<p><a href="https://docs.python.org/3.4/library/base64.html" rel="nofollow">https://docs.python.org/3.4/library/base64.html</a></p>
... | 2 | 2016-09-04T03:58:57Z | 39,313,581 | <p>Python's <a href="https://docs.python.org/3.4/library/base64.html" rel="nofollow">Base64</a>:</p>
<pre><code>import base64
encoded = base64.b64encode('Hello World!')
print encoded
# value of encoded is SGVsbG8gV29ybGQh
</code></pre>
<p>Javascript's <a href="http://www.w3schools.com/jsref/met_win_btoa.asp" rel="n... | 3 | 2016-09-04T04:34:51Z | [
"python",
"base64"
] |
The use of recursion in merge sort for python | 39,313,492 | <p>I am learning merge sort in python, and I am a little confused by the implementation of the following program. According to my understanding, when <code>mergeSort ([3,1], compare)</code> is implemented, it splits into <code>mergeSort([3], compare)</code> and <code>mergeSort([1], compare)</code>. and then <code>merge... | 2 | 2016-09-04T04:13:50Z | 39,313,542 | <p>This code prints <code>L</code> as it is being recursively split apart. It doesn't actually print the result of any merges. You can see the result of each merge by changing the line</p>
<pre><code>return merge(left, right, compare)
</code></pre>
<p>to</p>
<pre><code>merged = merge(left, right, compare)
print "mer... | 0 | 2016-09-04T04:27:48Z | [
"python",
"recursion",
"mergesort"
] |
The use of recursion in merge sort for python | 39,313,492 | <p>I am learning merge sort in python, and I am a little confused by the implementation of the following program. According to my understanding, when <code>mergeSort ([3,1], compare)</code> is implemented, it splits into <code>mergeSort([3], compare)</code> and <code>mergeSort([1], compare)</code>. and then <code>merge... | 2 | 2016-09-04T04:13:50Z | 39,313,574 | <p>This is the problem:</p>
<pre><code> print "left = ", L[:middle] # content of L before sorting
</code></pre>
<p>Replace this line and other analogous <code>print</code> statements with:</p>
<pre><code> print "left = ", left # actual result of mergeSort
</code></pre>
| 2 | 2016-09-04T04:33:52Z | [
"python",
"recursion",
"mergesort"
] |
The use of recursion in merge sort for python | 39,313,492 | <p>I am learning merge sort in python, and I am a little confused by the implementation of the following program. According to my understanding, when <code>mergeSort ([3,1], compare)</code> is implemented, it splits into <code>mergeSort([3], compare)</code> and <code>mergeSort([1], compare)</code>. and then <code>merge... | 2 | 2016-09-04T04:13:50Z | 39,313,577 | <pre><code>left = mergeSort(L[:middle], compare)
print "left = ", left
right = mergeSort(L[middle:], compare)
print "right = ", right
</code></pre>
<p>This should work.</p>
| 1 | 2016-09-04T04:34:19Z | [
"python",
"recursion",
"mergesort"
] |
Directing output from cron (calls) bash (calls) python3 | 39,313,645 | <p>I have a simple python script, <code>test.py</code>, which prints the date and time and then raises an error. </p>
<p>I have a bash function defined in <code>.bash_profile</code> and named <code>test()</code>, which calls the script with </p>
<pre><code>$ python3 ~/test.py
</code></pre>
<p>Finally, I have a cron... | 0 | 2016-09-04T04:49:40Z | 39,314,211 | <p>First of all <code>test</code> is a bad name for a function as almost all shells have <code>test</code> builtin and also there is external <code>test</code> command available in almost all systems.</p>
<p>Now, when you run something in <code>cron</code>, unlike starting of a login and/or interactive shell session n... | 2 | 2016-09-04T06:38:00Z | [
"python",
"bash",
"cron"
] |
Directing output from cron (calls) bash (calls) python3 | 39,313,645 | <p>I have a simple python script, <code>test.py</code>, which prints the date and time and then raises an error. </p>
<p>I have a bash function defined in <code>.bash_profile</code> and named <code>test()</code>, which calls the script with </p>
<pre><code>$ python3 ~/test.py
</code></pre>
<p>Finally, I have a cron... | 0 | 2016-09-04T04:49:40Z | 39,322,249 | <p>Why not just put the following line directly in your <code>crontab,</code> and eliminate the <em><code>test()</code> bash function</em> middleman?</p>
<pre><code>* * * * 1 /usr/bin/python3 /home/myname/test.py >> ~/$(date +\%Y-\%m-\%d_\%H:\%M:\%S).log 2>&1
</code></pre>
| 0 | 2016-09-04T23:12:11Z | [
"python",
"bash",
"cron"
] |
How does python interpreter run the code line by line in the following code? | 39,313,677 | <p>I have read that the interpreter runs the code line by line and reports the error if any at the same time and stops the further execution.
So in python, consider the file <code>ex1.py</code>,</p>
<pre><code>print "Hello world"
12variable = 'bye'
print 12variable
</code></pre>
<p>Now according to the working of int... | 2 | 2016-09-04T04:58:06Z | 39,313,702 | <p>Because your understanding of the interpreter is faulty. While it is possible for the behaviour you are describing to occur for a subset of errors it is not the common case for many (most?) errors.</p>
<p>If the interpreter can construct what it thinks is a valid program but there is an error at run time then what ... | 1 | 2016-09-04T05:04:22Z | [
"python",
"syntax-error",
"interpreter"
] |
How does python interpreter run the code line by line in the following code? | 39,313,677 | <p>I have read that the interpreter runs the code line by line and reports the error if any at the same time and stops the further execution.
So in python, consider the file <code>ex1.py</code>,</p>
<pre><code>print "Hello world"
12variable = 'bye'
print 12variable
</code></pre>
<p>Now according to the working of int... | 2 | 2016-09-04T04:58:06Z | 39,313,711 | <p>It's a myth that Python is a fully interpreted language. When CPython runs a script the source code is parsed (this is where it will catch syntax errors), and compiled into bytecode (sometimes these are cached in your directory as <code>.pyc</code> files) before anything is executed. In this regard Python is not all... | 3 | 2016-09-04T05:06:01Z | [
"python",
"syntax-error",
"interpreter"
] |
How does python interpreter run the code line by line in the following code? | 39,313,677 | <p>I have read that the interpreter runs the code line by line and reports the error if any at the same time and stops the further execution.
So in python, consider the file <code>ex1.py</code>,</p>
<pre><code>print "Hello world"
12variable = 'bye'
print 12variable
</code></pre>
<p>Now according to the working of int... | 2 | 2016-09-04T04:58:06Z | 39,313,813 | <p>It depends on how you run the Python interpréter. If you give it a full source file, it will first parse the whole file and convert it to bytecode before execution any instruction. But if you feed it line by line, it will parse and execute the code <em>bloc by bloc</em>:</p>
<ul>
<li><code>python script.py</code> ... | 3 | 2016-09-04T05:30:31Z | [
"python",
"syntax-error",
"interpreter"
] |
pandas dropping of words in dataframe | 39,313,680 | <p>I have a sample dataframe that I wish to drop all words and keep the values. </p>
<pre><code>Column1 Column2 Column3 Column4 Column5
5FQ 1.047 S$55.3 UG44.2 as of 02/Jun/2016 S$8.2 mm
</code></pre>
<p>Is it possible to drop words and keep all the numbers? IE: to get ... | 1 | 2016-09-04T04:59:28Z | 39,313,796 | <p>One way would be to do:</p>
<pre><code>In [212]: df
Out[212]:
Column1 Column2 Column3 Column4 Column5
0 5FQ 1.047 S$55.3 UG44.2 as of 02/Jun/2016 S$8.2 mm
In [213]: df.apply(lambda x: x.astype(str).str.extract(r'(\d+\.?\d*)', expand=True).astype(np.float))
Out[213]:
Column1 C... | 3 | 2016-09-04T05:27:34Z | [
"python",
"regex",
"dataframe"
] |
pandas dropping of words in dataframe | 39,313,680 | <p>I have a sample dataframe that I wish to drop all words and keep the values. </p>
<pre><code>Column1 Column2 Column3 Column4 Column5
5FQ 1.047 S$55.3 UG44.2 as of 02/Jun/2016 S$8.2 mm
</code></pre>
<p>Is it possible to drop words and keep all the numbers? IE: to get ... | 1 | 2016-09-04T04:59:28Z | 39,313,799 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow"><code>pd.Series.extract</code></a>:</p>
<pre><code>In [28]: for c in df:
df[c] = df[c].str.extract('(\d+\.?\d*)', expand=False)
....:
In [29]: df
Out[29]:
Column1 Column2 Column3... | 3 | 2016-09-04T05:27:45Z | [
"python",
"regex",
"dataframe"
] |
Python Profiling: What does "method 'poll' of 'select.poll' objects"? | 39,313,762 | <p>I have profiled my python code using python's <code>cProfile</code> module and got the following results:</p>
<pre><code> ncalls tottime percall cumtime percall filename:lineno(function)
13937860 96351.331 0.007 96351.331 0.007 {method 'poll' of 'select.poll' objects}
13930480 201.012 0.000 201.0... | 0 | 2016-09-04T05:20:00Z | 39,313,825 | <p>It's part of the python library. It's used to read events from I/O. By definition it will wait for events so it will take longer. Not something that you should be changing.</p>
| 0 | 2016-09-04T05:34:47Z | [
"python",
"methods",
"profiling"
] |
Python Profiling: What does "method 'poll' of 'select.poll' objects"? | 39,313,762 | <p>I have profiled my python code using python's <code>cProfile</code> module and got the following results:</p>
<pre><code> ncalls tottime percall cumtime percall filename:lineno(function)
13937860 96351.331 0.007 96351.331 0.007 {method 'poll' of 'select.poll' objects}
13930480 201.012 0.000 201.0... | 0 | 2016-09-04T05:20:00Z | 39,314,087 | <p>After doing some experiments I figured it out: My program does most of its work wrapped in sharedmem's parallel map method:</p>
<pre><code>with sharedmem.MapReduce() as pool:
pool.map(myMethod, argumentList)
</code></pre>
<p>However, <code>myMethod</code> does not appear anywhere in the profile log. Moreover, ... | 0 | 2016-09-04T06:18:14Z | [
"python",
"methods",
"profiling"
] |
UnicodeEncodeError Only When Script is Run as a Subprocess | 39,313,780 | <p>I'm running my main script in Python 3.5 using the Spyder IDE, and I want to import functions from a script that happens to only work in Python 3.4. So I was recommended to run this second script as a subprocess like so:</p>
<pre><code>import subprocess
cmd = [r'c:\python34\pythonw.exe', r'C:\users\John\Desktop\scr... | 0 | 2016-09-04T05:23:46Z | 39,314,123 | <p>In short, your issue is as follows:</p>
<ul>
<li>Python IDE fully supports UTF-8 encoding, and that's why your invoked script runs fine there.</li>
<li>On the other hand, when opening a subprocess, since you are on Windows, you are using Windows1252 charset by default, which doesn't support part of your output.</li... | 0 | 2016-09-04T06:23:08Z | [
"python",
"subprocess"
] |
Sentinel object and it's applications? | 39,313,943 | <p>I know in python the builtin object() returns a sentinel object. I'm curious to what it is, but mainly it's applications. </p>
<p>Thanks.</p>
| 0 | 2016-09-04T05:52:40Z | 39,314,200 | <p><code>object</code> is the base class that all other classes inherit from in python 3. There's not a whole lot you can do with a plain old object. However an object's <em>identity</em> could be useful. For example the <a href="https://docs.python.org/3/library/functions.html#iter" rel="nofollow">iter</a> function t... | 1 | 2016-09-04T06:36:00Z | [
"python"
] |
python..I am stuck with one of the functions for and while loop | 39,314,011 | <p>I need to create a game to be played n times and adds numbers from 0 to 10. First number is entered by the player, second is generated by the program. After that the player has to guess the answer. If it is correct the program prints'correct' and same for the opposite('incorrect').In the end of the game the program ... | -1 | 2016-09-04T06:06:22Z | 39,314,066 | <p>Value of <code>count</code> is reinitialize every time to zero </p>
<pre><code>def game(n):
count=0 # declare count here
for _ in range(n): # you can use some variable here instead of _ to increase code clarity
a=int(input('Enter a number:')) # As suggested use int instead of eval read end of post
... | 0 | 2016-09-04T06:15:56Z | [
"python"
] |
python..I am stuck with one of the functions for and while loop | 39,314,011 | <p>I need to create a game to be played n times and adds numbers from 0 to 10. First number is entered by the player, second is generated by the program. After that the player has to guess the answer. If it is correct the program prints'correct' and same for the opposite('incorrect').In the end of the game the program ... | -1 | 2016-09-04T06:06:22Z | 39,314,122 | <p>Do not use <code>eval</code>. You expect an integer from the user, use <code>int</code>. </p>
<p>Then move the <code>count</code> variable outside the loop to avoid recreating new <code>count</code> variables with every iteration and resetting the value to zero.</p>
<pre><code>def game(n):
count = 0
for _ ... | 0 | 2016-09-04T06:23:08Z | [
"python"
] |
do I need lock to protect mutli-thread race condition in my code | 39,314,024 | <p>Using Python 2.7 on Windows, and will use Jython which support true multi-threading. The method <code>sendMessage</code> is used to receive message from a specific client, and the client may send the same message to a few other clients (which is what parameter <code>receivers</code> is for, and <code>receivers</code... | 1 | 2016-09-04T06:08:54Z | 39,343,271 | <p>Race conditions is about two or more threads changing some global states at the same time.</p>
<p>In your code for <code>sendMessage</code>, you are changing <code>self.messagePool[r]</code>, which is a global object. Hence, <code>self.messagePool[r]</code> should be locked before appending a new item.</p>
<p>Same... | 2 | 2016-09-06T07:42:15Z | [
"python",
"multithreading",
"python-2.7",
"jython"
] |
do I need lock to protect mutli-thread race condition in my code | 39,314,024 | <p>Using Python 2.7 on Windows, and will use Jython which support true multi-threading. The method <code>sendMessage</code> is used to receive message from a specific client, and the client may send the same message to a few other clients (which is what parameter <code>receivers</code> is for, and <code>receivers</code... | 1 | 2016-09-04T06:08:54Z | 39,343,544 | <p>I suggest to use <code>Queue</code> instead of <code>list</code>. It is designed for append\pop in threads with locking.</p>
| 4 | 2016-09-06T07:56:49Z | [
"python",
"multithreading",
"python-2.7",
"jython"
] |
do I need lock to protect mutli-thread race condition in my code | 39,314,024 | <p>Using Python 2.7 on Windows, and will use Jython which support true multi-threading. The method <code>sendMessage</code> is used to receive message from a specific client, and the client may send the same message to a few other clients (which is what parameter <code>receivers</code> is for, and <code>receivers</code... | 1 | 2016-09-04T06:08:54Z | 39,357,991 | <p>I think this question is already well-answered for CPython <a href="http://stackoverflow.com/questions/17682484/is-collections-defaultdict-thread-safe">here</a> and <a href="http://stackoverflow.com/questions/6319207/are-lists-thread-safe">here</a> (basically, you're safe because of GIL, although nothing in document... | 3 | 2016-09-06T21:18:06Z | [
"python",
"multithreading",
"python-2.7",
"jython"
] |
python : ImportError: No module named utils with clean_string | 39,314,115 | <p>Note: I have already check question with same error as mine but mine is different i want to ask if "clean_string, clean_number, clean_text, clean_float, clean_int"</p>
<p><strong><code>agency_id = scrapy.Field(serializer=clean_string)</code></strong></p>
<p>are some in built function in python or i have to import ... | 1 | 2016-09-04T06:22:23Z | 39,314,228 | <p>As per our discussion, please install <code>python -m pip install pyes</code></p>
<p>do it as below:</p>
<pre><code>from pyes import utils
# use it like below
class MyItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
agency_id = scrapy.Field(serializer=utils.clean... | 0 | 2016-09-04T06:40:07Z | [
"python"
] |
Why \ is used at the end of print statement in python? | 39,314,252 | <p>Consider the code:</p>
<pre><code>firstName = raw_input("Your fist Name: ")
lastName = raw_input("Your last Name: ")
print "Hello %s, May I call you" \
"Mr. %s?" % (firstName,lastName)
</code></pre>
<p>In line 3, what is the use of <code>\</code> ?</p>
| 0 | 2016-09-04T06:43:27Z | 39,314,268 | <p>It allows you to do a line break and continue your statement on the next line</p>
| 1 | 2016-09-04T06:45:02Z | [
"python",
"syntax"
] |
Why \ is used at the end of print statement in python? | 39,314,252 | <p>Consider the code:</p>
<pre><code>firstName = raw_input("Your fist Name: ")
lastName = raw_input("Your last Name: ")
print "Hello %s, May I call you" \
"Mr. %s?" % (firstName,lastName)
</code></pre>
<p>In line 3, what is the use of <code>\</code> ?</p>
| 0 | 2016-09-04T06:43:27Z | 39,314,270 | <p>The <code>\</code> tells Python that the statement continues on the next line. So, the <code>print</code> statement doesn't end on the first line, it continues on the next.</p>
<pre><code>print "Hello %s, May I call you" \
"Mr. %s?" % (firstName,lastName)
</code></pre>
<p>Is the same as:</p>
<pre><code>print "Hel... | 1 | 2016-09-04T06:45:10Z | [
"python",
"syntax"
] |
Why \ is used at the end of print statement in python? | 39,314,252 | <p>Consider the code:</p>
<pre><code>firstName = raw_input("Your fist Name: ")
lastName = raw_input("Your last Name: ")
print "Hello %s, May I call you" \
"Mr. %s?" % (firstName,lastName)
</code></pre>
<p>In line 3, what is the use of <code>\</code> ?</p>
| 0 | 2016-09-04T06:43:27Z | 39,314,274 | <p>The <code>\</code> character is used to break up long lines so they're easier to read and manage. The third and fourth lines could have been written as a single line without the <code>\</code> instead: </p>
<pre><code>print "Hello %s, May I call youMr. %s?" % (firstName,lastName)
</code></pre>
<p>(note there is no... | 1 | 2016-09-04T06:45:15Z | [
"python",
"syntax"
] |
Why \ is used at the end of print statement in python? | 39,314,252 | <p>Consider the code:</p>
<pre><code>firstName = raw_input("Your fist Name: ")
lastName = raw_input("Your last Name: ")
print "Hello %s, May I call you" \
"Mr. %s?" % (firstName,lastName)
</code></pre>
<p>In line 3, what is the use of <code>\</code> ?</p>
| 0 | 2016-09-04T06:43:27Z | 39,314,276 | <p>to make you able to spilt a single line of string to many lines.</p>
| 1 | 2016-09-04T06:45:32Z | [
"python",
"syntax"
] |
Where does `pip` install libraries compared to where `python` from terminal runs? | 39,314,282 | <p>I'm trying to install <code>python's scikit learn</code> for some machine learning, and it appears to do it successfully (i.e. it is already installed). However, when I try to actually use it in <code>python</code> in the terminal, it gives me an error, as shown below. </p>
<pre><code>23:39 $ sudo pip install skl... | 0 | 2016-09-04T06:46:14Z | 39,314,463 | <p>This problem doesn't have anything to do with python package paths. It is due to the unresolved symbol <code>___addtf3</code> which is a GCC software floating point routine provided by a <code>gfortran</code> library. A <a href="https://github.com/JuliaLang/julia/issues/636" rel="nofollow">similar issue with a diffe... | 0 | 2016-09-04T07:13:23Z | [
"python",
"python-2.7",
"terminal",
"scikit-learn"
] |
Openerp, how to make a unique record | 39,314,292 | <p>I am currently working with <code>hr_holidays</code> (aka <code>Leave Management</code>) Module and I need to add leave allocation as a unique record for given type of leave.</p>
<p>I have added one extra condition in the <code>create()</code> function and that result in not allowing any making leave request to be... | 0 | 2016-09-04T06:47:49Z | 39,316,446 | <p>Instead of doing a search anytime you want to create a new record, enforce a <code>UniqueConstraint</code> on the database, that wouldn't allow duplicate records to be created, with this</p>
<pre><code>_sql_constraints = [
('unique_hol_empid_type', 'unique(holiday_status_id, employee_id, type)', 'Error: Alr... | 1 | 2016-09-04T11:31:08Z | [
"python",
"python-2.7",
"openerp"
] |
ordinal suffix of the letter of a word python 3.5. | 39,314,327 | <pre><code>import random
import string
import sys
vowels = ['a', 'e', 'i', 'o', 'u']
consonants = [x for x in string.ascii_lowercase if x not in vowels]
SelectedWords = ['TRAILER', 'LAPTOP', 'SUNFLOWER', 'SKIPPING', 'AIRPLANE', 'HOUR', 'POTATO', 'HUGE', 'TINY', 'GOOD', 'BAD', 'YES', 'NO', 'WAGON', 'QUESTION', 'LAGOON'... | -3 | 2016-09-04T06:53:31Z | 39,314,419 | <p>If you are looking to convert 1 => 1st, 2 => 2nd, 3 => 3rd, etc... this is the easiest way I can think of. This special cases 1, 2, 3 and all numbers ending in 1, 2 or 3 except 11, 12 and 13.</p>
<pre><code>num_suffix = lambda x: "{}{}".format(x, {1: "st", 2: "nd", 3: "rd"}.get(0 if 10 > x > 14 else x % 10, ... | 2 | 2016-09-04T07:06:24Z | [
"python",
"python-3.x"
] |
ordinal suffix of the letter of a word python 3.5. | 39,314,327 | <pre><code>import random
import string
import sys
vowels = ['a', 'e', 'i', 'o', 'u']
consonants = [x for x in string.ascii_lowercase if x not in vowels]
SelectedWords = ['TRAILER', 'LAPTOP', 'SUNFLOWER', 'SKIPPING', 'AIRPLANE', 'HOUR', 'POTATO', 'HUGE', 'TINY', 'GOOD', 'BAD', 'YES', 'NO', 'WAGON', 'QUESTION', 'LAGOON'... | -3 | 2016-09-04T06:53:31Z | 39,314,421 | <p>Here is the full revised code. There will obviously be issues with numbers larger than 10, it would be possible to either add numbers to the map or write a function with rules to determine what the correct ordinal suffix would be based on the current map but I know that the original OP didn't want any more than one ... | 0 | 2016-09-04T07:06:26Z | [
"python",
"python-3.x"
] |
Best practice for predicting values from model with Chainer | 39,314,364 | <p>With <a href="http://chainer.org/" rel="nofollow">Chainer</a>, I have created <code>model.pkl</code> with <em>Iris Datasets</em> (<a href="https://github.com/silwyb/train-iris" rel="nofollow">https://github.com/silwyb/train-iris</a>). So I can evaluate datasets, but I don't know the best way to output predicted valu... | -1 | 2016-09-04T06:58:52Z | 39,325,789 | <p>The following works.
<a href="https://github.com/silwyb/train-iris/blob/master/predict.py" rel="nofollow">silwyb/train-iris/predict.py</a></p>
<pre><code>def predict(x_test):
x = Variable(x_test)
h1 = F.dropout(F.relu(model.l1(x)))
h2 = F.dropout(F.relu(model.l2(h1)))
y = model.l3(h2)
return n... | 0 | 2016-09-05T07:37:11Z | [
"python",
"chainer"
] |
Javascript date string to python datetime object | 39,314,501 | <p>The current datetime is passed via an <strong>ajax request</strong> to a <strong>django backend</strong> where it will be stored in the database. To store it in the database, the date must first be converted to a <code>datetime</code> object which can be done for a date of the in UTC format (Eg. <code>Sun, 04 Sep 20... | 1 | 2016-09-04T07:21:23Z | 39,314,850 | <p>Your first problem is that the input has a different format. But unfortunatelly for you, that is not your only problem and it wouldn't work even if you fixed that.</p>
<p>The truth is that even the first format would fail with a different timezone:</p>
<pre><code>datetime.strptime("Sun, 04 Sep 2016 07:13:06 IST", ... | 0 | 2016-09-04T08:08:44Z | [
"javascript",
"python",
"django",
"datetime"
] |
Javascript date string to python datetime object | 39,314,501 | <p>The current datetime is passed via an <strong>ajax request</strong> to a <strong>django backend</strong> where it will be stored in the database. To store it in the database, the date must first be converted to a <code>datetime</code> object which can be done for a date of the in UTC format (Eg. <code>Sun, 04 Sep 20... | 1 | 2016-09-04T07:21:23Z | 39,314,936 | <p>You can use python's <code>dateutil</code> module to parse your date.</p>
<pre><code>from dateutil import parser
parser.parse("Sun, 04 Sep 2016 07:13:06 GMT+0530 (IST)")
</code></pre>
<p>It gives the output as a datetime object:</p>
<pre><code>datetime.datetime(2016, 9, 4, 7, 13, 6, tzinfo=tzoffset(u'IST', -19800... | 0 | 2016-09-04T08:22:41Z | [
"javascript",
"python",
"django",
"datetime"
] |
join two pandas pivot tables | 39,314,505 | <p>Considering two similar pandas pivot tables, how to join these two tables on their indexes e.g. <code>country</code>. For example: </p>
<pre><code>df1.pivot_table(index='country', columns='year', values=['rep','sales'], aggfunc='first')
rep sales
year 2013 201... | 1 | 2016-09-04T07:22:04Z | 39,314,754 | <blockquote>
<p>How to join these tables</p>
</blockquote>
<p>Is vague. There are many ways to join these tables.</p>
<h3>Setup</h3>
<pre><code>idx = pd.Index(['fr', 'uk', 'usa'], name='country')
col = pd.MultiIndex.from_product([['rep', 'sales'], range(2013, 2017)],
names=[None, ... | 1 | 2016-09-04T07:55:49Z | [
"python",
"pandas",
"join"
] |
CSV delimiter doesn't work properly [Python] | 39,314,544 | <pre><code>import csv
base='[email protected],username1\
[email protected],username2\
[email protected],username3\
[email protected],username4\
[email protected],username5'
parsed=csv.reader(base, delimiter=',')
for p in parsed:
print p
</code></pre>
<p>Returns:</p>
<pre><code>['e']
['e']
['s']
['t']
['1']
['@']
['m']
['a']
[... | 0 | 2016-09-04T07:27:47Z | 39,314,628 | <p>I think csv only works with file like objects. You can use StringIO in this case.</p>
<pre><code>import csv
import StringIO
base='''[email protected],username
[email protected],username2
[email protected],username3
[email protected],username4
[email protected],username5'''
parsed=csv.reader(StringIO.StringIO(base), delimiter='... | 2 | 2016-09-04T07:38:08Z | [
"python",
"csv"
] |
CSV delimiter doesn't work properly [Python] | 39,314,544 | <pre><code>import csv
base='[email protected],username1\
[email protected],username2\
[email protected],username3\
[email protected],username4\
[email protected],username5'
parsed=csv.reader(base, delimiter=',')
for p in parsed:
print p
</code></pre>
<p>Returns:</p>
<pre><code>['e']
['e']
['s']
['t']
['1']
['@']
['m']
['a']
[... | 0 | 2016-09-04T07:27:47Z | 39,315,289 | <p>Quoting <a href="https://docs.python.org/3/library/csv.html#csv.reader" rel="nofollow">official docs on csv module</a> (<strong>emphasis mine</strong>):</p>
<blockquote>
<p><code>csv.reader(csvfile, dialect='excel', **fmtparams)</code></p>
<p>Return a reader object which will iterate over lines in the given
... | 1 | 2016-09-04T09:07:17Z | [
"python",
"csv"
] |
Python - Unable to detect face and eye? | 39,314,610 | <p>I am trying to create a face and eye detection using OpenCV library. This is the code I been working with. It's running smoothly with no errors but the only problem is not showing any results no faces and eyes are found with this code </p>
<pre><code>import cv2
import sys
import numpy as np
import os
# Get user su... | 2 | 2016-09-04T07:35:11Z | 39,319,534 | <p>For me it works in my jupyter notebook on Ubuntu 15.10 using OpenCV 3.1.0-dev with python 3.4</p>
<p>Could it be, that you have a simple typo?</p>
<p><code>haarcascad_frontalface_default.xml</code> => <code>haarcascade_frontalface_default.xml</code></p>
<p>and here: </p>
<p><code>eyes = eyeCascade.detectMultisc... | 2 | 2016-09-04T17:18:36Z | [
"python",
"opencv",
"numpy",
"face-detection",
"eye-detection"
] |
How to trigger an event using pyquery python | 39,314,627 | <p>I'm trying to automate a headless web browser using python and packages like pyquery, beautiful soup, requests, mechanize.</p>
<p>But so far I haven't found a right way to trigger a click event on a button. For example, to fill an online form, I'm able to insert values in the text fields, but not able to click on t... | -2 | 2016-09-04T07:38:08Z | 39,314,823 | <p>According to the <a href="https://pypi.python.org/pypi/pyquery" rel="nofollow">docs</a>, pyquery isn't a library to interact with JS code (at least not yet). It is used to parse HTML Docs like beautiful soup.</p>
<p>As Nehal suggested, <a href="http://selenium-python.readthedocs.io/" rel="nofollow">selenium</a> is ... | 1 | 2016-09-04T08:04:33Z | [
"python",
"beautifulsoup",
"mechanize",
"pyquery"
] |
How to get the updates from XML file in Python? | 39,314,688 | <p>I am a newbie to Python. I have an XML file in the server which will be updated by a device with notifications periodically like below.</p>
<pre><code><notifications
xmlns="http://XXXXX">
<notification>
<received>2016-09-04T13:48:57Z</received>
<source-address>x... | -1 | 2016-09-04T07:46:22Z | 39,315,503 | <p>two separate issues â first issue is monitoring a file for changes ⦠this looks like itâs been addressed </p>
<ul>
<li><a href="http://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes-using-python">How do I watch a file for changes using Python?</a> </li>
<li><a href="http://stackoverflow.... | 0 | 2016-09-04T09:31:18Z | [
"python",
"xml",
"notifications"
] |
How to make this code a bit less memory consuming yet simple? | 39,314,695 | <p>To return a particular line from a txt file for further manipulation, also the file that must be opened by this function is quite big ~ 500 lines so creating a list and then printing a particular line seemed pretty absurd. Can you please suggest me an alternative? The code is as follows :</p>
<pre><code>def returnl... | 0 | 2016-09-04T07:48:26Z | 39,314,995 | <p>If your files are not many thousands of lines, I wouldn't worry about optimizing that bit, however, what you can do is simply keep reading the file until you've reached the line you want, and stop reading from there on; that way, when the file is, say, 5000 lines, and you want the 10th line, you'll only have to read... | 1 | 2016-09-04T08:29:39Z | [
"python",
"python-2.7",
"file-handling"
] |
Access elements of 2D list | 39,314,858 | <p>I have a list of variables in python and I would like to be able to access the index of individual values in each row and column. Because I am new to python, I do not know if there is another way to access the index or select individual values by row and column.</p>
<p>The only way I have found so far is to use the... | 0 | 2016-09-04T08:09:34Z | 39,314,915 | <p>What you want is a list of lists.</p>
<p>This is how you can make one:</p>
<pre><code>data = [[1, 2, 3, 4],
['blue', 'green', 'red', 'yellow']]
data.append(['elephant', 'donkey', 'cat'])
</code></pre>
<p>This is how you access its contents:</p>
<pre><code>data[0] # [1, 2, 3, 4]
data[0][0] # 1
data[1][2... | 0 | 2016-09-04T08:19:35Z | [
"python",
"indexing",
"data-structures"
] |
How to download using wget one by one in a loop in python | 39,314,891 | <p>I have following code written which downloads from a page:</p>
<pre><code>import urllib2,os
from bs4 import BeautifulSoup
page = urllib2.urlopen('http://somesite.com')
soup = BeautifulSoup(page)
for a in soup.find_all('a', href=True):
if "tutorials" in a['href']:
os.system('wge... | 1 | 2016-09-04T08:13:58Z | 39,314,924 | <p>Use the subprocess.call module instead of os.system.</p>
<pre><code>subprocess.call(['wget' , a['href']])
</code></pre>
| 1 | 2016-09-04T08:21:23Z | [
"python",
"loops",
"wget"
] |
Python generate and return tuples in a non-list form | 39,314,913 | <pre><code>def tuple_gen(x, y, num):
pos = []
for i in range(num):
x += 1
pos.append([x, y])
pos[i] = tuple(pos[i])
return pos
</code></pre>
<p>my input is:</p>
<pre><code>>>> tuple_gen(0,1,5)
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]
</code></pre>
<p>What I want is to ret... | 0 | 2016-09-04T08:19:20Z | 39,314,961 | <p>You are currently returning a list of tuples:</p>
<pre><code>>>> tuple_gen(0,1,5)
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]
</code></pre>
<p>You could return a tuple of tuples with <code>return tuple(pos)</code>.</p>
<p>That is what you asked for, but it won't help you for this use case:</p>
<pre><code>[... | 1 | 2016-09-04T08:25:24Z | [
"python",
"arrays",
"list",
"tuples",
"unpack"
] |
Python generate and return tuples in a non-list form | 39,314,913 | <pre><code>def tuple_gen(x, y, num):
pos = []
for i in range(num):
x += 1
pos.append([x, y])
pos[i] = tuple(pos[i])
return pos
</code></pre>
<p>my input is:</p>
<pre><code>>>> tuple_gen(0,1,5)
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]
</code></pre>
<p>What I want is to ret... | 0 | 2016-09-04T08:19:20Z | 39,314,980 | <p>You can't do that exactly as you said, But you have some options, first is chaining the result of your functions:</p>
<pre><code>>>> a = [(1, 1), (2, 1)]
>>> b = [(3, 1), (4, 1), (5, 1)]
>>>
>>> a + b
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]
>>> # Or using itertools.cha... | 1 | 2016-09-04T08:27:37Z | [
"python",
"arrays",
"list",
"tuples",
"unpack"
] |
Python generate and return tuples in a non-list form | 39,314,913 | <pre><code>def tuple_gen(x, y, num):
pos = []
for i in range(num):
x += 1
pos.append([x, y])
pos[i] = tuple(pos[i])
return pos
</code></pre>
<p>my input is:</p>
<pre><code>>>> tuple_gen(0,1,5)
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]
</code></pre>
<p>What I want is to ret... | 0 | 2016-09-04T08:19:20Z | 39,315,052 | <p>You need a container, which holds your tuples. You are thinking of list or scheme like tuples, which are linked lists. The tuples in python are expensive in creating, joining and appending. You should use lists for this purposes. You can take an list and just join it.</p>
<pre><code>tuple_gen(0,1,5) + tuple_gen(0,2... | 0 | 2016-09-04T08:38:01Z | [
"python",
"arrays",
"list",
"tuples",
"unpack"
] |
Python generate and return tuples in a non-list form | 39,314,913 | <pre><code>def tuple_gen(x, y, num):
pos = []
for i in range(num):
x += 1
pos.append([x, y])
pos[i] = tuple(pos[i])
return pos
</code></pre>
<p>my input is:</p>
<pre><code>>>> tuple_gen(0,1,5)
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]
</code></pre>
<p>What I want is to ret... | 0 | 2016-09-04T08:19:20Z | 39,315,352 | <p>You just need to change the way you're calling <code>tuple_gen</code>. Here's an example, with a slightly improved version of <code>tuple_gen</code>:</p>
<pre><code>def tuple_gen(x, y, num):
pos = []
for i in range(num):
x += 1
pos.append((x, y))
return pos
bases = (
(0, 1, 5),
... | 0 | 2016-09-04T09:14:33Z | [
"python",
"arrays",
"list",
"tuples",
"unpack"
] |
Python Error TypeError: unsupported operand type(s) for +: 'function' and 'function' | 39,314,935 | <p>I know there is some stuff online about this error but whatever I try just doesn't seem to fix it. I just started learning Python yesterday and am an absolute beginner so please don't judge my script. It is just a simple script wanting to take the order of a customer from a restaurant and just calculate the total pr... | 1 | 2016-09-04T08:22:27Z | 39,314,984 | <p>You are redifining your function names with your local variable names</p>
<p>No wonder why there is a mixup.</p>
<p>I know visual basic uses to do that for return values but you cannot do that in python.</p>
<p>Just rename your local variables (the ones assigned to result of raw_input and it will be ok</p>
| 2 | 2016-09-04T08:28:06Z | [
"python",
"typeerror"
] |
Python Error TypeError: unsupported operand type(s) for +: 'function' and 'function' | 39,314,935 | <p>I know there is some stuff online about this error but whatever I try just doesn't seem to fix it. I just started learning Python yesterday and am an absolute beginner so please don't judge my script. It is just a simple script wanting to take the order of a customer from a restaurant and just calculate the total pr... | 1 | 2016-09-04T08:22:27Z | 39,315,022 | <p>You shouldn't name functions the same as variables, i.e. the fruit function should look like this:</p>
<pre><code>def Fruit():
print("Welcome to The Buttler's Pantery")
global fruit
fruit = raw_input("what fruit would you like today?")
if (fruit == "Apple"):
Main()
elif (fruit == "Banan... | 1 | 2016-09-04T08:34:01Z | [
"python",
"typeerror"
] |
Python Error TypeError: unsupported operand type(s) for +: 'function' and 'function' | 39,314,935 | <p>I know there is some stuff online about this error but whatever I try just doesn't seem to fix it. I just started learning Python yesterday and am an absolute beginner so please don't judge my script. It is just a simple script wanting to take the order of a customer from a restaurant and just calculate the total pr... | 1 | 2016-09-04T08:22:27Z | 39,315,235 | <p>You used functions to define num1,num2... values , which becomes local variables . whereas you should have made these variables out of function . And use those variables in other functions using the keyword 'global'. </p>
<p>here's the edited code : </p>
<pre><code>Apple = 3
Banana = 4
Kiwi = 2
Peach = 5
Hamburger... | 1 | 2016-09-04T09:00:27Z | [
"python",
"typeerror"
] |
Why does my linear regression get nan values instead of learning? | 39,314,946 | <p>I'm running the following code:</p>
<pre><code>import tensorflow as tf
# data set
x_data = [10., 20., 30., 40.]
y_data = [20., 40., 60., 80.]
# try to find values for w and b that compute y_data = W * x_data + b
# range is -100 ~ 100
W = tf.Variable(tf.random_uniform([1], -1000., 1000.))
b = tf.Variable(tf.random... | 0 | 2016-09-04T08:23:58Z | 39,315,068 | <p>You are overflowing float32 because the learning rate is too high for your problem, and instead of converging the weight variable (<code>W</code>) is oscillating towards larger and larger magnitudes on each step of gradient descent.</p>
<p>If you change</p>
<pre><code>a = tf.Variable(0.1)
</code></pre>
<p>to </p>... | 0 | 2016-09-04T08:40:53Z | [
"python",
"tensorflow"
] |
Manipulation of values in Pandas via Regex | 39,315,053 | <p>This is actually a follow up question of <a href="http://stackoverflow.com/questions/39313680/pandas-dropping-of-words-in-dataframe/39313796?noredirect=1#comment65960430_39313796">here</a>. I had not been clear in my previous question, and since it has been answered, I felt it was better to post a new question inste... | 4 | 2016-09-04T08:38:02Z | 39,315,181 | <p>You could come up with:</p>
<pre><code>import re
def onlynumbers(value):
if value.startswith('('):
return '-' + value
rx = re.compile(r'\d+[\d.]*')
try:
return rx.search(value).group(0)
except:
return value
df.applymap(onlynumbers)
</code></pre>
<p>This returns:
<a href="h... | 2 | 2016-09-04T08:54:37Z | [
"python",
"regex",
"pandas",
"dataframe"
] |
Manipulation of values in Pandas via Regex | 39,315,053 | <p>This is actually a follow up question of <a href="http://stackoverflow.com/questions/39313680/pandas-dropping-of-words-in-dataframe/39313796?noredirect=1#comment65960430_39313796">here</a>. I had not been clear in my previous question, and since it has been answered, I felt it was better to post a new question inste... | 4 | 2016-09-04T08:38:02Z | 39,315,362 | <pre><code>r1 = r'\((\d+\.?\d*)\)'
r2 = r'(-?\d+\.?\d*)'
df.stack().str.replace(r1, r'-\1', 1) \
.str.extract(r2, expand=False).unstack()
</code></pre>
<p><a href="http://i.stack.imgur.com/tVR5u.png" rel="nofollow"><img src="http://i.stack.imgur.com/tVR5u.png" alt="enter image description here"></a></p>
| 4 | 2016-09-04T09:15:49Z | [
"python",
"regex",
"pandas",
"dataframe"
] |
Manipulation of values in Pandas via Regex | 39,315,053 | <p>This is actually a follow up question of <a href="http://stackoverflow.com/questions/39313680/pandas-dropping-of-words-in-dataframe/39313796?noredirect=1#comment65960430_39313796">here</a>. I had not been clear in my previous question, and since it has been answered, I felt it was better to post a new question inste... | 4 | 2016-09-04T08:38:02Z | 39,315,643 | <p><strong>UPDATE:</strong> <code>$1,005A</code> --> <code>1005</code> (example in 1st row, column <code>Column3</code>)</p>
<pre><code>In [131]: df
Out[131]:
Column1 Column2 Column3 Column4 Column5
0 5FQ 1.047 $1,005A UG44.2 as of 02/Jun/2016 S$8.2 mm
1 600 (1.047) S$23.3... | 2 | 2016-09-04T09:50:50Z | [
"python",
"regex",
"pandas",
"dataframe"
] |
How to install xgboost in python on Mac? | 39,315,156 | <p>I am a newbie and learning python. Can someone help me- how to install xgboost in python. Im using Mac 10.11. I read online and did the below mentioned step, but not able to decode what to do next: </p>
<pre><code>pip install xgboost -
</code></pre>
| 0 | 2016-09-04T08:51:46Z | 39,315,516 | <p>For a newbie learning python and Machine Learning on Mac, I would strongly recommand to install Anaconda first (<a href="https://www.continuum.io/downloads" rel="nofollow">install doc)</a>.</p>
<blockquote>
<p>Anaconda is a freemium open source distribution of the Python and R
programming languages for large-sc... | 0 | 2016-09-04T09:33:15Z | [
"python",
"xgboost"
] |
PyInstaller won't install, Python 3.6.0a4 and x64 Windows | 39,315,160 | <p>I have said Python version (from <a href="https://www.python.org/downloads/windows/" rel="nofollow">https://www.python.org/downloads/windows/</a>), and x64 Windows 10.
Every time I try to execute "pip install pyinstaller" it crashes with an error:</p>
<pre><code>C:\WINDOWS\system32>pip install pyinstaller
Collec... | 0 | 2016-09-04T08:52:12Z | 39,317,550 | <p>As cdarke pointed out, you are running python 2 code on Python 3.</p>
<p>Try this instead:</p>
<pre><code>pip3 install pyinstaller
</code></pre>
| 0 | 2016-09-04T13:43:14Z | [
"python",
"windows",
"64bit",
"pyinstaller"
] |
I can't replicate the code from book "Mastering pandas for Finance" - Zipline - KeyError: 'Cost' | 39,315,267 | <p>I'm reading the book "Mastering pandas for Finance". Up until where the Zipline module is involved all was very smooth and interesting, but now when I need to recreate the books code in the Jupyter Notebook, I'm getting and error from Zipline library.</p>
<p>The book's code is:</p>
<pre><code>import zipline as zp
... | 0 | 2016-09-04T09:04:56Z | 39,417,446 | <p>I am using Python 2.7 and Zipline 0.7.0 Since I have 32 bit OS and Zipline future releases are focused on 64 bit I cannot upgrade Zipline on my system. The code ran perfectly well on my system. Perhaps the code is compatible with older Zipline version. Are you using windows? Why is there Python3.4 between lib and si... | 0 | 2016-09-09T18:11:06Z | [
"python",
"pandas",
"algorithmic-trading",
"zipline"
] |
ImportError: No module named 'theano' | 39,315,270 | <p>I have installed (/library/python/2.7/site-packages) theano on my mac and still get this error.</p>
<p><strong>My code is</strong></p>
<pre><code>import theano
theano.test()
</code></pre>
<p><strong>and the error</strong></p>
<pre><code>Traceback (most recent call last):
File "/Users/mac/Downloads/n.py", line ... | 1 | 2016-09-04T09:05:24Z | 39,317,160 | <p>I had the same problem trying to install pygame, i'm using python 3.4.1 so I'm not 100% sure this will work for you</p>
<p>Here is my folder: C:\Python34\Scripts<a href="http://i.stack.imgur.com/xoYJZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/xoYJZ.png" alt="enter image description here"></a></p>
<p><... | 1 | 2016-09-04T12:59:35Z | [
"python",
"theano"
] |
Python Query properties of dict by value | 39,315,396 | <p>I'm trying to get the count of properties in a dict where poi == true. I've included a C# example for reference, followed by my python code. </p>
<p>What's the correct way of doing this in Python?</p>
<p>C#:</p>
<pre><code>enron_data.where(x => x.poi == true).count()
</code></pre>
<p>In Python:</p>
<pre><cod... | 1 | 2016-09-04T09:19:27Z | 39,315,441 | <p>You could use the <code>iter_items()</code> function like so:</p>
<pre><code>i = 0
for key,value in enron_data.iter_items():
if value["poi"]:
i = i + 1
print i
</code></pre>
<p>OR</p>
<pre><code>i = 0
for key,value in enron_data.iter_items():
i += int(value["poi"])
print i
</code></pre>
| 0 | 2016-09-04T09:24:03Z | [
"python"
] |
Python Query properties of dict by value | 39,315,396 | <p>I'm trying to get the count of properties in a dict where poi == true. I've included a C# example for reference, followed by my python code. </p>
<p>What's the correct way of doing this in Python?</p>
<p>C#:</p>
<pre><code>enron_data.where(x => x.poi == true).count()
</code></pre>
<p>In Python:</p>
<pre><cod... | 1 | 2016-09-04T09:19:27Z | 39,315,466 | <p>it's not right, since when never value["poi"] has a value that not false, i will increment by 1, so you should do:</p>
<pre><code>i = 0
for key,value in enron_data.iter_items():
if value["poi"] == True:
i = i + 1
print i
</code></pre>
| 0 | 2016-09-04T09:27:22Z | [
"python"
] |
Python Query properties of dict by value | 39,315,396 | <p>I'm trying to get the count of properties in a dict where poi == true. I've included a C# example for reference, followed by my python code. </p>
<p>What's the correct way of doing this in Python?</p>
<p>C#:</p>
<pre><code>enron_data.where(x => x.poi == true).count()
</code></pre>
<p>In Python:</p>
<pre><cod... | 1 | 2016-09-04T09:19:27Z | 39,315,484 | <p>Say you have a dictionary where each value indeed has a <code>poi</code> key (which your question implies):</p>
<pre><code>enron_data = {'foo': {'poi': True}, 'bar': {'poi': False}}
</code></pre>
<p>Then this will sum the number of <code>True</code> entries:</p>
<pre><code>sum(1 if e['poi'] else 0 for e in enron_... | 1 | 2016-09-04T09:29:13Z | [
"python"
] |
Python Query properties of dict by value | 39,315,396 | <p>I'm trying to get the count of properties in a dict where poi == true. I've included a C# example for reference, followed by my python code. </p>
<p>What's the correct way of doing this in Python?</p>
<p>C#:</p>
<pre><code>enron_data.where(x => x.poi == true).count()
</code></pre>
<p>In Python:</p>
<pre><cod... | 1 | 2016-09-04T09:19:27Z | 39,315,497 | <p>I'd probably do something like this assuming that the <code>poi</code> is always <code>True</code> or <code>False</code>. </p>
<pre><code>sum(int(v['poi']) for v in enron_data.values())
</code></pre>
<p><code>enron_data.values()</code> gives you an iterator that will return values of the dictionary. We're not inte... | 4 | 2016-09-04T09:30:14Z | [
"python"
] |
infinite while loop in python when integer compared with range | 39,315,460 | <p>my while code:</p>
<pre><code>i=0
a = range(100)
while i < range(100):
print i
i += 9
</code></pre>
<p>this goes into an infinite loop...may i know why?</p>
<p>is it because an integer is compared to the list?
but what happens when i becomes greater than 99?</p>
<p>shouldnt it come out... | 0 | 2016-09-04T09:26:44Z | 39,315,491 | <p>Sadly in Python 2.x, an <code>int</code> is always less than a <code>list</code> (even if that list is empty).</p>
<pre><code>>>> 9 < []
True
</code></pre>
<p>What you want to be doing is using the 3-argument form of <code>range</code> so you have a <em>start</em>, a <em>stop</em> and a <em>step</em>, ... | 7 | 2016-09-04T09:29:45Z | [
"python",
"python-2.7",
"while-loop"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.