title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Ubuntu 14.04 - Python 3.4 - pyenv: command Not Found
29,954,984
7
2015-04-29T21:31:58Z
29,955,015
12
2015-04-29T21:35:03Z
[ "python", "ubuntu" ]
I am trying to create a virtual environment for Python 3.4 on a fresh install of Ubuntu Server 14.04. I following the instructions for the venv module at: <https://docs.python.org/3/library/venv.html#module-venv> I don't have a lot of Python 3.4 or Ubuntu experience. When I type the command: ``` pyvenv testDir ``` ...
Ubuntu 14.04 uses Python 2 by default, and the `pyenv` command does not exist in Python 2 out of the box. You can, however, use `virtualenv` for the same purpose. You just need to install it! You should: * Install Python 3 and virtualenv `apt-get install -y python3 python-virtualenv` * Create a Python 3 virtualenv: ...
How can I select elements lesser than a given integer, from a sorted list?
29,957,895
4
2015-04-30T02:16:02Z
29,957,912
9
2015-04-30T02:17:50Z
[ "python", "list", "python-3.x" ]
I have array of primes e.g. between integers 0 to 1000 ``` primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,...
You can make use of the fact that `primes` is already sorted, with [`bisect`](https://docs.python.org/3/library/bisect.html#bisect.bisect), like this ``` >>> from bisect import bisect >>> primes[:bisect(primes, n)] ``` `bisect` does binary search on the input list and returns the index of the element which is lesser ...
Python: Time input validation
29,961,249
6
2015-04-30T07:11:10Z
29,961,522
7
2015-04-30T07:23:57Z
[ "python", "python-2.7", "date" ]
I have the fallowing problem, Im supposed to get user input in the form of `10:10:10` (hh:mm:ss) or `10:10`(mm:ss) or `10`(ss). Now i need check the fallowing parameters: * If I'm getting only seconds then there is no limit. * If I'm getting `mm:ss` then the seconds are limited to 0..59 and minutes are unlimited. * If...
How about using regular expression here: ``` import re import datetime pattern = re.compile(r'^(\d+)(?::([0-5]?\d)(?::([0-5]?\d))?)?$') def str2seconds(val): match = pattern.match(val) if not match: raise ValueError("Invalid input: %s" % val) else: result = 0 for i in match.groups(...
How to track anonymous users with Flask
29,961,898
3
2015-04-30T07:44:15Z
29,962,315
7
2015-04-30T08:06:01Z
[ "python", "flask", "flask-login", "anonymous-users" ]
My app implements a shopping cart in which anonymous users can fill their cart with products. User Login is required only before payment. How can this be implemented? The main challenge is that flask must keep track of the user (even if anonymous) and their orders. My current approach is to leverage the `AnonymousUser...
There is no need for a custom `AnonymousUserMixin`, you can keep the shopping cart data in session: * anonymous user adds something to hist cart -> update his session with the cart data * the user wants to check out -> redirect him to login page * logged in user is back at the check out -> take his cart data out of th...
What does this notation do for lists in Python: "someList[:]"?
29,963,686
32
2015-04-30T09:15:00Z
29,963,746
8
2015-04-30T09:18:23Z
[ "python", "list", "slice", "notation", "shallow-copy" ]
I sometimes get across this way of printing or returning a list - `someList[:]`. I don't see why people use it, as it returns the full list. Why not simply write `someList`, whithout the `[:]` part?
To **create a copy** of a list instead of passing by reference, as Python does. Use next two example to understand the difference. **Example:** ``` # Passing by reference SomeListA = [1, 2, 3] SomeListB = [2, 3, 4] SomeListB = SomeListA SomeListA[2] = 5 print SomeListB print SomeListA # Using slice SomeListA = [1, 2...
What does this notation do for lists in Python: "someList[:]"?
29,963,686
32
2015-04-30T09:15:00Z
29,963,752
52
2015-04-30T09:18:38Z
[ "python", "list", "slice", "notation", "shallow-copy" ]
I sometimes get across this way of printing or returning a list - `someList[:]`. I don't see why people use it, as it returns the full list. Why not simply write `someList`, whithout the `[:]` part?
`[:]` creates a slice, usually used to get just a part of a list. Without any minimum/maximum index given, it creates a copy of the entire list. Here's a Python session demonstrating it: ``` >>> a = [1,2,3] >>> b1 = a >>> b2 = a[:] >>> b1.append(50) >>> b2.append(51) >>> a [1, 2, 3, 50] >>> b1 [1, 2, 3, 50] >>> b2 [1,...
What does this notation do for lists in Python: "someList[:]"?
29,963,686
32
2015-04-30T09:15:00Z
29,964,001
15
2015-04-30T09:30:08Z
[ "python", "list", "slice", "notation", "shallow-copy" ]
I sometimes get across this way of printing or returning a list - `someList[:]`. I don't see why people use it, as it returns the full list. Why not simply write `someList`, whithout the `[:]` part?
In python, when you do `a = b`, a doesn't take the *value* of b, but *references* the same value referenced by b. To see this, make: ``` >>> a = {'Test': 42} >>> b = a >>> b['Test'] = 24 ``` What is now the value of a? ``` >>> a['Test'] 24 ``` It's similar with lists, so we must find a way to really *copy* a list, ...
Python -- Setting Background color to transparent in Plotly plots
29,968,152
3
2015-04-30T12:46:21Z
29,969,848
7
2015-04-30T14:01:28Z
[ "python", "plotly" ]
My python code creates a plotly Bar plot but the background is white in color i want to change it into transparent color is that doable ***My Code:*** ``` import plotly.plotly as py from plotly.graph_objs import * py.sign_in('username', 'api_key') data = Data([ Bar( x=['Sivaranjani S', 'Vijayalakshmi C', 'Rajeshw...
For a fully transparent plot, make sure to specify both the paper bgcolor and the plot's: ``` import plotly.plotly as py from plotly.graph_objs import * py.sign_in('', '') data = Data([ Bar( x=['Sivaranjani S', 'Vijayalakshmi C', 'Rajeshwari S', 'Shanthi Priscilla', 'Pandiyaraj G', 'Kamatchi S', 'MohanaPri...
Why is the en-dash written as '\xe2\x80\x93' in Python?
29,968,179
3
2015-04-30T12:47:42Z
29,968,221
10
2015-04-30T12:49:41Z
[ "python", "unicode", "utf-8" ]
Specifically, what does each escape in `\xe2\x80\x93` do and why does it need 3 escapes? Trying to decode one by itself leads to an 'unexpected end of data' error. ``` >>> print(b'\xe2\x80\x93'.decode('utf-8')) – >>> print(b'\xe2'.decode('utf-8')) Traceback (most recent call last): File "<stdin>", line 1, in <modu...
You have [UTF-8 bytes](http://en.wikipedia.org/wiki/UTF-8), which is a *codec*, a standard to represent text as computer-readable data. The [U+2013 EN-DASH codepoint](https://codepoints.net/U+2013) encodes to those 3 bytes when encoded to that codec. Trying to decode just one such byte as UTF-8 doesn't work because in...
While loop doesn't stop
29,970,679
5
2015-04-30T14:39:36Z
29,970,744
11
2015-04-30T14:42:11Z
[ "python" ]
I have this simple code in Python: ``` import sys class Crawler(object): def __init__(self, num_of_runs): self.run_number = 1 self.num_of_runs = num_of_runs def single_run(self): #do stuff pass def run(self): while self.run_number <= self.num_of_runs: self.single_run() print s...
``` num_of_runs = sys.argv[1] ``` `num_of_runs` is a string at that stage. ``` while self.run_number <= self.num_of_runs: ``` You are comparing a `string` and an `int` here. A simple way to fix this is to convert it to an int ``` num_of_runs = int(sysargv[1]) ``` Another way to deal with this is to use `argparser...
Count number of non-NaN entries in every column of Dataframe
29,971,075
13
2015-04-30T14:57:40Z
29,971,188
16
2015-04-30T15:01:44Z
[ "python", "pandas", "dataframe", null ]
I have a really big DataFrame and I was wondering if there was short (one or two liner) way to get the a count of non-NaN entries in a DataFrame. I don't want to do this one column at a time as I have close to 1000 columns. ``` df1 = pd.DataFrame([(1,2,None),(None,4,None),(5,None,7),(5,None,None)], ...
The [`count()`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.count.html) method returns the number of non-`NaN` values in each column: ``` >>> df1.count() a 3 b 2 d 1 dtype: int64 ``` Similarly, `count(axis=1)` returns the number of non-`NaN` values in each row.
Python SQLAlchemy and Postgres - How to query a JSON element
29,974,143
4
2015-04-30T17:27:11Z
29,975,187
7
2015-04-30T18:32:46Z
[ "python", "json", "postgresql", "filter", "sqlalchemy" ]
Let's say I have a Postgres database (9.3) and there is a table called Resources. In the Resources table I have the fields id which is an int and data which is a JSON type. Let's say I have the following records in said table. * 1, {'firstname':'Dave', 'lastname':'Gallant'} * 2, {'firstname':'John', 'lastname':'Doe'}...
Try using [**astext**](http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#sqlalchemy.dialects.postgresql.JSON) ``` records = db_session.query(Resource).filter( Resources.data["lastname"].astext == "Doe" ).all() ```
Why might Python's `from` form of an import statement bind a module name?
29,974,455
17
2015-04-30T17:45:30Z
29,974,921
9
2015-04-30T18:16:42Z
[ "python", "import" ]
I have a Python project with the following structure: ``` testapp/ ├── __init__.py ├── api │   ├── __init__.py │   └── utils.py └── utils.py ``` All of the modules are empty except `testapp/api/__init__.py` which has the following code: ``` from testapp import utils print "a", ...
From the [import system documentation](https://docs.python.org/3/reference/import.html#submodules): > When a submodule is loaded using any mechanism (e.g. `importlib` APIs, > the `import` or **`import-from`** statements, or built-in `__import__()`) > a binding is placed in the parent module’s namespace to the submod...
Save File to Webserver from POST Request
29,977,261
9
2015-04-30T20:31:24Z
34,116,375
10
2015-12-06T10:29:52Z
[ "javascript", "php", "python", "html", "http-post" ]
I am making a post request with some javascript to a python script in my `/var/www/cgi-bin` on my web server, and then in this python script I want to save the image file to my html folder, so it can later be retrieved. Located at `/var/www/html`, but right now the only way I know how to do this is to set the python s...
If you don't want to change the permission of that directory to `777`, you can change the owner of the directory to your HTTP server user, then the user of your web app will be able to write file into that directory because they have `rwx - 7` permission of the directory. To do that, via (since you're using Apache as ...
Why are slice objects not hashable in python
29,980,786
7
2015-05-01T02:23:17Z
29,980,846
8
2015-05-01T02:32:03Z
[ "python" ]
Why are slice objects in python not hashable: ``` >>> s = slice(0, 10) >>> hash(s) TypeError Traceback (most recent call last) <ipython-input-10-bdf9773a0874> in <module>() ----> 1 hash(s) TypeError: unhashable type ``` They seem to be immutable: ``` >>> s.start = 5 TypeError ...
From the [Python bug tracker](https://bugs.python.org/issue1733184): > Patch [# 408326](https://bugs.python.org/issue408326) was designed to make assignment to d[:] an error where > d is a dictionary. See discussion starting at > <http://mail.python.org/pipermail/python-list/2001-March/072078.html> . Slices were spec...
Converting a loop with an assignment into a comprehension
29,980,865
6
2015-05-01T02:34:56Z
29,980,952
9
2015-05-01T02:46:13Z
[ "python" ]
Converting a loop into a comprehension is simple enough: ``` mylist = [] for word in ['Hello', 'world']: mylist.append(word.split('l')[0]) ``` to ``` mylist = [word.split('l')[0] for word in ['Hello', 'world']] ``` But I'm not sure how to proceed when the loop involves assigning a value to a reference. ``` myl...
You can't directly translate that loop to a comprehension. Comprehensions, being expressions, can only contain expressions, and assignments are statements. However, that doesn't mean there are no options. First, at the cost of calling `split` twice, you can just do this: ``` mylist = [word.split('l')[0]+word.split('...
How to reverse values in a dictionary or list?
29,981,473
2
2015-05-01T04:09:13Z
29,981,488
12
2015-05-01T04:11:01Z
[ "python", "list", "dictionary" ]
I have a dictionary ``` {1:’one’,2:’two’} ``` I want to reverse it using a function and became to the following ``` {‘1:’eno’,2:’owt’ } ``` How can I do it? Similarly, if I have a list or tuple like `[15,49]`, how can I convert it to `[94,51]`?
You can use a simple dict comprehension, using the fact that `string[::-1]` reverses a string: ``` >>> d = {1: "one", 2: "two"} >>> {x: v[::-1] for x, v in d.items()} {1: 'eno', 2: 'owt'} ``` You could also define a function: ``` def reverse_values(dct): for key in dct: dct[key] = dct[key][::-1] ``` Whic...
How can i set proxy with authentication in selenium chrome web driver using python
29,983,106
4
2015-05-01T07:24:28Z
30,953,780
7
2015-06-20T12:04:32Z
[ "python", "python-2.7", "google-chrome", "selenium", "proxy" ]
I have following script to visit a web page using python selenium Chrome driver. ``` from selenium import webdriver USERNAME = 'usename' PASSWORD = 'pass' proxies = ["xxx.xxx.xxx.xxx"] proxy_tpl ='{0}:{1}' proxy = proxy_tpl.format(proxies[0],'xx') chrome_options = webdriver.ChromeOptions() chrome_options.add_argument...
Inspired by this this [solution in php](https://github.com/RobinDev/Selenium-Chrome-HTTP-Private-Proxy), i wrote a equivalent in python: ``` from selenium import webdriver from selenium.webdriver.chrome.options import Options import zipfile manifest_json = """ { "version": "1.0.0", "manifest_version": 2, ...
Python 2.7: Ints as objects
29,986,244
5
2015-05-01T11:44:21Z
29,986,373
7
2015-05-01T11:54:22Z
[ "python", "python-2.7" ]
How does an int in python avoid being an object but yet is one: If I do the following: ``` >>> dir(10) ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__',...
The Python tokenizer is greedy, it always tries to match the longest token possible at any given position; otherwise it could think that `10.e+123` is the same as `(10).e + 123`. In the case of `10.__add__(20)` it sees the following tokens: ``` >>> tokenize.tokenize(iter(['10.__add__(20)']).next) 1,0-1,3: NUMB...
Error connecting python to neo4j using py2neo
29,986,317
8
2015-05-01T11:49:45Z
29,986,433
17
2015-05-01T11:59:00Z
[ "python", "neo4j" ]
I wrote the following python code to neo4j using py2neo ``` from py2neo import Graph from py2neo import neo4j,Node,Relationship sgraph = Graph() alice = Node("person",name="alice") bob = Node("person",name="bob") alice_knows_bob = Relationship(alice,"KNOWS",bob) sgraph.create(alice_knows_bob) ``` but i got t...
If you're using Neo4j 2.2, authentication for database servers is enabled by default. You need to authenticate before performing further operations. Read [documentation](http://py2neo.org/2.0/essentials.html#authentication). ``` from py2neo import authenticate, Graph # set up authentication parameters authenticate("l...
Python Imports Convention
29,986,805
3
2015-05-01T12:24:54Z
29,986,891
7
2015-05-01T12:31:26Z
[ "python" ]
I've noticed in Python code it's usually preferred to import explicitly the parts of a module you need, eg ``` from django.core.urlresolvers import reverse from django.db import models ``` However, I've noticed that this doesn't seem to be the case for Python standard library modules, where I'd typically see, eg: ``...
The [holy style guide](https://www.python.org/dev/peps/pep-0008/#imports) is pretty loose regarding this subject: > When importing a class from a class-containing module, it's usually > okay to spell this: > > ``` > from myclass import MyClass > from foo.bar.yourclass import YourClass > ``` > > If this spelling causes...
How to execute Python code from within Visual Studio Code
29,987,840
42
2015-05-01T13:35:17Z
29,989,061
35
2015-05-01T14:45:42Z
[ "python", "vscode" ]
[Visual Studio Code](https://code.visualstudio.com/) was recently released and I liked the look of it and the features it offered, so I figured I would give it a go. I downloaded the application from the [downloads page](https://code.visualstudio.com/Download) fired it up, messed around a bit with some of the features...
You can [add a custom task](https://www.stevefenton.co.uk/Content/Blog/Date/201505/Blog/Custom-Tasks-In-Visual-Studio-Code/) to do this. Here is a basic custom task for Python. ``` { "version": "0.1.0", "command": "c:\\Python34\\python", "args": ["app.py"], "problemMatcher": { "fileLocation": [...
How to execute Python code from within Visual Studio Code
29,987,840
42
2015-05-01T13:35:17Z
34,975,137
44
2016-01-24T11:24:01Z
[ "python", "vscode" ]
[Visual Studio Code](https://code.visualstudio.com/) was recently released and I liked the look of it and the features it offered, so I figured I would give it a go. I downloaded the application from the [downloads page](https://code.visualstudio.com/Download) fired it up, messed around a bit with some of the features...
Here is how to Configure Task Runner in Visual Studio Code to run a py file. In your console press `Ctrl`+`Shift`+`P` (Windows) or `Cmd`+`Shift`+`P` (Apple) and this brings up a search box where you search for "Configure Task Runner" [![enter image description here](http://i.stack.imgur.com/IbyrC.png)](http://i.stack....
How to execute Python code from within Visual Studio Code
29,987,840
42
2015-05-01T13:35:17Z
38,995,516
8
2016-08-17T11:35:15Z
[ "python", "vscode" ]
[Visual Studio Code](https://code.visualstudio.com/) was recently released and I liked the look of it and the features it offered, so I figured I would give it a go. I downloaded the application from the [downloads page](https://code.visualstudio.com/Download) fired it up, messed around a bit with some of the features...
There is a much easier way to run Python, no any configuration needed: 1. Install the [Code Runner Extension](https://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner) 2. Open the Python code file in Text Editor, then use shortcut `Ctrl+Alt+N`, or press `F1` and then select/type `Run Code`, the co...
Python hide ticks but show tick labels
29,988,241
7
2015-05-01T13:58:01Z
29,988,431
11
2015-05-01T14:08:57Z
[ "python", "matplotlib" ]
I can remove the ticks with ``` ax.set_xticks([]) ax.set_yticks([]) ``` but this removes the labels as well. Any way I can plot the tick labels but not the ticks and the spine
You can set the tick length to 0 using `tick_params` (<http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.tick_params>): ``` fig = plt.figure() ax = fig.add_subplot(111) ax.plot([1],[1]) ax.tick_params(axis=u'both', which=u'both',length=0) plt.show() ```
Python list input error
29,989,095
4
2015-05-01T14:47:52Z
29,989,124
9
2015-05-01T14:49:18Z
[ "python", "list", "python-2.7" ]
``` grid = [] for _ in range(3): grid.append(raw_input().split()) ``` **Input:** ``` 000 000 000 ``` **Output**: `[['000'], ['000'], ['000']]`. How do I change my code to get the output? `[['0','0','0'], ['0','0','0'],['0','0','0']]`
You have: ``` "000".split() == ["000"] ``` You want: ``` list("000") == ["0", "0", "0"] ```
Python asyncio debugging example
29,996,257
8
2015-05-01T22:49:24Z
30,000,466
12
2015-05-02T09:08:50Z
[ "python", "python-asyncio" ]
I would like to enable Asyncio's un-yielded coroutine detection, but have not succeeded. This simple code implements the recommendations on: <https://docs.python.org/3/library/asyncio-dev.html#asyncio-logger> but does not actually catch the un-yielded 'dummy' coroutine. ``` import sys, os import asyncio import log...
`asyncio` performs check for `PYTHONASYNCIODEBUG` on module importing. Thus you need setup environment variable **before** very first asyncio import: ``` import sys os.environ['PYTHONASYNCIODEBUG'] = '1' import asyncio # rest of your file ```
Deleting consonants from a string in Python
29,998,052
3
2015-05-02T03:25:06Z
29,998,062
13
2015-05-02T03:26:37Z
[ "python", "string", "list", "python-3.x", "python-idle" ]
Here is my code. I'm not exactly sure if I need a counter for this to work. The answer should be `'iiii'`. ``` def eliminate_consonants(x): vowels= ['a','e','i','o','u'] vowels_found = 0 for char in x: if char == vowels: print(char) eliminate_consonants('mississippi...
## Correcting your code The line `if char == vowels:` is wrong. It has to be `if char in vowels:`. This is because you need to check if that particular character is present in the list of vowels. Apart from that you need to `print(char,end = '')` (in python3) to print the output as `iiii` all in one line. The final p...
Django Import Error: No module named apps
30,001,009
4
2015-05-02T10:10:39Z
35,322,449
7
2016-02-10T17:51:23Z
[ "python", "django", "module", "directory", "importerror" ]
I just checked out a project with git. The project structure is ``` project apps myapp settings __init__.py __init__.py manage.py ``` There are other directories and files, but I think those are the important ones. When I run the server I get ``` Traceback (most recent call last): ...
Note that in Django 1.9 there is a module called django.apps Avoiding name clashes with built-in modules is generally advised
Summing list of counters in python
30,003,466
6
2015-05-02T14:30:44Z
30,003,471
13
2015-05-02T14:31:56Z
[ "python", "python-2.7", "counter" ]
I am looking to sum a list of counters in python. For example to sum: ``` counter_list = [Counter({"a":1, "b":2}), Counter({"b":3, "c":4})] ``` to give `Counter({'b': 5, 'c': 4, 'a': 1})` I can get the following code to do the summation: ``` counter_master = Counter() for element in counter_list: counter_master...
The [`sum`](https://docs.python.org/3/library/functions.html#sum) function has the optional *start* argument which defaults to 0. Quoting the linked page: > `sum(iterable[, start])` > > Sums *start* and the items of an *iterable* from left to right and returns > the total Set *start* to (empty) `Counter` object to av...
How to use a bash variable in python
30,007,026
2
2015-05-02T20:18:53Z
30,007,057
7
2015-05-02T20:21:37Z
[ "python", "linux", "bash" ]
In bash I'm able to do this in bash`IP=$(wget -qO- ipinfo.io/ip)` This captures my public IP and stores it as the variable $IP on my Raspberry Pi. Now I want to capture this variable in python to make a led connected to GPIO 1 turn on when the `$IP` is not equal to 82.1x.xxx.xx . I'm kind of a newbie in python so I nee...
You should use [os.environ](https://docs.python.org/2/library/os.html#os.environ) dict. Try it out: ``` >>> import os >>> os.environ['IP'] ``` or ``` >>> os.environ.get('IP') ``` From doc: **os.environ** > A mapping object representing the string environment. For example, > environ['HOME'] is the pathname of your...
What is this piece of code doing, python
30,008,825
6
2015-05-03T00:00:46Z
30,008,850
11
2015-05-03T00:05:08Z
[ "python", "if-statement" ]
I am self learning python and I was doing an exercise, the solution to which was posted in [this](http://stackoverflow.com/questions/15396739/i-made-a-python-robbers-language-translating-programme-is-it-correct) thread. Could anyone translate into english what this piece of code means? When I learned if statements I ne...
It's a longer piece of code, written as a generator. Here is what it would look like, more drawn out. ``` consonants = 'bcdfghjklmnpqrstvwxz' ls = [] for l in s: if l in consonants: ls.append(l + 'o' + l) else: ls.append(l) return ''.join(ls) ``` It loops through `s` and checks if `l` is in ...
How to reorder indexed rows based on a list in Pandas data frame
30,009,948
5
2015-05-03T03:34:33Z
30,010,004
10
2015-05-03T03:43:59Z
[ "python", "pandas" ]
I have a data frame that looks like this: ``` company Amazon Apple Yahoo name A 0 130 0 C 173 0 0 Z 0 0 150 ``` It was created using this code: ``` import pandas as pd df = pd.DataFrame({'name' : ['A', 'Z','C'], 'company' : ['Apple', '...
You could set index on predefined order using `reindex` like ``` In [14]: df.reindex(["Z", "C", "A"]) Out[14]: company Amazon Apple Yahoo Z 0 0 150 C 173 0 0 A 0 130 0 ``` However, if it's alphabetical order, you could use `sort_index(ascending=False)` `...
opencv 3.0.0-dev python bindings not working properly
30,013,009
10
2015-05-03T10:56:51Z
30,013,069
31
2015-05-03T11:02:29Z
[ "python", "opencv", "binding" ]
I am on ubuntu 14.04.02, i have python, cython and numpy installed and updated. i pulled the latest sources of open cv from <http://github.com/itseez/opencv>, compiled according to the documentation... when trying to run the python source i pulled from <https://github.com/shantnu/FaceDetect/> it's giving me the followi...
the cv2.cv submodule got removed in opencv3.0, also some constants were changed. please use cv2.CASCADE\_SCALE\_IMAGE instead (do a `help(cv2)` to see the updated constants)
Problems obtaining most informative features with scikit learn?
30,017,491
15
2015-05-03T18:07:12Z
30,065,040
10
2015-05-05T23:41:41Z
[ "python", "pandas", "machine-learning", "nlp", "scikit-learn" ]
Im triying to obtain the most informative features from a [textual corpus](http://pastebin.com/3qYc9mfZ). From this well answered [question](https://stackoverflow.com/questions/26976362/how-to-get-most-informative-features-for-scikit-learn-classifier-for-different-c) I know that this task could be done as follows: ```...
To solve this specifically for linear SVM, we first have to understand the formulation of the SVM in sklearn and the differences that it has to MultinomialNB. The reason why the `most_informative_feature_for_class` works for MultinomialNB is because the output of the `coef_` is essentially the log probability of featu...
How do I add to odd index values in python?
30,018,033
3
2015-05-03T18:55:46Z
30,018,119
8
2015-05-03T19:02:50Z
[ "python", "for-loop", "indexing" ]
I have to process the list to add an amount to every odd position. For example, if I start with ``` def main(): L = [1,3,5,7,9,11] ``` and have to add 5 to each odd position, the output should be ``` L = [1,8,5,12,9,16] ``` I'm stumped as to where to begin, I am supposed to use indexing and a for loop but e...
You can splice your list. Splicing is making assignments to indexes of your original list from another source list. This "other source list" can come from a simple list comprehension that is formed from another slice. ``` >>> L = [1,3,5,7,9,11] >>> L[1::2] = [x+5 for x in L[1::2]] >>> L [1, 8, 5, 12, 9, 16] ``` --- ...
In Python is there any way to append behind?
30,018,467
2
2015-05-03T19:35:10Z
30,018,493
8
2015-05-03T19:37:37Z
[ "python", "matrix", "append", "behind" ]
I have a matrix: ``` [[1 2 3], [4 5 6], [7 8 9]] ``` and I need to create a new matrix: ``` [[7 4 1], [8 5 2], [9 6 3]] ``` I tried ``` new_matrix = [[1]] new_matrix.append(matrix[1][0]) ``` and got a new\_matrix = `[4 1]` instead of a new\_matrix = `[1 4]` If you need more clarification, please just ask.
Yes. Use `new_matrix.insert(0,matrix[1][0])`. `insert(position,value)` allows you to insert objects into specified positions in a list. In this case, since you want to insert a number at the beginning, the position is zero. Note, however, that this take O(n) time if new\_matrix has n elements. If new\_matrix has 100 ...
How can I get a list of the symbols in a sympy expression?
30,018,977
6
2015-05-03T20:23:44Z
30,019,034
7
2015-05-03T20:28:57Z
[ "python", "python-3.x", "sympy" ]
For example, if I run ``` import sympy x, y, z = sympy.symbols('x:z') f = sympy.exp(x + y) - sympy.sqrt(z) ``` is there any method of `f` that I can use to get a list or tuple of `sympy.Symbol` objects that the expression contains? I'd rather not have to parse `srepr(f)` or parse downward through `f.args`. In this c...
You can use: ``` f.free_symbols ``` which will return a set of all free symbols. Example: ``` >>> import sympy >>> x, y, z = sympy.symbols('x:z') >>> f = sympy.exp(x + y) - sympy.sqrt(z) >>> f.free_symbols set([x, z, y]) ```
How to find the first index of any of a set of characters in a string
30,020,184
12
2015-05-03T22:36:31Z
30,020,209
16
2015-05-03T22:41:00Z
[ "python", "string", "indexing" ]
I'd like to find the index of the first occurrence of any “special” character in a string, like so: ``` >>> "Hello world!".index([' ', '!']) 5 ``` …except that's not valid Python syntax. Of course, I can write a function that emulates this behavior: ``` def first_index(s, characters): i = [] for c in c...
You can use [enumerate](https://docs.python.org/2/library/functions.html#enumerate) and [next](https://docs.python.org/2/library/functions.html#next) with a [generator expression](https://docs.python.org/2/reference/expressions.html#generator-expressions), getting the first match or returning None if no character appea...
can't build matplotlib (png package issue)
30,022,983
9
2015-05-04T05:09:43Z
30,026,042
13
2015-05-04T08:47:15Z
[ "python", "linux", "matplotlib", "fedora" ]
try to build matplotlib on fedora-18, build fails with ``` ... png: no [pkg-config information for 'libpng' could not be found.] ... * The following required packages can not be built: * png ``` What should I do/check to build png package ?
Sounds like you don't have `libpng-devel` installed. This install is not handled by pip, so you'll need to install it yourself. You should be able to install it via `yum`. ``` sudo yum install libpng-devel ``` You may also need `freetype`. Maybe try `yum-builddep matplotlib`?
sklearn.cross_validation.StratifiedShuffleSplit - error: "indices are out-of-bounds"
30,023,927
9
2015-05-04T06:35:04Z
30,025,025
19
2015-05-04T07:43:29Z
[ "python", "pandas", "scikit-learn" ]
I was trying to split the sample dataset using Scikit-learn's Stratified Shuffle Split. I followed the example shown on the Scikit-learn documentation [here](http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.StratifiedShuffleSplit.html) ``` import pandas as pd import numpy as np # UCI's wine da...
You're running into the different conventions for Pandas `DataFrame` indexing versus NumPy `ndarray` indexing. The arrays `train_index` and `test_index` are collections of row indices. But `data` is a Pandas `DataFrame` object, and when you use a single index into that object, as in `data[train_index]`, Pandas is expec...
Flask: Download a csv file on clicking a button
30,024,948
5
2015-05-04T07:39:12Z
30,043,470
7
2015-05-05T02:52:37Z
[ "javascript", "python", "json", "csv", "flask" ]
I just got started with Flask/Python. What I want to achieve is that I have a download button in my HTML and it calls the following function: ``` function downloadPlotCSV() { $.ajax({ url: "/getPlotCSV", type: "post", success: function(data) { dataPlot = JSON...
Here is one way to download a CSV file with no Javascript: ``` #!/usr/bin/python from flask import Flask, Response app = Flask(__name__) @app.route("/") def hello(): return ''' <html><body> Hello. <a href="/getPlotCSV">Click me.</a> </body></html> ''' @app.route("/getPlotCSV") de...
Add Multiple Columns to Pandas Dataframe from Function
30,026,815
6
2015-05-04T09:32:39Z
30,027,273
8
2015-05-04T09:57:09Z
[ "python", "pandas" ]
I have a pandas data frame `mydf` that has two columns,and both columns are datetime datatypes: `mydate` and `mytime`. I want to add three more columns: `hour`, `weekday`, and `weeknum`. ``` def getH(t): #gives the hour return t.hour def getW(d): #gives the week number return d.isocalendar()[1] def getD(d): #...
Here's on approach to do it using one `apply` Say, `df` is like ``` In [64]: df Out[64]: mydate mytime 0 2011-01-01 2011-11-14 1 2011-01-02 2011-11-15 2 2011-01-03 2011-11-16 3 2011-01-04 2011-11-17 4 2011-01-05 2011-11-18 5 2011-01-06 2011-11-19 6 2011-01-07 2011-11-20 7 2011-01-08 2011-11-21 8 2...
Correct placement of colorbar relative to geo axes (cartopy)
30,030,328
9
2015-05-04T12:33:59Z
30,077,745
9
2015-05-06T13:08:50Z
[ "python", "matplotlib", "axes", "colorbar", "cartopy" ]
Using Cartopy, I would like to have full control of where my colorbar goes. Usually I do this by getting the current axes position as basis and then create new axes for the colorbar. This works well for standard matplotlib axes but not when using Cartopy and geo\_axes, because this will distort the axes. So, my questi...
Great question! Thanks for the code, and pictures, it makes the problem a lot easier to understand as well as making it easier to quickly iterate on possible solutions. The problem here is essentially a matplotlib one. Cartopy calls `ax.set_aspect('equal')` as this is part of the the Cartesian units of a projection's ...
does nolearn/lasagne support python 3
30,034,492
9
2015-05-04T15:58:06Z
30,177,516
7
2015-05-11T20:57:51Z
[ "python", "python-3.x", "theano" ]
I am working with Neural Net implementation in `nolearn.lasagne` as mentioned [here](http://nbviewer.ipython.org/github/ottogroup/kaggle/blob/master/Otto_Group_Competition.ipynb) However I get the following error: `ImportError: No module named 'cPickle'` I figure out that `cPickle` is `pickle` in python-3 Does ...
You seem to be using an older version of nolearn. Try the current master from Github with these commands: `pip uninstall nolearn pip install https://github.com/dnouri/nolearn/archive/master.zip#egg=nolearn` Here's the tests in master running with both Python 2.7 and 3.4: <https://travis-ci.org/dnouri/nolearn/builds/6...
What are the differences between Conda and Anaconda
30,034,840
14
2015-05-04T16:16:48Z
30,057,885
28
2015-05-05T15:59:19Z
[ "python", "anaconda", "conda" ]
I first installed *Anaconda* on my ubuntu at `~/anaconda`, when I was trying to update my anaconda, according to the [documentation](http://docs.continuum.io/anaconda/install.html) from Continuum Analytics, I should use the following commands: ``` conda update conda conda update anaconda ``` Then I realized that I di...
conda is the package manager. Anaconda is a set of about a hundred packages including conda, numpy, scipy, ipython notebook, and so on. You installed Miniconda, which is a smaller alternative to Anaconda that is just conda and its dependencies (as opposed to Anaconda, which is conda and a bunch of other packages like ...
How do I use all() built-in function?
30,035,163
2
2015-05-04T16:33:30Z
30,035,214
8
2015-05-04T16:36:05Z
[ "python", "python-2.7", "python-2.x" ]
I am attempting to use [`all()`](https://docs.python.org/2/library/functions.html#all) but it is not working for me: ``` >>> names = ["Rhonda", "Ryan", "Red Rackham", "Paul"] >>> all([name for name in names if name[0] == "R"]) True >>> ``` I am trying to check if all the names begin with `"R"`, and even though I adde...
You misunderstand how `all` works. From the [docs](https://docs.python.org/3/library/functions.html#all): > `all(iterable)` > > Return `True` if all elements of the `iterable` are true (or if the > `iterable` is empty). In your code, you are first collecting all names that start with `R` into a list and then passing ...
Sum of products of pairs in a list
30,039,334
8
2015-05-04T20:25:45Z
30,039,414
23
2015-05-04T20:30:46Z
[ "python", "numpy", "pandas", "itertools" ]
This is the problem I have. Given a list ``` xList = [9, 13, 10, 5, 3] ``` I would like to calculate for sum of each element multiplied by subsequent elements ``` sum([9*13, 9*10, 9*5 , 9*3]) + sum([13*10, 13*5, 13*3]) + sum([10*5, 10*3]) + sum ([5*3]) ``` in this case the answer is **608**. Is there a way to d...
``` x = array([9, 13, 10, 5, 3]) result = (x.sum()**2 - x.dot(x)) / 2 ``` This takes advantage of some mathematical simplifications to work in linear time and constant space, compared to other solutions that might have quadratic performance. Here's a diagram of how this works. Suppose `x = array([2, 3, 1])`. Then if ...
Sum of products of pairs in a list
30,039,334
8
2015-05-04T20:25:45Z
30,039,462
7
2015-05-04T20:33:15Z
[ "python", "numpy", "pandas", "itertools" ]
This is the problem I have. Given a list ``` xList = [9, 13, 10, 5, 3] ``` I would like to calculate for sum of each element multiplied by subsequent elements ``` sum([9*13, 9*10, 9*5 , 9*3]) + sum([13*10, 13*5, 13*3]) + sum([10*5, 10*3]) + sum ([5*3]) ``` in this case the answer is **608**. Is there a way to d...
You actually want combinations not product: ``` from itertools import combinations print(sum(a*b for a,b in combinations(xList,2))) 608 ``` Even creating a numpy array from a python list, [@user2357112](http://stackoverflow.com/a/30039414/2141635) answer wipes the floor with the rest of us. ``` In [38]: timeit sum(...
Why are nested dictionaries OK but nested sets forbidden?
30,040,864
3
2015-05-04T22:08:54Z
30,040,995
8
2015-05-04T22:19:11Z
[ "python", "dictionary", "set", "hashtable" ]
Why are nested dictionaries allowed in Python, while nested sets are disallowed? One can nest dictionaries and change the sub-dictionaries on the fly, as the following demonstrates: ``` In [1]: dict1 = {'x':{'a':1, 'b':2}, 'y':{'c':3}} In [2]: dict2 = {'x':{'a':1, 'b':2}, 'y':{'c':3}} In [3]: dict1 == dict2 Out[3]: T...
The problem is that your examples aren't alike. There is no restriction on the **values** of a dictionary, only on the **keys**. Here is a more accurate comparison: ``` >>> d = {{'a': 'b'}: 'c'} Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> d = {{'a': 'b'}: 'c'} TypeError: unhashabl...
Python self and super in multiple inheritance
30,041,679
12
2015-05-04T23:23:29Z
30,041,888
10
2015-05-04T23:43:53Z
[ "python", "inheritance", "self", "super", "method-resolution-order" ]
In Raymond Hettinger's talk "[Super considered super speak](https://www.youtube.com/watch?v=EiOglTERPEo)" at PyCon 2015 he explains the advantages of using `super` in Python in multiple inheritance context. This is one of the examples that Raymond used during his talk: ``` class DoughFactory(object): def get_dough...
Just to clarify, there are four cases, based on changing the second line in `Pizza.order_pizza` and the definition of `OrganicPizza`: 1. `super()`, `(Pizza, OrganicDoughFactory)` *(original)*: `'Making pie with pure untreated wheat dough'` 2. `self`, `(Pizza, OrganicDoughFactory)`: `'Making pie with pure untreated whe...
Python: sorting a list of tuples on alpha case-insensitive order
30,043,709
3
2015-05-05T03:21:09Z
30,043,740
8
2015-05-05T03:25:11Z
[ "python", "list", "sorting" ]
I have a list of tuples ("twoples") ``` [('aaa',2), ('BBB',7), ('ccc',0)] ``` I need to print it in that order, but ``` >>> sorted([('aaa',2), ('BBB',7), ('ccc',0)]) ``` gives ``` [('BBB', 7), ('aaa', 2), ('ccc', 0)] list.sort(key=str.tolower) ``` doesn't work (obviously), because ``` AttributeError: type objec...
You're right that this is a Python 2 thing, but the fix is pretty simple: ``` list.sort(key=lambda a: (a[0].lower(), a[1])) ``` That doesn't really seem any less clear, because the names `a` and `b` don't have any more inherent meaning than `a[0]` and `a[1]`. (If they were, say, `name` and `score` or something, that ...
Bash pipe to python
30,043,857
5
2015-05-05T03:38:01Z
30,043,896
7
2015-05-05T03:43:46Z
[ "python", "linux", "bash", "shell" ]
I need to absorb output of a bash command via pipe in real time. E.g ``` for i in $(seq 1 4); do echo $i; sleep 1; done | ./script.py ``` Where script.py has this ``` for line in sys.stdin.readlines(): print line ``` I'm expecting the sequence to be printed as it becomes available, but the python script is ...
The first problem is that [`readlines`](https://docs.python.org/2.7/library/stdtypes.html#file.readlines) reads all the lines into a list. It can't do that until all of the lines are present, which won't be until `stdin` has reached EOF. But you don't actually need a *list* of the lines, just *some iterable* of the li...
Truth value of numpy array with one falsey element seems to depend on dtype
30,043,901
21
2015-05-05T03:44:32Z
30,044,111
8
2015-05-05T04:09:02Z
[ "python", "numpy" ]
``` import numpy as np a = np.array([0]) b = np.array([None]) c = np.array(['']) d = np.array([' ']) ``` Why should we have this inconsistency: ``` >>> bool(a) False >>> bool(b) False >>> bool(c) True >>> bool(d) False ```
I'm pretty sure the answer is, as explained in [Scalars](http://docs.scipy.org/doc/numpy/reference/arrays.scalars.html), that: > Array scalars have the same attributes and methods as ndarrays. [1] This allows one to treat items of an array partly on the same footing as arrays, smoothing out rough edges that result whe...
Truth value of numpy array with one falsey element seems to depend on dtype
30,043,901
21
2015-05-05T03:44:32Z
30,830,103
7
2015-06-14T13:44:49Z
[ "python", "numpy" ]
``` import numpy as np a = np.array([0]) b = np.array([None]) c = np.array(['']) d = np.array([' ']) ``` Why should we have this inconsistency: ``` >>> bool(a) False >>> bool(b) False >>> bool(c) True >>> bool(d) False ```
For arrays with one element, the array's truth value is determined by the truth value of that element. The main point to make is that `np.array([''])` is *not* an array containing one empty Python string. This array is created to hold strings of exactly one byte each and NumPy pads strings that are too short with the ...
Elegant way to create empty pandas DataFrame with NaN of type float
30,053,329
12
2015-05-05T12:44:09Z
30,053,435
7
2015-05-05T12:48:36Z
[ "python", "numpy", "pandas", null ]
I want to create a Pandas DataFrame filled with NaNs. During my research I found [an answer](http://stackoverflow.com/questions/13784192/creating-an-empty-pandas-dataframe-then-filling-it): ``` import pandas as pd df = pd.DataFrame(index=range(0,4),columns=['A']) ``` This code results in a DataFrame filled with NaNs...
You could specify the dtype directly when constructing the DataFrame: ``` >>> df = pd.DataFrame(index=range(0,4),columns=['A'], dtype='float') >>> df.dtypes A float64 dtype: object ``` Specifying the dtype forces Pandas to try creating the DataFrame with that type, rather than trying to infer it.
Elegant way to create empty pandas DataFrame with NaN of type float
30,053,329
12
2015-05-05T12:44:09Z
30,053,507
13
2015-05-05T12:51:01Z
[ "python", "numpy", "pandas", null ]
I want to create a Pandas DataFrame filled with NaNs. During my research I found [an answer](http://stackoverflow.com/questions/13784192/creating-an-empty-pandas-dataframe-then-filling-it): ``` import pandas as pd df = pd.DataFrame(index=range(0,4),columns=['A']) ``` This code results in a DataFrame filled with NaNs...
This one-liner seems to work as well: ``` >>> df = pd.DataFrame(np.nan, index=[0,1,2,3], columns=['A']) >>> df.dtypes A float64 dtype: object ```
Complex numbers in Cython
30,054,019
35
2015-05-05T13:12:59Z
30,168,885
18
2015-05-11T13:24:05Z
[ "python", "c", "numpy", "cython", "complex-numbers" ]
What is the correct way to work with complex numbers in Cython? I would like to write a pure C loop using a numpy.ndarray of dtype np.complex128. In Cython, the associated C type is defined in `Cython/Includes/numpy/__init__.pxd` as ``` ctypedef double complex complex128_t ``` so it seems this is just a simple C dou...
The simplest way I can find to work around this issue is to simply switch the order of multiplication. If in `testcplx.pyx` I change ``` varc128 = varc128 * varf64 ``` to ``` varc128 = varf64 * varc128 ``` I change from the failing situation to described to one that works correctly. This scenario is useful as it a...
Pythonic way to merge two overlapping lists, preserving order
30,055,830
24
2015-05-05T14:29:53Z
30,056,066
15
2015-05-05T14:40:27Z
[ "python", "list", "python-3.x", "merge" ]
Alright, so I have two lists, as such: * They can and will have overlapping items, for example, `[1, 2, 3, 4, 5]`, `[4, 5, 6, 7]`. * There will *not* be additional items in the overlap, for example, this will *not* happen: `[1, 2, 3, 4, 5]`, `[3.5, 4, 5, 6, 7]` * The lists are not necessarily ordered nor unique. `[9, ...
You can try the following: ``` >>> a = [1, 3, 9, 8, 3, 4, 5] >>> b = [3, 4, 5, 7, 8] >>> matches = (i for i in xrange(len(b), 0, -1) if b[:i] == a[-i:]) >>> i = next(matches, 0) >>> a + b[i:] [1, 3, 9, 8, 3, 4, 5, 7, 8] ``` The idea is we check the first `i` elements of `b` (`b[:i]`) with the last `i` elements of `a...
Pythonic way to merge two overlapping lists, preserving order
30,055,830
24
2015-05-05T14:29:53Z
30,056,970
9
2015-05-05T15:17:07Z
[ "python", "list", "python-3.x", "merge" ]
Alright, so I have two lists, as such: * They can and will have overlapping items, for example, `[1, 2, 3, 4, 5]`, `[4, 5, 6, 7]`. * There will *not* be additional items in the overlap, for example, this will *not* happen: `[1, 2, 3, 4, 5]`, `[3.5, 4, 5, 6, 7]` * The lists are not necessarily ordered nor unique. `[9, ...
There are a couple of easy optimizations that are possible. 1. You don't need to start at master[1], since the longest overlap starts at master[-len(addition)] 2. If you add a call to `list.index` you can avoid creating sub-lists and comparing lists for each index: This approach keeps the code pretty understandable t...
RSA encryption and decryption in Python
30,056,762
2
2015-05-05T15:08:38Z
30,057,820
10
2015-05-05T15:56:05Z
[ "python", "encryption", "rsa", "pycrypto" ]
I need help using RSA encryption and decryption in Python. I am creating a private/public key pair, encrypting a message with keys and writing message to a file. Then I am reading ciphertext from file and decrypting text using key. I am having trouble with the decryption portion. As you can see in my code below, when...
In order to make it work you need to convert key from str to tuple before decryption(ast.literal\_eval function). Here is fixed code: ``` import Crypto from Crypto.PublicKey import RSA from Crypto import Random import ast random_generator = Random.new().read key = RSA.generate(1024, random_generator) #generate pub an...
python - iterate through list whose elements have variable length
30,060,671
4
2015-05-05T18:32:57Z
30,060,753
7
2015-05-05T18:38:23Z
[ "python", "list", "loops", "iterator" ]
How can I iterate through a list or tuple whose elements as lists with variable length in Python? For example I want to do ``` tup=( [1,2], [2,3,5], [4,3], [4,5,6,7] ) for a,b,c,d in tup: print a,b,c,d ``` and then have the elements of `tup` that are short to be completed with, say, `None`. I have found a workar...
To match your own output you can use [`izip_longest`](https://docs.python.org/2/library/itertools.html#itertools.izip_longest) to fill with `None`'s and transpose again to get back to the original order: ``` from itertools import izip_longest tup=( [1,2], [2,3,5], [4,3], [4,5,6,7] ) for a,b,c,d in zip(*izip_longest(*...
Python How to get every first element in 2 Dimensional List
30,062,429
2
2015-05-05T20:14:30Z
30,062,458
7
2015-05-05T20:16:05Z
[ "python", "list", "multidimensional-array", "python-2.x" ]
I have a list like this : ``` a = ((4.0, 4, 4.0), (3.0, 3, 3.6), (3.5, 6, 4.8)) ``` I want an outcome like this (**EVERY** first element in the list) : ``` 4.0, 3.0, 3.5 ``` I tried a[::1][0], but it doesn't work I'm just start learning Python weeks ago. Python version = 2.7.9
You can get the index `[0]` from each element in a list comprehension ``` >>> [i[0] for i in a] [4.0, 3.0, 3.5] ``` Also just to be pedantic, you don't have a `list` of `list`, you have a `tuple` of `tuple`.
Exponential calculation in Python
30,064,526
7
2015-05-05T22:48:00Z
30,064,564
12
2015-05-05T22:51:00Z
[ "python", "optimization", "largenumber", "exponentiation" ]
While experimenting with [Euler 99](https://projecteuler.net/problem=99), I noticed that these operations take different time: ``` >>> 632382**518061 # never finishes.. >>> 632382**518061 > 519432**525806 # finishes in few seconds True ``` I wonder what's the reason for this?
The thing is python tries to print the first result. But this number has a zillion digits and python doesn't flush the output until a newline is encountered, which is after sending all the digits to standard output. As @abarnert mentioned, what is many times worse, is converting the number to string for printing it. Th...
Python - What are the major improvement of Pandas over Numpy/Scipy
30,067,051
4
2015-05-06T03:39:14Z
30,067,640
7
2015-05-06T04:38:13Z
[ "python", "numpy", "pandas", "scipy", "data-analysis" ]
I have been using numpy/scipy for data analysis. I recently started to learn Pandas. I have gone through a few tutorials and I am trying to understand what are the major improvement of Pandas over Numpy/Scipy. It seems to me that the key idea of Pandas is to wrap up different numpy arrays in a Data Frame, with some u...
Pandas is not particularly *revolutionary* and does use the NumPy and SciPy ecosystem to accomplish it's goals along with some key Cython code. It can be seen as a simpler API to the functionality with the addition of key utilities like joins and simpler group-by capability that are particularly useful for people with ...
How to store indices in a list
30,067,470
7
2015-05-06T04:20:04Z
30,067,595
14
2015-05-06T04:32:41Z
[ "python", "python-3.x" ]
I want to find certain segments of a string and store them, however, I will need to store a large number of these strings and I was thinking that it might be more elegant to store them as indices of the master string rather than as a list of strings. I am having trouble retrieving the indices for use. For example: ```...
The colon-based slicing syntax is only valid inside the indexing operator, e.g. `x[i:j]`. Instead, you can store `slice` objects in your list, where `slice(x,y,z)` is equivalent to `x:y:z`, e.g. ``` index = [slice(0,3), slice(5,6)] print([s[i] for i in index]) ``` will print: ``` ['ABC', 'F'] ```
Escape character \t behaves differently with space
30,068,184
6
2015-05-06T05:25:00Z
30,068,215
12
2015-05-06T05:26:52Z
[ "python" ]
Why do I see output only if I put space. ``` print "I love you %s" % "\tI'm tabbled in." print "I love you %s" % " \tI'm tabbled in." ``` output ``` I love you I'm tabbled in. I love you I'm tabbled in. ```
Typically, \t (TAB) goes to the *next* [tab stop](http://en.wikipedia.org/wiki/Tab_stop) - it is *not* a synonym for "n spaces". ``` I love you XI'm tabbled in. I love you XXXXI'm tabbled in. 0---1---2---3---4--- ``` The current terminal is configured with a tab stop size of 4 which is shown on the bottom. The "X...
How to find out Chinese or Japanese Character in a String in Python?
30,069,846
11
2015-05-06T07:09:31Z
30,070,664
16
2015-05-06T07:51:14Z
[ "python", "string", "unicode", "utf-8", "character-encoding" ]
Such as: ``` str = 'sdf344asfasf天地方益3権sdfsdf' ``` Add `()` to Chinese and Japanese Characters: ``` strAfterConvert = 'sdfasfasf(天地方益)3(権)sdfsdf' ```
As a start, you can check if the character is in one of the following unicode blocks: * [Unicode Block 'CJK Unified Ideographs'](http://www.fileformat.info/info/unicode/block/cjk_unified_ideographs/index.htm) - U+4E00 to U+9FFF * [Unicode Block 'CJK Unified Ideographs Extension A'](http://www.fileformat.info/info/unic...
list() takes at most 1 argument (3 given)
30,070,358
7
2015-05-06T07:35:54Z
30,070,423
23
2015-05-06T07:39:20Z
[ "python" ]
I want to get the vector like: `v:[1.0, 2.0, 3.0]` Here is my code: ``` class VECTOR(list) : def _init_ (self,x=0.0,y=0.0,z=0.0,vec=[]) : list._init_(self,[float(x),float(y),float(z)]) if vec : for i in [0,1,2] : self[i] = vec[i] ``` But when I typed: `a = ...
The problem is that you've misspelled the name of the constructor. Replace `_init_` with `__init__`. Here's the fixed code: ``` class VECTOR(list) : def __init__ (self,x=0.0,y=0.0,z=0.0,vec=[]) : list.__init__(self,[float(x),float(y),float(z)]) if vec : for i in [0,1,2] : ...
How to get current time in python and break up into year, month, day, hour, minute?
30,071,886
24
2015-05-06T08:51:46Z
30,071,999
43
2015-05-06T08:56:35Z
[ "python", "python-2.7", "datetime", "time" ]
I would like to get the current time in Python and assign them into variables like `year`, `month`, `day`, `hour`, `minute`. How can this be done in Python 2.7?
The [`datetime`](https://docs.python.org/2/library/datetime.html#datetime.datetime.now) module is your friend: ``` import datetime now = datetime.datetime.now() print now.year, now.month, now.day, now.hour, now.minute, now.second # 2015 5 6 8 53 40 ``` You don't need separate variables, the attributes on the returned...
how to handle long path name for pep8 compliance?
30,078,851
5
2015-05-06T13:53:19Z
30,078,906
7
2015-05-06T13:55:19Z
[ "python", "pep8" ]
How would I handle long path name like below for pep8 compliance? Is 79 characters per line a must even if it becomes somewhat unreadable? ``` def setUp(self): self.patcher1 = patch('projectname.common.credential.CredentialCache.mymethodname') ```
There are multiple ways to do this: 1. Use a variable to store this ``` def setUp(self): path = 'projectname.common.credential.CredentialCache.mymethodname' self.patcher1 = patch(path) ``` 2. String concatenation: An assignment like `v = ("a" "b" "c")` gets converted into `v = "abc"`: `...
Where does cython pyximport compile?
30,079,858
3
2015-05-06T14:36:20Z
30,086,081
7
2015-05-06T19:41:13Z
[ "python", "cython" ]
My `cython` / `pyximport` code works very well on a read/write filesystem. But (for testing purposes), I need to try it on a **read only filesystem**. **How to change the cython / pyximport temporary directory** ? (where does it do the job? i.e. the on-the-fly compilation?) How to set this "working directory" to som...
From `help(pyximport.install)` > By default, compiled modules will end up in a `.pyxbld` > directory in the user's home directory. Passing a different path > as `build_dir` will override this. so pass `build_dir` as an argument when you call `pyximport.install` to make it use your read/write system.
Is divmod() faster than using the % and // operators?
30,079,879
8
2015-05-06T14:37:00Z
30,079,965
13
2015-05-06T14:40:29Z
[ "python", "performance", "division", "modulus", "divmod" ]
I remember from assembly that integer division instructions yield both the quotient and remainder. So, in python will the built-in divmod() function be better performance-wise than using the % and // operators (suppose of course one needs both the quotient and the remainder)? ``` q, r = divmod(n, d) q, r = (n // d, n ...
To measure is to know: ``` >>> import timeit >>> timeit.timeit('divmod(n, d)', 'n, d = 42, 7') 0.22105097770690918 >>> timeit.timeit('n // d, n % d', 'n, d = 42, 7') 0.14434599876403809 ``` The `divmod()` function is at a disadvantage here because you need to look up the global each time. Binding it to a local (all v...
Procfile for Heroku for Django 1.8
30,081,246
3
2015-05-06T15:31:46Z
30,082,046
7
2015-05-06T16:09:06Z
[ "python", "django", "python-2.7", "heroku" ]
In all the tutorials I found they suggested to create the `Procfile` to deploy to heroku with the following line: ``` web: gunicorn ProjectName.wsgi --log-file - ``` Since I'm using Django 1.8 and in setting.py I have this: ``` WSGI_APPLICATION = 'ProjectName.wsgi.application' ``` I thought this would work: ``` we...
Very close! What you need is: ``` web: gunicorn ProjectName.wsgi:application --log-file - ``` Note the colon, instead of a dot.
Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?
30,081,275
771
2015-05-06T15:32:43Z
30,081,318
738
2015-05-06T15:33:58Z
[ "python", "performance", "python-3.x", "range", "python-internals" ]
It is my understanding that the `range()` function, which is actually [an object type in Python 3](https://docs.python.org/3/library/stdtypes.html#typesseq-range), generates its contents on the fly, similar to a generator. This being the case, I would have expected the following line to take an inordinate amount of ti...
The Python 3 `range()` object doesn't produce numbers immediately; it is a smart sequence object that produces numbers *on demand*. All it contains is your start, stop and step values, then as you iterate over the object the next integer is calculated each iteration. The object also implements the [`object.__contains_...
Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?
30,081,275
771
2015-05-06T15:32:43Z
30,081,467
74
2015-05-06T15:41:13Z
[ "python", "performance", "python-3.x", "range", "python-internals" ]
It is my understanding that the `range()` function, which is actually [an object type in Python 3](https://docs.python.org/3/library/stdtypes.html#typesseq-range), generates its contents on the fly, similar to a generator. This being the case, I would have expected the following line to take an inordinate amount of ti...
To add to Martijn’s answer, this is the relevant part of [the source](https://hg.python.org/cpython/file/7f8cd879687b/Objects/rangeobject.c#l415) (in C, as the range object is written in native code): ``` static int range_contains(rangeobject *r, PyObject *ob) { if (PyLong_CheckExact(ob) || PyBool_Check(ob)) ...
Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?
30,081,275
771
2015-05-06T15:32:43Z
30,081,470
180
2015-05-06T15:41:18Z
[ "python", "performance", "python-3.x", "range", "python-internals" ]
It is my understanding that the `range()` function, which is actually [an object type in Python 3](https://docs.python.org/3/library/stdtypes.html#typesseq-range), generates its contents on the fly, similar to a generator. This being the case, I would have expected the following line to take an inordinate amount of ti...
Use the [source](https://github.com/python/cpython/blob/cff677abe1823900e954592035a170eb67840971/Objects/rangeobject.c#L364-L413), Luke! In CPython, `range(...).__contains__` (a method wrapper) will eventually delegate to a simple calculation which checks if the value can possibly be in the range. The reason for the s...
Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?
30,081,275
771
2015-05-06T15:32:43Z
30,081,894
319
2015-05-06T16:01:17Z
[ "python", "performance", "python-3.x", "range", "python-internals" ]
It is my understanding that the `range()` function, which is actually [an object type in Python 3](https://docs.python.org/3/library/stdtypes.html#typesseq-range), generates its contents on the fly, similar to a generator. This being the case, I would have expected the following line to take an inordinate amount of ti...
The fundamental misunderstanding here is in thinking that `range` is a generator. It's not. In fact, it's not any kind of iterator. You can tell this pretty easily: ``` >>> a = range(5) >>> print(list(a)) [0, 1, 2, 3, 4] >>> print(list(a)) [0, 1, 2, 3, 4] ``` If it were a generator, iterating it once would exhaust i...
Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?
30,081,275
771
2015-05-06T15:32:43Z
30,081,959
24
2015-05-06T16:04:37Z
[ "python", "performance", "python-3.x", "range", "python-internals" ]
It is my understanding that the `range()` function, which is actually [an object type in Python 3](https://docs.python.org/3/library/stdtypes.html#typesseq-range), generates its contents on the fly, similar to a generator. This being the case, I would have expected the following line to take an inordinate amount of ti...
The other answers explained it well already, but I'd like to offer another experiment illustrating the nature of range objects: ``` >>> r = range(5) >>> for i in r: print(i, 2 in r, list(r)) 0 True [0, 1, 2, 3, 4] 1 True [0, 1, 2, 3, 4] 2 True [0, 1, 2, 3, 4] 3 True [0, 1, 2, 3, 4] 4 True [0, 1, 2, 3, 4] ``` ...
Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?
30,081,275
771
2015-05-06T15:32:43Z
30,088,140
52
2015-05-06T21:42:53Z
[ "python", "performance", "python-3.x", "range", "python-internals" ]
It is my understanding that the `range()` function, which is actually [an object type in Python 3](https://docs.python.org/3/library/stdtypes.html#typesseq-range), generates its contents on the fly, similar to a generator. This being the case, I would have expected the following line to take an inordinate amount of ti...
If you're wondering *why* this optimization was added to `range.__contains__`, and why it *wasn't* added to `xrange.__contains__` in 2.7: First, as Ashwini Chaudhary discovered, [issue 1766304](http://bugs.python.org/issue1766304) was opened explicitly to optimize `[x]range.__contains__`. A patch for this was [accepte...
how to locate the center of a bright spot in an image?
30,081,725
4
2015-05-06T15:52:59Z
30,085,210
7
2015-05-06T18:51:20Z
[ "python", "image", "matlab", "search", "image-processing" ]
Here is an example of the kinds of images I'll be dealing with: ![Balls](http://pages.cs.wisc.edu/~csverma/CS766_09/Stereo/callight.jpg) There is one bright spot on each ball. I want to locate the coordinates of the centre of the bright spot. How can I do it in Python or Matlab? The problem I'm having right now is th...
You can simply threshold the image and find the average coordinates of what is remaining. This handles the case when there are multiple values that have the same intensity. When you threshold the image, there will obviously be more than one bright white pixel, so if you want to bring it all together, find the centroid ...
How to join list in Python but make the last separator different?
30,083,949
19
2015-05-06T17:43:11Z
30,084,022
11
2015-05-06T17:46:55Z
[ "python" ]
I'm trying to turn a list into separated strings joined with an ampersand if there are only two items, or commas and an ampersand between the last two e.g. ``` Jones & Ben Jim, Jack & James ``` I currently have this: ``` pa = ' & '.join(listauthors[search]) ``` and don't know how to make sort out the comma/ampersan...
``` "&".join([",".join(my_list[:-1]),my_list[-1]]) ``` I would think would work or maybe just ``` ",".join(my_list[:-1]) +"&"+my_list[-1] ``` to handle edge cases where only 2 items you could ``` "&".join([",".join(my_list[:-1]),my_list[-1]] if len(my_list) > 2 else my_list) ```
How to join list in Python but make the last separator different?
30,083,949
19
2015-05-06T17:43:11Z
30,084,025
11
2015-05-06T17:47:02Z
[ "python" ]
I'm trying to turn a list into separated strings joined with an ampersand if there are only two items, or commas and an ampersand between the last two e.g. ``` Jones & Ben Jim, Jack & James ``` I currently have this: ``` pa = ' & '.join(listauthors[search]) ``` and don't know how to make sort out the comma/ampersan...
You could break this up into two joins. Join all but the last item with `", "`. Then join this string and the last item with `" & "`. ``` all_but_last = ', '.join(authors[:-1]) last = authors[-1] ' & '.join([all_but_last, last]) ``` Note: This doesn't deal with edge cases, such as when `authors` is empty or has only...
Python convert list of multiple words to single words
30,085,694
3
2015-05-06T19:17:58Z
30,085,746
10
2015-05-06T19:21:14Z
[ "python", "nlp", "nltk" ]
I have a list of words for example: `words = ['one','two','three four','five','six seven']` # quote was missing And I am trying to create a new list where each item in the list is just one word so I would have: `words = ['one','two','three','four','five','six','seven']` Would the best thing to do be join the entire...
``` words = ['one','two','three four','five','six seven'] ``` With a loop: ``` words_result = [] for item in words: for word in item.split(): words_result.append(word) ``` or as a comprehension: ``` words = [word for item in words for word in item.split()] ```
Python convert list of multiple words to single words
30,085,694
3
2015-05-06T19:17:58Z
30,085,757
8
2015-05-06T19:21:50Z
[ "python", "nlp", "nltk" ]
I have a list of words for example: `words = ['one','two','three four','five','six seven']` # quote was missing And I am trying to create a new list where each item in the list is just one word so I would have: `words = ['one','two','three','four','five','six','seven']` Would the best thing to do be join the entire...
You can join using a space separator and then split again: ``` In [22]: words = ['one','two','three four','five','six seven'] ' '.join(words).split() Out[22]: ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] ```
What is the different between assignment and parameter passing?
30,086,020
2
2015-05-06T19:38:20Z
30,086,070
9
2015-05-06T19:40:36Z
[ "python", "variable-assignment" ]
I can assign a sequence like this in python: ``` a,b,c="ABC" ``` But I am unable to pass this sequence to a function as a parameter. i.e ``` def function2(a,b,c): print a print b print c function2("ABC") ``` The above statement is raising an error. Can any one tell me the difference between assignment ...
The compiler sees a comma-separated list on the LHS and emits bytecode to iterate over the RHS for you. With the function call it sees a single value and so sends it as a single argument. You need to tell it to split the sequence explicitly: ``` >>> function2(*"ABC") A B C ```
Why is my (newbie) code so slow?
30,086,851
9
2015-05-06T20:25:31Z
30,087,482
8
2015-05-06T21:04:02Z
[ "python", "performance", "profiler" ]
I'm learning python and came across [this example](https://www.binpress.com/tutorial/introduction-to-agentbased-models-an-implementation-of-schelling-model-in-python/144) of a simulation of a model I've seen before. One of the functions looked unnecessarily long, so I thought it would be good practice to try to make it...
Don't use `np.add`, just use `neighbor = (x+xo, y+yo)`. That should make it much faster (10x faster in my little test). You can also... * ask `if neighbor in self.agents:` without the `.keys()` * leave out the `list` * check `xo or yo` and not have an empty if-block * avoid the double-lookup of neighbor in self-agent...
Can't figure out how to fix the error in the following code
30,088,006
9
2015-05-06T21:34:39Z
31,458,385
12
2015-07-16T15:23:43Z
[ "python", "json", "python-2.7", "pandas" ]
I am trying to read in a json file into pandas data frame. Here is the first line line of the json file: ``` {"votes": {"funny": 0, "useful": 0, "cool": 0}, "user_id": "P_Mk0ygOilLJo4_WEvabAA", "review_id": "OeT5kgUOe3vcN7H6ImVmZQ", "stars": 3, "date": "2005-08-26", "text": "This is a pretty typical cafe. The sandwic...
You have to read it line by line. For example, you can use the following code provided by [ryptophan](http://www.reddit.com/user/ryptophan) on [reddit](http://www.reddit.com/r/MachineLearning/comments/33eglq/python_help_jsoncsv_pandas/): ``` import pandas as pd # read the entire file into a python array with open('yo...
Mortgage calculator math error
30,090,173
2
2015-05-07T01:00:52Z
30,090,308
7
2015-05-07T01:16:28Z
[ "python", "math", "calculator" ]
This program *runs* fine, but the monthly payment it returns is totally off. For a principal amount of $400,000, interest rate of 11%, and a 10-year payment period, it returns the monthly payment of $44000.16. I googled the equation (algorithm?) for mortgage payments and put it in, not sure where I'm going wrong. ``` ...
The problem is in your interest rate used. You request the annual interest rate and never convert to a monthly interest rate. From <https://en.wikipedia.org/wiki/Mortgage_calculator#Monthly_payment_formula>: > r - the **monthly** interest rate, expressed as a decimal, not a > percentage. Since the quoted yearly perce...
about close a file in Python
30,092,249
6
2015-05-07T04:55:51Z
30,092,299
18
2015-05-07T05:00:19Z
[ "python", "file" ]
I know it is a good habit of using close to close a file if not used any more in Python. I have tried to open a large number of open files, and not close them (in the same Python process), but not see any exceptions or errors. I have tried both Mac and Linux. So, just wondering if Python is smart enough to manage file ...
Python **will**, in general, *garbage collect* objects no longer in use and no longer being referenced. This means it's entirely possible that open file objects, that match the garbage collector's filters, will get cleaned up and probably closed. **However**; you should not rely on this, and instead use: ``` with open...
cost of len() and pep8 suggestion on sequence empty check
30,100,096
2
2015-05-07T11:43:48Z
30,100,188
7
2015-05-07T11:48:00Z
[ "python", "pep8" ]
If the complexity of python `len()` is O(1), why does pep8 suggest to use `if seq:` instead of `if len(seq) == 0:` > <https://wiki.python.org/moin/TimeComplexity> > <https://www.python.org/dev/peps/pep-0008/#programming-recommendations> Isn't `len(seq) == 0` more readable?
The former can handle both empty string and `None`. For example consider these two variables. ``` >>> s1 = '' >>> s2 = None ``` Using the first method ``` def test(s): if s: return True else: return False >>> test(s1) False >>> test(s2) False ``` Now using `len` ``` def test(s): if len...
Format seconds as float
30,100,474
3
2015-05-07T12:00:56Z
30,100,634
8
2015-05-07T12:07:58Z
[ "python" ]
I wish to output: ``` "14:48:06.743174" ``` This is the closest I can get: ``` `"14:48:06"` ``` with: ``` t = time.time() time.strftime("%H:%M:%S",time.gmtime(t)) ```
According to the [manual on `time`](https://docs.python.org/3.2/library/time.html#time.strftime) there is no straight forward way to print microseconds (or seconds as float): ``` >>> time.strftime("%H:%M:%S.%f",time.gmtime(t)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Invalid...
Why are some float < integer comparisons four times slower than others?
30,100,725
264
2015-05-07T12:11:08Z
30,100,743
334
2015-05-07T12:11:39Z
[ "python", "performance", "floating-point", "cpython", "python-internals" ]
When comparing floats to integers, some pairs of values take much longer to be evaluated than other values of a similar magnitude. For example: ``` >>> import timeit >>> timeit.timeit("562949953420000.7 < 562949953421000") # run 1 million times 0.5387085462592742 ``` But if the float or integer is made smaller or la...
A comment in the Python source code for float objects acknowledges that: > [Comparison is pretty much a nightmare](https://hg.python.org/cpython/file/ea33b61cac74/Objects/floatobject.c#l285) This is especially true when comparing a float to an integer, because, unlike floats, integers in Python can be arbitrarily lar...
Pandas: can not write to excel file
30,102,232
10
2015-05-07T13:17:03Z
30,304,735
7
2015-05-18T13:38:23Z
[ "python", "pandas" ]
Trying this example from the [documentation](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.to_excel.html) ``` writer = ExcelWriter('output.xlsx') df1.to_excel(writer,'Sheet1') df2.to_excel(writer,'Sheet2') writer.save() ``` I found out that I can not write to an excel file with the error ``` Ty...
For fast solution replace this ``` xcell.style = xcell.style.copy(**style_kwargs) ``` with ``` pass ``` At pandas/io/excel.py line 778. openpyxl upgraded their api and pandas also need to be updated for support openpyxl.
Pandas: can not write to excel file
30,102,232
10
2015-05-07T13:17:03Z
30,378,303
11
2015-05-21T15:37:04Z
[ "python", "pandas" ]
Trying this example from the [documentation](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.to_excel.html) ``` writer = ExcelWriter('output.xlsx') df1.to_excel(writer,'Sheet1') df2.to_excel(writer,'Sheet2') writer.save() ``` I found out that I can not write to an excel file with the error ``` Ty...
As per their [documentation](http://pandas.pydata.org/pandas-docs/stable/install.html), pandas depends > on openpyxl version 1.6.1 or higher, but lower than 2.0.0 The last [openpyxl](https://openpyxl.readthedocs.org/en/latest/) version lower than 2.0.0 being version 1.8.6, you should simply remove your current openpy...
Pandas: can not write to excel file
30,102,232
10
2015-05-07T13:17:03Z
32,107,505
7
2015-08-19T23:56:53Z
[ "python", "pandas" ]
Trying this example from the [documentation](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.to_excel.html) ``` writer = ExcelWriter('output.xlsx') df1.to_excel(writer,'Sheet1') df2.to_excel(writer,'Sheet2') writer.save() ``` I found out that I can not write to an excel file with the error ``` Ty...
If you don't care whether the headers have borders around them and bold font, and you don't want to restrict the version of openpyxl, the quickest way is to overwrite the `header_style` dictionary to be `None`. If you also have dates or datetimes, you must also explicitly set the workbook's `date` and `datetime` forma...
How to get Best Estimator on GridSearchCV (Random Forest Classifier Scikit)
30,102,973
9
2015-05-07T13:45:10Z
30,105,413
15
2015-05-07T15:24:28Z
[ "python", "scikit-learn", "random-forest", "cross-validation" ]
I'm running GridSearch CV to optimize the parameters of a classifier in scikit. Once I'm done, I'd like to know which parameters were chosen as the best. Whenever I do so I get a `AttributeError: 'RandomForestClassifier' object has no attribute 'best_estimator_'`, and can't tell why, as it seems to be a legitimate att...
You have to fit your data before you can get the best parameter combination. ``` from sklearn.grid_search import GridSearchCV from sklearn.datasets import make_classification from sklearn.ensemble import RandomForestClassifier # Build a classification task using 3 informative features X, y = make_classification(n_samp...
Go - constructing struct/json on the fly
30,105,798
2
2015-05-07T15:41:31Z
30,106,057
9
2015-05-07T15:54:08Z
[ "python", "json", "go", "syntactic-sugar" ]
In Python it is possible to create a dictionary and serialize it as a JSON object like this: ``` example = { "key1" : 123, "key2" : "value2" } js = json.dumps(example) ``` Go is statically typed, so we have to declare the object schema first: ``` type Example struct { Key1 int Key2 string } example := &Exam...
You can use a map: ``` example := map[string]interface{}{ "Key1": 123, "Key2": "value2" } js, _ := json.Marshal(example) ``` You can also create types inside of a function: ``` func f() { type Example struct { } } ``` Or create unnamed types: ``` func f() { json.Marshal(struct { Key1 int; Key2 string }{123...
Looking for idiomatic way to evaluate to False if argument is False in Python 3
30,107,570
14
2015-05-07T17:08:03Z
30,107,704
9
2015-05-07T17:15:13Z
[ "python", "python-3.x" ]
I have a chain of functions, all defined elsewhere in the class: ``` fus(roh(dah(inp))) ``` where `inp` is either a dictionary, or `bool(False)`. The desired result is that if `inp`, or any of the functions evaluate to `False`, `False` is returned by the function stack. I attempted to use ternary operators, but the...
Decorator should look like: ``` def validate_inp(fun): def wrapper(inp): return fun(inp) if inp else False return wrapper @validate_inp def func(inp): return int(inp['value']) + 1 print(func(False)) print(func({'value': 1})) ``` If you want to use your decorator with a class member: ``` def va...
Looking for idiomatic way to evaluate to False if argument is False in Python 3
30,107,570
14
2015-05-07T17:08:03Z
30,109,995
8
2015-05-07T19:27:41Z
[ "python", "python-3.x" ]
I have a chain of functions, all defined elsewhere in the class: ``` fus(roh(dah(inp))) ``` where `inp` is either a dictionary, or `bool(False)`. The desired result is that if `inp`, or any of the functions evaluate to `False`, `False` is returned by the function stack. I attempted to use ternary operators, but the...
> I attempted to use ternary operators, but they don't evaluate correctly. > > ``` > def func(inp): > return int(inp['value']) + 1 if inp else False > ``` > > throws a TypeError, bool not subscriptable, if `i == False` because `inp['value']` is evaluated before the conditional. This is not true - that code works. ...