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
python close file automatically like context manager
38,051,862
<p>How to close this file or does the file automatically gets closed like a context manager <code>with</code></p> <pre><code>lines = open(file_name).readlines() </code></pre> <p>I wanted to avoid the <code>with</code> statement as the above statement is a one liner, but now i see that the above said statement is of n...
0
2016-06-27T10:41:25Z
38,053,601
<pre><code>lines = (lambda f=open(file_name): [f.readlines(), f.close()][0])() </code></pre> <p>However this would not be considered very Pythonic because it's not very readable.</p>
1
2016-06-27T12:08:47Z
[ "python" ]
How to get differents colors in a single line in a Matplotlib figure?
38,051,922
<p>I am using matplotlib to create the plots. I have to draw a line in a chart which color must be defined in function of each point. For example, I need a line where the points under 2000 are painted red, and points above 2000 are painted blue. How can I get this ? Do you know a similar solution or workaround to achie...
2
2016-06-27T10:44:10Z
38,052,905
<p>You have to color every segment of your line:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from matplotlib.colors import ListedColormap, BoundaryNorm # my func x = np.linspace(0, 2 * np.pi, 100) y = 3000 * np.sin(x) # select how to color cmap ...
1
2016-06-27T11:34:16Z
[ "python", "matplotlib" ]
How remove escaped sequences (e.g. \"escaped string\") using regex?
38,051,973
<p>I am trying to remove quoted sequences from a string. For the example below my script works fairly:</p> <pre><code>import re doc = ' Doc = "This is a quoted string: this is cool!" ' cleanr = re.compile('\".*?\"') doc = re.sub(cleanr, '', doc) print doc </code></pre> <p>Result (as expected):</p> <pre><code>' Doc =...
1
2016-06-27T10:46:18Z
38,052,239
<p><code>doc</code> doesn't contain any escaped characters, so your regex doesn't match.</p> <p>Add the <a href="http://stackoverflow.com/questions/2081640/what-exactly-do-u-and-r-string-flags-do-in-python-and-what-are-raw-string-l"><code>r</code></a> prefix to the string, which means that it should be treated as a <e...
2
2016-06-27T11:00:30Z
[ "python", "regex", "string", "match" ]
find common elements in N files
38,052,039
<p>I have many .txt files (N) that contain the names of several genes in the first column. The names are sorted and no redundant in the single files. I'm looking for a script that lists the names of the genes that are common in all the N files and write them in a new txt file. Or ,if is possible, an output with the com...
-2
2016-06-27T10:49:56Z
38,059,941
<pre><code>cut -f1 file_whatever &gt; b for f in file*; do cut -f1 f &gt; a comm -12 a b &gt; c; mv c b done cat b </code></pre> <p>unfit question. only answering because you are looking for genes</p>
0
2016-06-27T17:34:01Z
[ "python", "awk" ]
converting hexadecimal escape chars to binary
38,052,235
<p>I'm looking for a way to uniformly convert JavaScript chars to binary. One problem that I'm facing is that I'm not able to convert strings used in unescape function correctly </p> <pre><code>document.write("HI"); ==&gt; HI (case 1) document.write("\x48\x49"); ==&gt; HI (case 2) document.write(unescape("%48%49")); ...
-1
2016-06-27T11:00:16Z
38,052,668
<p>The <code>decodeURIComponent</code> is the right function for this. The <code>decode</code> function is deprecated. Here is an example.</p> <p>If you put <code>%48%49</code> in the input and click on the 'Convert' button, it gives you the second case.</p> <p><div class="snippet" data-lang="js" data-hide="false" da...
0
2016-06-27T11:23:11Z
[ "javascript", "java", "python" ]
Error importing nuke module in a python script and opening file
38,052,247
<p>I am getting these errors and completely lost on what I am missing, if anything, to be installed or appended to my sys.path. Does anyone know if this is a package that just needs to be installed that it is looking for? I tried scouring the Python directory for PyOpenColorIO, but couldn't find it.</p> <pre><code>i...
0
2016-06-27T11:00:53Z
38,525,716
<p><code>PyOpenColorIO</code> definitely ships with Nuke. I believe your issue is by the <code>nuke</code> module not currently being able to locate all of Nuke's library dependencies properly. Many of the modules are stored in non-standard locations compared to a traditional Python installation (for example, the <code...
0
2016-07-22T11:49:01Z
[ "python", "import", "nuke" ]
Odoo 8 Wizard Error: "For this kind of document, you may only access records you created yourself."
38,052,515
<p>I made a model A with lots of fields. It has a Many2one relationship with a minimal model B. B has only one <code>name = fields.Char(...)</code> field. </p> <p>Now I have a transient model C which is a wizard where its fields correspond to the fields of model A. So that when the user inputs some data on the wizard ...
1
2016-06-27T11:14:33Z
38,054,058
<p>Just add <code>s</code> to <code>char</code>, change <code>name = field.Char</code> by <code>name = fields.Char</code></p> <p>and restart a service.</p>
0
2016-06-27T12:30:08Z
[ "python", "openerp", "odoo-8", "wizard" ]
Odoo 8 Wizard Error: "For this kind of document, you may only access records you created yourself."
38,052,515
<p>I made a model A with lots of fields. It has a Many2one relationship with a minimal model B. B has only one <code>name = fields.Char(...)</code> field. </p> <p>Now I have a transient model C which is a wizard where its fields correspond to the fields of model A. So that when the user inputs some data on the wizard ...
1
2016-06-27T11:14:33Z
39,178,630
<p>It mean you have problem(write or unlink) in model osv.osv_memory or models.Transient..</p> <p>osv_memory or transient will save in temporary memory. if user use a wizard.</p> <p>For example table_transient_x you have data<br> id, create_uid, name, age<br> 499, 5, 'Batman', 29<br> 500, 6, 'Bahrudin', 20<br> 501, 5...
0
2016-08-27T07:31:09Z
[ "python", "openerp", "odoo-8", "wizard" ]
Scrapy 1.1.0 - no active project
38,052,549
<p>I am newbie in Python, installed Scrapy successfully, using PyDev in eclipse. When I run the programm it is showing like this (Figure illustrates)</p> <p>[<img src="http://i.stack.imgur.com/vzM9A.png" alt="error screenshot">]</p> <p>I am running this code : </p> <pre><code>import scrapy class DmozSpider(scrapy.S...
0
2016-06-27T11:16:02Z
38,053,642
<p>Your current directory is not a Scrapy project.</p> <p>A scrapy project has a defined format and files. Have a look at: <a href="http://doc.scrapy.org/en/latest/intro/tutorial.html" rel="nofollow">http://doc.scrapy.org/en/latest/intro/tutorial.html</a></p> <p>You really should go though the tutorial once.</p> <p>...
1
2016-06-27T12:10:18Z
[ "python", "python-2.7", "pydev" ]
Python - Most efficient means of testing if a list of time intervals contains clashes?
38,052,577
<p>I have a list of time intervals, something like this:</p> <pre><code>[ [1,2], [2,3], [4,5], [1,2], [1,1.5], [1.5,2.5] ] </code></pre> <p>I want to be able to test if the list contains any clashes.</p> <p>For my purposes, I do not consider it to be a clash if one event ends at the exact same time as another starts...
-2
2016-06-27T11:17:38Z
38,053,205
<p>Try this</p> <pre><code>def clash(a,b): if a == True or b == True: return True if b[0] &gt;= a[0] and a[-1] &gt;b[0]: return True return b def test_clashes(intervals): intervals = sorted(intervals) if not reduce(clash,intervals) == True: return False else: r...
0
2016-06-27T11:49:29Z
[ "python", "python-2.7", "python-3.x" ]
Python - Most efficient means of testing if a list of time intervals contains clashes?
38,052,577
<p>I have a list of time intervals, something like this:</p> <pre><code>[ [1,2], [2,3], [4,5], [1,2], [1,1.5], [1.5,2.5] ] </code></pre> <p>I want to be able to test if the list contains any clashes.</p> <p>For my purposes, I do not consider it to be a clash if one event ends at the exact same time as another starts...
-2
2016-06-27T11:17:38Z
38,053,219
<p>try:</p> <pre><code>mylist = [ [1,2], [2,3], [4,5], [1,2], [1,1.5], [1.5,2.5] ] last = 0 for i in mylist: if last&gt;i[0]: print('Clashed!!',first,last," and ",i[0],i[1]) first = i[0] last = i[1] </code></pre> <p>this will check everything and print the places where the two ove...
0
2016-06-27T11:50:13Z
[ "python", "python-2.7", "python-3.x" ]
Python - Most efficient means of testing if a list of time intervals contains clashes?
38,052,577
<p>I have a list of time intervals, something like this:</p> <pre><code>[ [1,2], [2,3], [4,5], [1,2], [1,1.5], [1.5,2.5] ] </code></pre> <p>I want to be able to test if the list contains any clashes.</p> <p>For my purposes, I do not consider it to be a clash if one event ends at the exact same time as another starts...
-2
2016-06-27T11:17:38Z
38,053,698
<p>EDIT Modified: to handle all possible combinations rather than just adjacent entries. </p> <p>First I sort the list. </p> <p>Then I compare the first element with all remaining elements to the right in the list.<br> Then I compare the second element with all the remaining elements to the right in the list.<br> A...
0
2016-06-27T12:13:17Z
[ "python", "python-2.7", "python-3.x" ]
Python - Most efficient means of testing if a list of time intervals contains clashes?
38,052,577
<p>I have a list of time intervals, something like this:</p> <pre><code>[ [1,2], [2,3], [4,5], [1,2], [1,1.5], [1.5,2.5] ] </code></pre> <p>I want to be able to test if the list contains any clashes.</p> <p>For my purposes, I do not consider it to be a clash if one event ends at the exact same time as another starts...
-2
2016-06-27T11:17:38Z
38,053,710
<p>You're looking for overlapping ranges, but accept that start of a range may be equal to the end of the other:</p> <pre><code>def overlap(x, y): x_start, x_end = x y_start, y_end = y # return not (x_end &lt;= y_start or y_end &lt;= x_start) return x_end &gt; y_start and y_end &gt; x_start </code></pr...
1
2016-06-27T12:13:51Z
[ "python", "python-2.7", "python-3.x" ]
Installing aspell for python 3 on MacOS X
38,052,604
<p>I am trying to install aspell for Python 3 (on MacOS X 10.11), and have encountered an issue (the same one) using both pip and the manual installer (by cloning the git repo). I have already installed aspell using MacPorts (sudo port install aspell) as well as the english dictionary (sudo port install aspell-dict-en)...
0
2016-06-27T11:19:10Z
38,169,404
<p>Asked the same question on the project's GitHub page. Original can be found <a href="https://github.com/WojciechMula/aspell-python/issues/11" rel="nofollow">here</a>. Copied here for convenience. </p> <p>In case anybody encounters the same issue, I had installed aspell using MacPorts (sudo port install aspell) and ...
0
2016-07-03T11:16:26Z
[ "python", "osx", "aspell" ]
How to use data as array instead of namedtuple
38,052,687
<p>For a preorder traversal on the below hierarchy</p> <pre><code> 1 / \ / \ / \ 2 3 / \ / 4 5 6 / / \ 7 8 9 </code></pre> <p>The correct output should look like this:</p> <pre><code>preorder: 1 2 4 7 5 3 6 8 9 </code></pre> <p>I have ...
-3
2016-06-27T11:24:01Z
38,052,747
<p>You can do something like this, Store the left , right of an element at index i at 2i+1, 2i+2 in an array where i is 0 for root and in case of Null, store -1 or INF. </p> <p>Now for the traversal you can traverse to left and right in the same way. But now the left is at 2i+1 and the right is at 2i+2. </p> <p>So, ...
0
2016-06-27T11:26:39Z
[ "python" ]
python-selenium and ChromeDriver: Can't open tab to control it
38,052,783
<p>I'm unable to open a new tab - or even click on a link and open it on a new tab - with Python 2.7.1, Selenium 2.53.0, ChromeDriver 2.22 and Google Chrome 51.0 on Mac OS X.</p> <pre><code> import selenium.webdriver as webdriver import selenium.webdriver.support.ui as ui from selenium.webdriver.common.keys import K...
1
2016-06-27T11:28:34Z
38,053,097
<p>You can try to click on the link while holding the <code>ctrl</code> key, this will open the link in new tab</p> <pre><code>actions = ActionChains(driver) actions.key_down(Keys.CONTROL).perform() driver.find_element_by_id('signin-email').click() actions.key_up(Keys.CONTROL).perform() </code></pre>
0
2016-06-27T11:43:49Z
[ "python", "selenium" ]
python-selenium and ChromeDriver: Can't open tab to control it
38,052,783
<p>I'm unable to open a new tab - or even click on a link and open it on a new tab - with Python 2.7.1, Selenium 2.53.0, ChromeDriver 2.22 and Google Chrome 51.0 on Mac OS X.</p> <pre><code> import selenium.webdriver as webdriver import selenium.webdriver.support.ui as ui from selenium.webdriver.common.keys import K...
1
2016-06-27T11:28:34Z
38,053,234
<p>You should try as below :-</p> <pre><code>driver.find_element_by_id('signin-email').send_keys(Keys.COMMAND + Keys.RETURN); </code></pre> <p>Hope it will help you..:)</p>
1
2016-06-27T11:50:41Z
[ "python", "selenium" ]
pandas Timestamp components - some are properties and some are methods?
38,052,815
<p>I've been playing around with the pandas Time/Date components described in the docs, and I've noticed that of the Time/Date components listed <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#time-date-components" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/timeseries.html#time-date...
1
2016-06-27T11:30:21Z
38,053,376
<p>If I refer your example, Then:</p> <pre><code>pd.Timestamp </code></pre> <p>is the property. Any direct pandas operation is a pandas property.</p> <p>Below are some possibilities:</p> <pre><code>In [4]: pd. Display all 158 possibilities? (y or n) pd.Categorical pd.SparseTimeSeries pd.ewmvol ...
1
2016-06-27T11:58:13Z
[ "python", "datetime", "pandas" ]
Not able to install crytography package in python
38,052,882
<p>I tried to search a lot before asking it here, but unfortunately couldn't find anything helping.</p> <p>I want to install cryptography package in python3.4.3 64bit version running on (windows 64bit} machine.</p> <p>I am getting the following error:</p> <p>{</p> <pre><code>generating cffi module 'build\\temp.win-...
0
2016-06-27T11:32:57Z
38,065,314
<p>We ship a statically linked wheel for Windows (our <a href="https://cryptography.io/en/latest/installation/#on-windows" rel="nofollow">install instructions</a> mention this) so all you need to do is be running the latest pip (as of June 2016 this is 8.1.2). To upgrade your pip you can do <code>python -m pip install ...
1
2016-06-28T00:38:58Z
[ "python", "visual-studio", "cryptography" ]
Update Query runs successfully in SQL but there are no changes in Database
38,052,904
<p>I have an update query to make some changes in the database, but unfortunately, it executes successfully and I see no changes in the database. What could be possibly wrong in a single line statement of SQL update query?</p> <pre><code>update_query = '''UPDATE air_programmes SET total_count = total_count + 1 WHERE ...
-1
2016-06-27T11:34:16Z
38,053,425
<p>You mention phpMyAdmin so I assume you're using MySQL with a db-api compliant connector (python-MySQL or mysql-connector-python etc).</p> <p>First point: you need to explicitely commit your changes, ie:</p> <pre><code>connection = YourConnector.connect(**connection_info) cursor = connection.cursor() update_query ...
1
2016-06-27T12:00:25Z
[ "python", "sql" ]
Database connection error of " signup() takes no arguments 4 given"
38,052,973
<p>Help me find where am going wrong here please....can't send anything to the database am getting this error "signup() takes no argument 4 given"</p> <p>This is my model.py file</p> <pre><code>app.secret_key = '9vY%N\\#l\xd1L\xd6r\xac\xec\xf5\xa6\x01W9_QD\\$' app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://po...
0
2016-06-27T11:37:36Z
38,053,104
<p>This isn't in any way at all a database connection error. It appears to be an indentation error; your <code>__init__</code> method (and the <code>__repr__</code> as well) are not inside the class, so the instantiation is not expecting the arguments you are passing.</p>
0
2016-06-27T11:44:07Z
[ "python" ]
sum two different class attributes
38,053,009
<p>Lets say I have 2 class and I want to add the second classes attributes to first class I can make like that:</p> <pre><code>class first: def __init__(self): self.value_one = 2 self.value_two = 5 self.value_third = 7 #second class don't have that attribute def sum_class(self, cls): ...
0
2016-06-27T11:39:16Z
38,053,353
<p>you can make it shorter by using:</p> <pre><code>def sum_class(self, cls): [setattr(self, attr, getattr(cls, attr) + getattr(self, attr)) for attr in cls.__dict__] </code></pre> <p>Edit 1:</p> <p>It was unclear what you wanted, but after you sad in comments you want something like <code>classA.__dict__ + clas...
-1
2016-06-27T11:57:00Z
[ "python" ]
sum two different class attributes
38,053,009
<p>Lets say I have 2 class and I want to add the second classes attributes to first class I can make like that:</p> <pre><code>class first: def __init__(self): self.value_one = 2 self.value_two = 5 self.value_third = 7 #second class don't have that attribute def sum_class(self, cls): ...
0
2016-06-27T11:39:16Z
38,053,772
<p>The only class that have a behvaiour similar to what you are looking for is the <a href="https://docs.python.org/3.5/library/collections.html#collections.Counter" rel="nofollow"><code>Counter</code></a> class:</p> <pre><code>&gt;&gt;&gt; c = Counter() &gt;&gt;&gt; c['a'] = 1.0 &gt;&gt;&gt; c + Counter('a') Counter(...
1
2016-06-27T12:16:37Z
[ "python" ]
Avoid python loop in deleting error prone values
38,053,016
<p>My timelines are stored in simple numpy Arrays, and they are long (>10 Million entrys)</p> <p>I have to detect machine shutdowns, that show in jumps in the time vector . After that shutdown I want do delete the next 10 values (The sensors do give bad results for a while after being switched on) and continue.</p> <...
1
2016-06-27T11:39:33Z
38,053,801
<p>Basically you are trying to spread/grow or in image-processing terms <a href="https://en.wikipedia.org/wiki/Dilation_(morphology)" rel="nofollow"><code>dilate</code></a> the <code>False</code> regions. For the same, we have a built-in as <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndima...
2
2016-06-27T12:18:07Z
[ "python", "numpy", "vectorization" ]
How can I change a network after initialising using functional API?
38,053,073
<p>I have a rather "simple" question. When I create a network using the functional API:</p> <pre><code>layer2 = Dense(8, name="layer2")(layer1) </code></pre> <p>and then initialise it with</p> <pre><code>model = Model(input=..., output=...) </code></pre> <p>what can I do if I want to change layers afterwards? If I ...
2
2016-06-27T11:42:46Z
38,104,192
<p>The <code>Model</code> object does not hold the weights, the layers do. You can load the weights for your model using <code>model.load_weights()</code> and then create a new layer based on the layers you have without losing the initialization of the layers.</p> <p>For example:</p> <pre><code>model.load_weights(f) ...
2
2016-06-29T15:36:53Z
[ "python", "neural-network", "theano", "conv-neural-network", "keras" ]
How do i write a generator function in html view in web2py with no return?
38,053,123
<p>I'm trying to print the remote terminal logs in a html modal,and i intend to achieve this using generator function &amp; writing it down in the view but how do i write it since the generator function does not return anything and hence no keyword return. Also it gives me a constant error ---SocketClosed: Client close...
0
2016-06-27T11:45:28Z
38,058,283
<p>Python code in web2py templates is executed entirely on the server <em>before</em> the HTML page is returned to the browser. No Python code can be executed in the browser. Therefore, this method will not work for dynamically displaying data from the server within the web page.</p> <p>Once the web page has been load...
0
2016-06-27T15:51:08Z
[ "javascript", "python", "html", "web2py" ]
Django store joined table in DB and update when tables change
38,053,496
<p>In my Django (1.9) project I need to construct a table from an expensive <code>JOIN</code>. I would therefore like to store the table in the DB and only redo the query if the tables involved in the <code>JOIN</code> change. As I need the table as a basis for later <code>JOIN</code> operations I definitely want to st...
1
2016-06-27T12:03:28Z
38,056,481
<h2>Materialized Views and Postgresql</h2> <p>If you were on postgresql, you could have used what's known as a <a href="https://www.postgresql.org/docs/9.3/static/sql-creatematerializedview.html" rel="nofollow">Materialized View</a>. Thus you can create a view based on your join and it would exist almost like a real t...
1
2016-06-27T14:24:57Z
[ "python", "mysql", "django", "celery" ]
Access last elements of inner multiindex level in pandas dataframe
38,053,687
<p>In a <code>multi index</code> pandas dataframe I want to access the <strong>last</strong> element of the second index for all values of the first index. The number of levels in the second index vary depending on the value of the first index. I went through the <a href="http://pandas.pydata.org/pandas-docs/stable/adv...
1
2016-06-27T12:12:43Z
38,053,778
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.tail.html" rel="nofollow"><code>tail</code></a>:</p> <pre><code>print (df.groupby(...
0
2016-06-27T12:16:55Z
[ "python", "pandas", "indexing", "dataframe", "multi-index" ]
Converting vertical headers to horizontal in csv
38,053,822
<p>I am new to Python. I have a csv file which will generate the file in below format:</p> <pre class="lang-none prettyprint-override"><code>Timestamp for usage of CPU 1466707823 1466707828 1466707833 Percent use for CPU# 0 0.590551162 0.588235305 0.59055119 Percent use for CPU# 1 7.874015497 7.843137402 7.6771654...
1
2016-06-27T12:19:20Z
38,056,896
<p>It seems like the simplest way to do it would be to first read and convert the data in the input file into a list of lists with each sublist corresponding to a column of data in the output csv file. The sublists will start off with the column's header and then be followed by the values associated with it from the ne...
0
2016-06-27T14:42:41Z
[ "python", "python-2.7", "python-3.x", "csv" ]
Loop that will iterate a certain number of times through a CSV in Python
38,053,893
<p>I have a large CSV file (~250000 rows) and before I work on fully parsing and sorting it I was trying to display only a part of it by writing it to a text file.</p> <pre><code> csvfile = open(file_path, "rb") rows = csvfile.readlines() text_file = open("output.txt", "w") row_num = 0 while row_num &lt;...
0
2016-06-27T12:22:29Z
38,053,991
<p>There's nothing specifically wrong with what you're doing, but it's not particularly Pythonic. In particular reading the whole file into memory with <code>readlines()</code> at the start seems pointless if you're only using 20 lines.</p> <p>Instead you could use a for loop with enumerate and break when necessary.</...
2
2016-06-27T12:26:49Z
[ "python", "python-2.7", "csv" ]
Loop that will iterate a certain number of times through a CSV in Python
38,053,893
<p>I have a large CSV file (~250000 rows) and before I work on fully parsing and sorting it I was trying to display only a part of it by writing it to a text file.</p> <pre><code> csvfile = open(file_path, "rb") rows = csvfile.readlines() text_file = open("output.txt", "w") row_num = 0 while row_num &lt;...
0
2016-06-27T12:22:29Z
38,054,497
<p>A simple solution would be to just do :</p> <pre><code>#!/usr/bin/python # -*- encoding: utf-8 -*- file_path = './test.csv' with open(file_path, 'rb') as csvfile: with open('output.txt', 'wb') as textfile: for i, row in enumerate(csvfile): textfile.write(row) if i &gt;= 20: ...
1
2016-06-27T12:52:25Z
[ "python", "python-2.7", "csv" ]
SciPy sparse matrix (COO,CSR): Clear row
38,053,935
<p>For creating a <a href="https://docs.scipy.org/doc/scipy/reference/sparse.html" rel="nofollow">scipy sparse matrix</a>, I have an array or row and column indices <code>I</code> and <code>J</code> along with a data array <code>V</code>. I use those to construct a matrix in <a href="https://docs.scipy.org/doc/scipy-0....
0
2016-06-27T12:24:31Z
38,055,182
<p>If you intend to clear multiple rows at once, this</p> <pre><code>def _wipe_rows_csr(matrix, rows): assert isinstance(matrix, sparse.csr_matrix) # delete rows for i in rows: matrix.data[matrix.indptr[i]:matrix.indptr[i+1]] = 0.0 # Set the diagonal d = matrix.diagonal() d[rows] = ...
1
2016-06-27T13:24:51Z
[ "python", "scipy", "sparse-matrix" ]
SciPy sparse matrix (COO,CSR): Clear row
38,053,935
<p>For creating a <a href="https://docs.scipy.org/doc/scipy/reference/sparse.html" rel="nofollow">scipy sparse matrix</a>, I have an array or row and column indices <code>I</code> and <code>J</code> along with a data array <code>V</code>. I use those to construct a matrix in <a href="https://docs.scipy.org/doc/scipy-0....
0
2016-06-27T12:24:31Z
38,059,066
<p><code>np.in1d</code> should be a faster way of finding the <code>indices</code>:</p> <pre><code>In [322]: I # from a np.arange(12).reshape(4,3) matrix Out[322]: array([0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3], dtype=int32) In [323]: indices=[i for i, x in enumerate(I) if x in [1,2]] In [324]: indices Out[324]: [2, 3, 4...
0
2016-06-27T16:37:41Z
[ "python", "scipy", "sparse-matrix" ]
How do I efficiently get the index and value for a key from SortedDict?
38,053,949
<p>Given a collection that is ordered and keyed (like OrderedDict or <a href="http://www.grantjenks.com/docs/sortedcontainers/" rel="nofollow">SortedContainers</a> SortedDict) I want to do the following:</p> <pre><code>d['first'] = 'hi' d['second'] = 'there' d['third'] = 'world' (ix, value) = d.get_index_and_value('se...
0
2016-06-27T12:25:00Z
38,054,145
<p>You can use the <code>index</code> method of <code>keys</code>:</p> <pre><code>ix, value = d.keys().index('second'), d['second'] </code></pre> <p>this will return</p> <pre><code>(1, 'there') </code></pre> <p>If you don't want to repeat yourself, you can make this a function, or extend <code>OrderedDict</code> to...
1
2016-06-27T12:34:56Z
[ "python", "sortedcontainers" ]
Duplicating list items variable number of times with list comprehension
38,054,064
<p>I am basically trying to get my head around using a list comprehension with this basic bit of code. Im trying to duplicate a list item by the value of the list item:</p> <pre><code>y = [1, 2, 0, 1] x = [] for i in y: for j in range(i): x.append(i) # Desired output &gt;&gt;&gt; [1, 2, 2, 1] x = [i for _...
1
2016-06-27T12:30:19Z
38,054,158
<p>The right comprehension is:</p> <pre><code>x = [i for i in y for j in range(i)] </code></pre> <p>This give the result you want<br> item for item in list range(item) times<br> inspired by this <a href="http://stackoverflow.com/questions/11264684/flatten-list-of-lists">thread</a></p> <pre><code>flattened = [val for...
1
2016-06-27T12:35:31Z
[ "python", "list" ]
Duplicating list items variable number of times with list comprehension
38,054,064
<p>I am basically trying to get my head around using a list comprehension with this basic bit of code. Im trying to duplicate a list item by the value of the list item:</p> <pre><code>y = [1, 2, 0, 1] x = [] for i in y: for j in range(i): x.append(i) # Desired output &gt;&gt;&gt; [1, 2, 2, 1] x = [i for _...
1
2016-06-27T12:30:19Z
38,054,221
<pre><code>x = [j for j in y for i in range(j)] </code></pre>
-1
2016-06-27T12:38:11Z
[ "python", "list" ]
Duplicating list items variable number of times with list comprehension
38,054,064
<p>I am basically trying to get my head around using a list comprehension with this basic bit of code. Im trying to duplicate a list item by the value of the list item:</p> <pre><code>y = [1, 2, 0, 1] x = [] for i in y: for j in range(i): x.append(i) # Desired output &gt;&gt;&gt; [1, 2, 2, 1] x = [i for _...
1
2016-06-27T12:30:19Z
38,054,233
<p>When you have multiple <code>for</code> loops inside a list comprehension, the loops are processed in the same order as they would be using "traditional" <code>for</code> loops. Your list comp that gives the correct output has the loops in the same order as your code at the start using <code>.append</code> with trad...
3
2016-06-27T12:38:31Z
[ "python", "list" ]
Django model, filter then group and total cost
38,054,066
<p>I have a filter, whereby I want to choose a provider, then for that provider show what circuit types we have and the total cost for those circuit types, from my research the below should work</p> <p>query:</p> <pre><code>model_provider_costs = CircuitInfoData.objects.filter(provider = "BT").values('circuit_type')....
0
2016-06-27T12:30:39Z
38,054,834
<p>It should probably be</p> <pre><code>model_provider_costs = CircuitInfoData.objects.filter(provider = "BT").prefetch_related('circuit_type').aggregate(Sum('cost_per_month')) </code></pre>
0
2016-06-27T13:08:40Z
[ "python", "django" ]
pandas wont add columns in order
38,054,160
<p>I have two data frames </p> <p>numbers:</p> <pre><code>Unnamed: 0 Name Number 42 42 Aberavon 1742 43 43 Aberconwy 2769 16 16 Aberdeen North 3253 25 25 Aberdeen South 4122 355 ...
0
2016-06-27T12:35:34Z
38,054,213
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.values.html" rel="nofollow"><code>values</code></a> for converting column <code>Number</code> to <code>numpy array</code>, so align is corrected:</p> <pre><code>numbers['No. Voters] = electorate['Number'].values </code></pre> ...
1
2016-06-27T12:37:47Z
[ "python", "numpy", "pandas", "multiple-columns" ]
pandas wont add columns in order
38,054,160
<p>I have two data frames </p> <p>numbers:</p> <pre><code>Unnamed: 0 Name Number 42 42 Aberavon 1742 43 43 Aberconwy 2769 16 16 Aberdeen North 3253 25 25 Aberdeen South 4122 355 ...
0
2016-06-27T12:35:34Z
38,054,219
<p>Look at the indexes of your dataframes, they aren't the same. That's why you have problems when you create your new column.</p> <p>If you don't care about keeping the index of <code>electorate</code> you can use <code>reset_index</code> before defining the new column of <code>number</code>:</p> <pre><code>electora...
1
2016-06-27T12:38:10Z
[ "python", "numpy", "pandas", "multiple-columns" ]
Django Heroku - Dropdown not working in bootstrap
38,054,246
<p>I made a Django project and a page has side menu, whenever the side menu is selected a dropdown appears. This is happening when I run it locally, whereas its not working from heroku. The dropdown code is as follows:</p> <pre><code>&lt;li class="panel panel-default" id="dropdown"&gt; &lt;a data-toggle="c...
0
2016-06-27T12:39:01Z
38,054,319
<p>You are trying to load an unencrypted (<code>http</code>) resource from a secure (<code>https</code>) page. You will notice that if you check your page using <code>http</code> it will work.</p> <p>Change the following line</p> <pre><code>&lt;script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.m...
1
2016-06-27T12:43:47Z
[ "jquery", "python", "django", "twitter-bootstrap", "heroku" ]
gensim: custom similarity measure
38,054,356
<p>Using <code>gensim</code>, I want to calculate the similarity within a list of documents. This library is excellent at handling the amounts of data that I have got. The documents are all reduced to timestamps and I have got a function <code>time_similarity</code> to compare them. <code>gensim</code> however, uses th...
6
2016-06-27T12:45:42Z
38,214,528
<p>It is possible to do this by inheriting from the interface <code>SimilarityABC</code>. I did not find any documentation for this but it looks like it has been done before to define <a href="https://github.com/RaRe-Technologies/gensim/blob/develop/gensim/similarities/docsim.py#L555" rel="nofollow">Word Mover Distance...
1
2016-07-05T23:46:22Z
[ "python", "time", "similarity", "gensim" ]
Trying to check if String in Python follows the correct pattern (good formatting)
38,054,373
<p>I have a dataset that contains columns with strings. One of those columns contain a identifier. Now I want to check if that identifier follows this pattern: e.g. AB12CD, so 2 letters(Capital), 2 numbers followed by 2 letters again.</p> <p>The data is stored in a pandas data frame. I have:</p> <pre><code>for i in r...
0
2016-06-27T12:46:27Z
38,054,463
<p>Your code doesn't work as expected because <code>data['identifier Check'] = 'Ok'</code> assigns <code>'Ok'</code> to every row in the <code>identifier Check</code> column. </p> <p>Your code also scans the DataFrame column-wise instead of row-wise (ie it checks the value in the first row of every column, instead of ...
2
2016-06-27T12:51:02Z
[ "python", "python-3.x", "pandas", "match" ]
Python connector error on trying to delete using user input
38,054,381
<p>I have implemented most other basic database transactions including insert,update,select with similar syntax,but on trying to delete,i get error</p> <blockquote> <p>mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server v...
0
2016-06-27T12:46:59Z
38,054,477
<p>You need to pass query parameters to <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html" rel="nofollow"><code>cursor.execute()</code></a> as a <em>tuple</em>, even for a single parameter. Try this:</p> <pre><code>sql = "DELETE FROM users WHERE email = %s" cursor.exe...
2
2016-06-27T12:51:24Z
[ "python", "mysql", "syntax-error", "mysql-connector" ]
Indexing a list with another list which contains arrays
38,054,392
<p>Dear forum I want to index a patient data list with an annotation list where every element is an nx1 array. </p> <p>Patient List: e.g. 10 patients, 20 features, 300 datapoints (each element of the list is an 300x20 array) Annotation List: e.g. 10 patients, 300 annotations </p> <p>The aim is to create a list with p...
3
2016-06-27T12:47:55Z
38,071,361
<p>I seems to work with this:</p> <pre><code>Xfeat=[val[idx[sb],:] for sb, val in enumerate(Xfeat) if sb in selected_babies] </code></pre> <p>I still get the indexError, but only for a certain patient. I will have to figure out what happens there. Hope I could help someone.</p> <p>Cheers</p>
1
2016-06-28T08:49:37Z
[ "python", "arrays", "list", "indexing" ]
How to pick up 2 parameters using scipy optimize
38,054,424
<p>I have data </p> <pre><code>diff_time 0 124 56 87 40 168 449 13 </code></pre> <p>I should write a function, where I can get 2 parameters automatically <code>a and b</code>, where </p> <pre><code>for el in df['diff_time']: if el &gt; a: el = b else: el = continue </code></pre> <p>How can I...
2
2016-06-27T12:49:30Z
38,054,516
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mask.html" rel="nofollow"><code>mask</code></a> by <code>boolean mask</code> created by <code>df.diff_time &gt; a</code>:</p> <pre><code>a = 100 b = 33 print (df.diff_time &gt; a) 0 False 1 True 2 False 3 ...
1
2016-06-27T12:53:14Z
[ "python", "pandas", "scipy" ]
How to pick up 2 parameters using scipy optimize
38,054,424
<p>I have data </p> <pre><code>diff_time 0 124 56 87 40 168 449 13 </code></pre> <p>I should write a function, where I can get 2 parameters automatically <code>a and b</code>, where </p> <pre><code>for el in df['diff_time']: if el &gt; a: el = b else: el = continue </code></pre> <p>How can I...
2
2016-06-27T12:49:30Z
38,054,580
<pre><code>a = 100 b = 33 df['diff_time'].apply(lambda el: b if el &gt; a else el) 0 0 1 33 2 56 3 87 4 40 5 33 6 33 7 13 Name: diff_time, dtype: int64 </code></pre>
0
2016-06-27T12:55:34Z
[ "python", "pandas", "scipy" ]
TypeError when creating a MySQL table with parameters
38,054,436
<p>Something is wrong either with this execute statement or with the list I'm passing into it. </p> <p>I keep getting:</p> <pre><code>Traceback (most recent call last): File "/Users/Hardway/test_package/sqltest5.py", line 12, in &lt;module&gt; cur.execute(create_table, ('userid', 'age_of_account', 'number_of_fr...
1
2016-06-27T12:50:09Z
38,054,784
<p>You can't pass column names as query parameters to <code>cursor.execute()</code>. You'll have to use string <a href="https://docs.python.org/2/library/stdtypes.html#str.format" rel="nofollow">formatting</a> to interpolate them into the query:</p> <pre><code>create_table = ("CREATE TABLE Users ({} INT, {} INT, {} I...
1
2016-06-27T13:06:23Z
[ "python", "mysql" ]
TypeError when creating a MySQL table with parameters
38,054,436
<p>Something is wrong either with this execute statement or with the list I'm passing into it. </p> <p>I keep getting:</p> <pre><code>Traceback (most recent call last): File "/Users/Hardway/test_package/sqltest5.py", line 12, in &lt;module&gt; cur.execute(create_table, ('userid', 'age_of_account', 'number_of_fr...
1
2016-06-27T12:50:09Z
38,059,482
<p>You can pass <em>values</em> in <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html" rel="nofollow">MySQLCursor.execute</a> but not the column names. So, use <code>str.format</code>:</p> <pre><code>create_table = "Create table Users ({0} int, {1} int, {2} int, {3} fl...
1
2016-06-27T17:04:41Z
[ "python", "mysql" ]
zip_longest without fillvalue
38,054,593
<p>I am searching for a middle ground between Python's <code>zip</code> and <code>zip_longest</code> functions (from the <em>itertools</em> module), that exhausts all given iterators, but does not fill in anything. So, for example, it should transpose tuples like so:</p> <pre class="lang-py prettyprint-override"><co...
2
2016-06-27T12:56:02Z
38,059,462
<p>You approach is good. I think using a sentinel is elegant. I might be considered a bit more pythonic to use a nested generator expression:</p> <pre><code>def zip_discard_gen(*iterables, sentinel=object()): return ((entry for entry in iterable if entry is not sentinel) for iterable in zip_longest(*it...
2
2016-06-27T17:03:17Z
[ "python", "functional-programming", "itertools" ]
zip_longest without fillvalue
38,054,593
<p>I am searching for a middle ground between Python's <code>zip</code> and <code>zip_longest</code> functions (from the <em>itertools</em> module), that exhausts all given iterators, but does not fill in anything. So, for example, it should transpose tuples like so:</p> <pre class="lang-py prettyprint-override"><co...
2
2016-06-27T12:56:02Z
38,061,444
<p>Both <code>zip</code> and <code>zip_longest</code> were designed to always generate tuples of equal length, you can define your own generator that doesn't care about the len with something like this:</p> <pre><code>def _one_pass(iters): for it in iters: try: yield next(it) except Sto...
3
2016-06-27T19:08:39Z
[ "python", "functional-programming", "itertools" ]
Importing submodules in python
38,054,679
<p>This question is related to <a href="http://stackoverflow.com/questions/33012531/python-import-breaks-when-importing-submodule">this</a> one. After going through the python's module documentation <a href="https://docs.python.org/2/tutorial/modules.html" rel="nofollow">here</a>, I'm unable to import a submodule into ...
0
2016-06-27T13:01:02Z
38,054,729
<p>Your launcher.py seems to be at the "test_module" level already. Did you try <code>import test_submodule.app</code> ?</p> <p><strong><em>EDIT</em></strong></p> <p>Try <code>from test_submodule import app</code></p>
0
2016-06-27T13:03:27Z
[ "python", "module", "pycharm" ]
Python Searching Nested Lists
38,054,897
<p>I have a nested list called players as shown below:</p> <pre><code>players = [["PlayerA", "10", "20"], ["PlayerB", "15", "30"], ["PlayerC", "15", "30"] ] </code></pre> <p>I want to be able to search by Player name (PlayerA, PlayerB, etc) using an input statement and if the search matches an item, then it prints ou...
3
2016-06-27T13:11:38Z
38,054,942
<pre><code>if item == search: </code></pre> <p>This conditional won't succeed because <code>item</code> is <code>["PlayerA", "10", "20"]</code>, and <code>search</code> is <code>"PlayerA"</code>. A list won't ever compare equal to a string.</p> <p>Try comparing <code>search</code> against the first element of <code>i...
4
2016-06-27T13:14:24Z
[ "python" ]
Python Searching Nested Lists
38,054,897
<p>I have a nested list called players as shown below:</p> <pre><code>players = [["PlayerA", "10", "20"], ["PlayerB", "15", "30"], ["PlayerC", "15", "30"] ] </code></pre> <p>I want to be able to search by Player name (PlayerA, PlayerB, etc) using an input statement and if the search matches an item, then it prints ou...
3
2016-06-27T13:11:38Z
38,054,949
<p>You need to access to first element or your nested list. Like this:</p> <pre><code>for player in players: if player[0] == input: return player </code></pre>
2
2016-06-27T13:14:34Z
[ "python" ]
Python Searching Nested Lists
38,054,897
<p>I have a nested list called players as shown below:</p> <pre><code>players = [["PlayerA", "10", "20"], ["PlayerB", "15", "30"], ["PlayerC", "15", "30"] ] </code></pre> <p>I want to be able to search by Player name (PlayerA, PlayerB, etc) using an input statement and if the search matches an item, then it prints ou...
3
2016-06-27T13:11:38Z
38,054,989
<p>The reason that it's printing "item not found" is because you are comparing a sublist to the string to find, e.g.,</p> <pre><code>["PlayerA", "10", "20"] == "PlayerA" </code></pre> <p>which, of course, is false. You need to extract the name from each sublist. </p> <p>One way you could do this is to use <code>fi...
4
2016-06-27T13:16:29Z
[ "python" ]
Python Searching Nested Lists
38,054,897
<p>I have a nested list called players as shown below:</p> <pre><code>players = [["PlayerA", "10", "20"], ["PlayerB", "15", "30"], ["PlayerC", "15", "30"] ] </code></pre> <p>I want to be able to search by Player name (PlayerA, PlayerB, etc) using an input statement and if the search matches an item, then it prints ou...
3
2016-06-27T13:11:38Z
38,055,395
<p>Yeah just make you're code like this:</p> <pre><code>players = [["PlayerA", "10", "20"], ["PlayerB", "15", "30"], ["PlayerC", "15", "30"] ] search = input("Please enter the players name: ") result = [player for player in players if player[0] == search] if result == []: print("item not found") else: print(...
1
2016-06-27T13:34:42Z
[ "python" ]
map with failure in Numpy
38,054,955
<p>Inspired by Haskell:</p> <p>How can I implement the following with a numpy array in Python?</p> <pre><code>In [13]: [(x if x&gt;3 else None) for x in range(10)] Out[13]: [None, None, None, None, 4, 5, 6, 7, 8, 9] </code></pre> <p>In other words, I am looking for a function for numpy that would have the signature:...
3
2016-06-27T13:14:50Z
38,055,046
<p>NumPy's <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow"><code>where()</code></a> will do the trick:</p> <pre><code>In [429]: import numpy as np In [430]: arr = np.arange(10, dtype=np.object) In [431]: np.where(arr &gt; 3, arr, None) Out[431]: array([None, None, None, ...
5
2016-06-27T13:18:53Z
[ "python", "haskell", "numpy" ]
map with failure in Numpy
38,054,955
<p>Inspired by Haskell:</p> <p>How can I implement the following with a numpy array in Python?</p> <pre><code>In [13]: [(x if x&gt;3 else None) for x in range(10)] Out[13]: [None, None, None, None, 4, 5, 6, 7, 8, 9] </code></pre> <p>In other words, I am looking for a function for numpy that would have the signature:...
3
2016-06-27T13:14:50Z
38,056,015
<p>A slightly different technique than Tonechas' which uses numpy's boolean indexing feature.</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; x = np.arange(10).astype(np.object) &gt;&gt;&gt; x[x&lt;4] = None </code></pre> <p>returns </p> <pre><code>array([None, None, None, None, 4, 5, 6, 7, 8, 9], dtype=...
3
2016-06-27T14:03:28Z
[ "python", "haskell", "numpy" ]
map with failure in Numpy
38,054,955
<p>Inspired by Haskell:</p> <p>How can I implement the following with a numpy array in Python?</p> <pre><code>In [13]: [(x if x&gt;3 else None) for x in range(10)] Out[13]: [None, None, None, None, 4, 5, 6, 7, 8, 9] </code></pre> <p>In other words, I am looking for a function for numpy that would have the signature:...
3
2016-06-27T13:14:50Z
38,064,258
<p>I'd recommend to revisit the premise that you want <code>None</code>s in a numpy array: you need an array of <code>dtype=object</code> to store a <code>None</code>, i.e. you'll be storing python objects in an array. This way you're going to lose most of the advantages that numpy provides over plain lists.</p> <p>If...
5
2016-06-27T22:34:25Z
[ "python", "haskell", "numpy" ]
What is the dask equivalent of numpy.tile?
38,054,970
<p>Dask (<a href="http://dask.pydata.org/en/latest/array-api.html" rel="nofollow">http://dask.pydata.org/en/latest/array-api.html</a>) is a flexible parallel computing library for analytics. It scales to big data, in constrast to Numpy and has many similar methods. How can I achieve the same effect as <code>numpy.tile<...
3
2016-06-27T13:15:28Z
38,057,938
<p>Using <a href="http://dask.pydata.org/en/latest/array-api.html#dask.array.concatenate" rel="nofollow"><code>dask.array.concatenate()</code></a> could be a possible workaround.</p> <p>Demo in NumPy:</p> <pre><code>In [374]: x = numpy.arange(4).reshape((2, 2)) In [375]: x Out[375]: array([[0, 1], [2, 3]]) ...
1
2016-06-27T15:32:44Z
[ "python", "numpy", "dask" ]
Scrapy and Pycharm - Stange import error - No module named [insert name of scrapyproject here]
38,054,980
<p>Hi Stackoverflow Community</p> <p>I encountered the following issue. I have a scrapy project which I added to my project:</p> <pre><code>-.idea -associate -core -scrapyproject -- scrapyproject_one --- spiders ---- __iniy.py__ ---- dmoz_spider.py -- __init__.py -- items.py -- pipeline...
0
2016-06-27T13:15:57Z
38,055,401
<p>All right, I figured it out. </p> <p>What I needed to do was to declare my 'spiderproject' folder as a 'Sources folder' in PyCharm. </p> <p>You can do that by going to File>Settings>Project:[Project Name]>Project Structure.</p> <p>Select the level 1 project folder of your scrapy project (in this case 'spiderproje...
0
2016-06-27T13:35:04Z
[ "python", "module", "scrapy", "pycharm" ]
python float to string without precision loss
38,055,000
<p>For python 3 I want to convert a float to a string, with possibly different length (i.e. number of digits) but with full precision.</p> <p>Also I need to have a decimal point in any case:</p> <pre><code>1 -&gt; '1.' 1/10 -&gt; '0.1000000000000000055511151231257827021181583404541015625' </code></pre> <p>current...
1
2016-06-27T13:17:03Z
38,057,205
<p>why do you use Decimal, you can just use:</p> <pre><code>x = 0.1 s = str(x) print(s) # this prints '0.1' </code></pre> <p>but if you use Decimal for something else than instead of this:</p> <pre><code>out = str(Decimal(x)) if out.find('.') &lt; 0: out += '.' return out </code></pre> <p>you can just use:</p...
1
2016-06-27T14:57:14Z
[ "python", "python-3.x", "floating-point" ]
python float to string without precision loss
38,055,000
<p>For python 3 I want to convert a float to a string, with possibly different length (i.e. number of digits) but with full precision.</p> <p>Also I need to have a decimal point in any case:</p> <pre><code>1 -&gt; '1.' 1/10 -&gt; '0.1000000000000000055511151231257827021181583404541015625' </code></pre> <p>current...
1
2016-06-27T13:17:03Z
38,058,477
<p>Use Pythons <a href="https://docs.python.org/3/library/string.html#format-examples" rel="nofollow">string formatting functions</a>:</p> <pre><code>&gt;&gt;&gt; x = 1.0; '{:.55f}'.format(x) '1.0000000000000000000000000000000000000000000000000000000' &gt;&gt;&gt; x = 1/10; '{:.55f}'.format(x) '0.100000000000000005551...
2
2016-06-27T16:01:12Z
[ "python", "python-3.x", "floating-point" ]
Pandas: compute numerous columns of percentage values
38,055,029
<p>I'm failing to loop through the values of select dataframe columns in order to create new columns representing percentage values. Reproducible example:</p> <pre><code> data = {'Respondents': [90, 43, 89, '89', '67', '88', '73', '78', '62', '101'], 'answer_1': [51, 15, 15, 61, 16, 14, 15, 1, 0, 16], ...
2
2016-06-27T13:18:08Z
38,055,132
<p>You almost had it, note that you have string values in respondents col which I've corrected prior to calling the following:</p> <pre><code>In [172]: for col in df.columns[1:4]: i_name = 'percentage_' + col i_group = (df[col] / df['Respondents']) * 100 df[i_name] = i_group df Out[172]: Respondents ...
3
2016-06-27T13:22:44Z
[ "python", "pandas" ]
Pandas: compute numerous columns of percentage values
38,055,029
<p>I'm failing to loop through the values of select dataframe columns in order to create new columns representing percentage values. Reproducible example:</p> <pre><code> data = {'Respondents': [90, 43, 89, '89', '67', '88', '73', '78', '62', '101'], 'answer_1': [51, 15, 15, 61, 16, 14, 15, 1, 0, 16], ...
2
2016-06-27T13:18:08Z
38,055,253
<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html" rel="nofollow"><code>div</code></a> desired columns by column <code>Respondents</code> and then add to new columns names:</p> <pre><code>print ('percentage_' + df.columns[1:4]) Index(['percentage_answer_...
0
2016-06-27T13:28:14Z
[ "python", "pandas" ]
Pandas: compute numerous columns of percentage values
38,055,029
<p>I'm failing to loop through the values of select dataframe columns in order to create new columns representing percentage values. Reproducible example:</p> <pre><code> data = {'Respondents': [90, 43, 89, '89', '67', '88', '73', '78', '62', '101'], 'answer_1': [51, 15, 15, 61, 16, 14, 15, 1, 0, 16], ...
2
2016-06-27T13:18:08Z
38,055,291
<p>I recommend using div and concat:</p> <pre><code>df['Respondents'] = df['Respondents'].astype(float) df_pct = (df.drop('Respondents', axis=1) .div(df['Respondents'], axis=0) .mul(100) .rename(columns=lambda col: 'percentage_' + col) ) pd.concat([df, df_pct], axis=1) ...
2
2016-06-27T13:29:55Z
[ "python", "pandas" ]
Efficient way to convert image stored as numpy array into hsv
38,055,065
<p>I'm doing some data analysis of images. For some analysis I would like to convert the image's pixels in to HSV from RGB in which they are originally stored.</p> <p>At the moment I'm using this code:</p> <pre><code>def generate_hsv(im): coords = product(range(im.shape[0]), range(im.shape[1])) num_cores = mu...
1
2016-06-27T13:19:43Z
38,055,826
<p>As Warren Weckesser said, the conversion function is problematic. I ended up using matplotlib:</p> <p><code>matplotlib.colors.rgb_to_hsv(arr)</code></p> <p>It now runs a million times faster.</p>
1
2016-06-27T13:54:36Z
[ "python", "numpy", "image-processing", "parallel-processing" ]
Efficient way to convert image stored as numpy array into hsv
38,055,065
<p>I'm doing some data analysis of images. For some analysis I would like to convert the image's pixels in to HSV from RGB in which they are originally stored.</p> <p>At the moment I'm using this code:</p> <pre><code>def generate_hsv(im): coords = product(range(im.shape[0]), range(im.shape[1])) num_cores = mu...
1
2016-06-27T13:19:43Z
38,059,401
<p><code>Colorsys</code> module has its implementation for each pixel with the input being expected as <code>(R,G,B)</code>. Now, <a href="https://github.com/python/cpython/blob/master/Lib/colorsys.py#L124" rel="nofollow"><code>colorsys</code>'s implementation</a> is listed below -</p> <pre><code>def rgb_to_hsv(r, g, ...
1
2016-06-27T16:59:36Z
[ "python", "numpy", "image-processing", "parallel-processing" ]
List Comprehension - Double Loop or Not?
38,055,285
<p>I am having the following issue:</p> <pre><code># Neither this trial1 = [[x for x in 10000 // 5**i] for i in range(1, 10)] # nor this trial2 = [x for i in range(1, 10) for x in 10000 // 5**i] # work. </code></pre> <p>They both return: "int" object is not iterable, which is somehow confusing to me. Since <code>...
0
2016-06-27T13:29:40Z
38,055,357
<p>The comprehension equivalent of your working <code>for</code> loop would be:</p> <pre><code>[10000 // 5**i for i in range(1, 10)] </code></pre> <p>There are no double loops in that example, so there shouldn't be in the comprehension either.</p> <p>Regarding your second question; <code>i</code> is <em>not</em> a l...
2
2016-06-27T13:33:23Z
[ "python" ]
List Comprehension - Double Loop or Not?
38,055,285
<p>I am having the following issue:</p> <pre><code># Neither this trial1 = [[x for x in 10000 // 5**i] for i in range(1, 10)] # nor this trial2 = [x for i in range(1, 10) for x in 10000 // 5**i] # work. </code></pre> <p>They both return: "int" object is not iterable, which is somehow confusing to me. Since <code>...
0
2016-06-27T13:29:40Z
38,055,359
<p><code>for x in 10000 // 34**i</code> or anything like that means <em>iterating through a number</em>, which doesn't make sense and results in an error.</p> <p>You seem to be trying to append numbers to a list, which is easy:</p> <pre><code>trial = [10000 // 5**i for i in range(1, 5)] </code></pre> <p>Here you're ...
1
2016-06-27T13:33:24Z
[ "python" ]
List Comprehension - Double Loop or Not?
38,055,285
<p>I am having the following issue:</p> <pre><code># Neither this trial1 = [[x for x in 10000 // 5**i] for i in range(1, 10)] # nor this trial2 = [x for i in range(1, 10) for x in 10000 // 5**i] # work. </code></pre> <p>They both return: "int" object is not iterable, which is somehow confusing to me. Since <code>...
0
2016-06-27T13:29:40Z
38,055,385
<p>The equivalent of </p> <pre><code>trial = [] for i in range(1, k): trial.append(n // 5**i) </code></pre> <p>is simply</p> <pre><code>trial = [10000 // 5**i for i in range(1, k)] </code></pre> <p>since you are simply calculating <code>10000 // 5**i</code> for ever <code>i</code> in <code>range(1, k)</code></p...
2
2016-06-27T13:34:14Z
[ "python" ]
Loading a json file in python
38,055,307
<p>I've got multiple file to load as JSON, they are all formatted the same way but for one of them I can't load it without raising an exception. This is where you can find the file:</p> <p><a href="https://s3-us-west-1.amazonaws.com/riot-api/seed_data/matches3.json" rel="nofollow">File</a></p> <p>I did the following ...
1
2016-06-27T13:31:16Z
38,055,378
<ol> <li>replace <code>file_name = 'data/matches%s.json' % i</code> with file_name = 'data/matches%i.json' % i</li> <li><p>the right syntax is <code>data = json.load(file_name)</code> and not - </p> <p>with open(file_name) as data_file: data = json.load(data_file)</p></li> </ol> <p>EDIT:</p> <pre><code>def from_...
2
2016-06-27T13:34:03Z
[ "python", "json", "encoding" ]
Loading a json file in python
38,055,307
<p>I've got multiple file to load as JSON, they are all formatted the same way but for one of them I can't load it without raising an exception. This is where you can find the file:</p> <p><a href="https://s3-us-west-1.amazonaws.com/riot-api/seed_data/matches3.json" rel="nofollow">File</a></p> <p>I did the following ...
1
2016-06-27T13:31:16Z
38,055,389
<p>Your JSON is trying to force the data into unicode, not just a simple string. You've got some embedded character (probably a space or something not very noticable) that is not able to be forced into unicode.</p> <p><a href="http://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-ones-...
2
2016-06-27T13:34:21Z
[ "python", "json", "encoding" ]
Loading a json file in python
38,055,307
<p>I've got multiple file to load as JSON, they are all formatted the same way but for one of them I can't load it without raising an exception. This is where you can find the file:</p> <p><a href="https://s3-us-west-1.amazonaws.com/riot-api/seed_data/matches3.json" rel="nofollow">File</a></p> <p>I did the following ...
1
2016-06-27T13:31:16Z
38,055,419
<p>try :</p> <pre><code>json.loads(data_file.read(), encoding='utf-8') </code></pre>
1
2016-06-27T13:36:06Z
[ "python", "json", "encoding" ]
Loading a json file in python
38,055,307
<p>I've got multiple file to load as JSON, they are all formatted the same way but for one of them I can't load it without raising an exception. This is where you can find the file:</p> <p><a href="https://s3-us-west-1.amazonaws.com/riot-api/seed_data/matches3.json" rel="nofollow">File</a></p> <p>I did the following ...
1
2016-06-27T13:31:16Z
38,055,575
<p>Try:</p> <pre><code>json.loads(unicode(data_file.read(), errors='ignore')) </code></pre> <p>or :</p> <pre><code>json.loads(unidecode.unidecode(unicode(data_file.read(), errors='ignore'))) </code></pre> <p>(for the second, you would need to install <a href="https://pypi.python.org/pypi/Unidecode" rel="nofollow">u...
1
2016-06-27T13:43:29Z
[ "python", "json", "encoding" ]
Problems finding a cell with openpyxl
38,055,514
<p>I'm trying to find the value of a cell in excel, by first locating the row that it's in and then passing through the coordinates of the cell (the column will be the same each time).</p> <p>I tried using the code below, the problem with it is that it rownum is not the number of the row (as I was expecting). Please c...
1
2016-06-27T13:40:06Z
38,056,416
<p>I wasn't able to find a function that locates the row number, but I can find the row number with the cell value I'm looking for by using the following:</p> <pre><code>wb = openpyxl.load_workbook('C:\\rtemp\\Names.xlsx') ws = wb['Sheet5'] rownum = 0 for row in ws: for cell in row: if cell.value == 'ResellBalan...
0
2016-06-27T14:22:26Z
[ "python", "excel" ]
how to read path which is original windows path form from a file in python?
38,055,565
<p>I have a text file contains some path, for example, it contains: c:\text\text1 c:\text\text2 ....... how can I read these file directory as correct path? I know that I can put 'r' before path to make it work, such as </p> <pre><code>path=r'c:\text\text1' </code></pre> <p>but this time I need to read these to a var...
-1
2016-06-27T13:42:56Z
38,055,977
<p>Assuming you stored the path you read to variable path, just do this:</p> <pre><code>path = r'C:\Users\ShengFeng\Documents\April.txt' path = path.replace("\\", "\\\\") print(path) #prints: 'C:\\Users\\ShengFeng\\Documents\\April.txt' </code></pre>
1
2016-06-27T14:01:53Z
[ "python" ]
Left-align a pandas rolling object
38,055,632
<p>Using pandas 0.18.1, I'd like to take the rolling average of a one-column dataframe. Since version 0.18.0, this is done with rolling() objects. The default for these rolling objects is to be right-justified. There is a boolean argument you can pass, center=True, to align the rolling object to the center value, but t...
2
2016-06-27T13:46:10Z
38,056,328
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.shift.html" rel="nofollow"><code>shift</code></a>:</p> <pre><code>a = df.rolling(window=3).mean().shift(-2) print (a) A 0 3.666667 1 5.666667 2 11.333333 3 18.333333 4 NaN 5 NaN </code></p...
2
2016-06-27T14:18:15Z
[ "python", "pandas" ]
AWS boto - stop servers in threads
38,055,717
<p>So here is my little piece of code that is supposed to stop multiple servers in threads:</p> <pre><code>for x in range(amount): server_id = str(servers[x][4]) t = threading.Thread(target=stop_server, args=(server_id)) threads.append(t) t.start() </code></pre> <p>Now, the issue is that server_id is ...
0
2016-06-27T13:49:39Z
38,055,924
<p>Ok - a coma was missing after "server_id" in args....</p>
0
2016-06-27T13:59:05Z
[ "python", "multithreading", "amazon-web-services", "boto" ]
How to test Generators in Python 3. It gives error all the time
38,055,783
<p>I have snippet of the code below. Which I cannot change but I need to test. What it does is it connects to the server and gets data that I need. In particular I need to insert falsely input for variable data1 on line 12 to test it. But I can't achieve it so far.</p> <pre><code>1. url = "http://localhost:8000" 2. da...
-6
2016-06-27T13:52:43Z
38,055,898
<p>Yes, a <em>generator</em> can't be equal to a string.</p> <p>When your call your function: <code>get_objects("anything")</code>, it <em>returns a generator object</em> you can iterate over to get the values.</p> <p>If you want to check if the <code>i</code>th element returned is equal to <code>something</code>, do...
2
2016-06-27T13:57:47Z
[ "python", "python-3.x", "testing", "generator", "python-unittest" ]
Response 404, but URL is reachable from python
38,055,903
<p>I have a webcrawler, but currently the <strong>404</strong> error occurs when calling <code>requests.get(url)</code> from the requests module. But the URL is reachable.</p> <pre><code>base_url = "https://www.blogger.com/profile/" site = base_url + blogs_to_visit.pop().rsplit('/', 1)[-1] r = requests.get(site) soup ...
0
2016-06-27T13:57:52Z
38,056,098
<p>In reference to <a href="http://stackoverflow.com/questions/15233340/getting-rid-of-n-when-using-readlines">Getting rid of \n when using .readlines()</a>, perhaps use:</p> <pre><code>with open("foo") as p: return p.read().splitlines() </code></pre>
1
2016-06-27T14:06:50Z
[ "python", "web-scraping" ]
Response 404, but URL is reachable from python
38,055,903
<p>I have a webcrawler, but currently the <strong>404</strong> error occurs when calling <code>requests.get(url)</code> from the requests module. But the URL is reachable.</p> <pre><code>base_url = "https://www.blogger.com/profile/" site = base_url + blogs_to_visit.pop().rsplit('/', 1)[-1] r = requests.get(site) soup ...
0
2016-06-27T13:57:52Z
38,056,151
<p>you can use:</p> <pre><code>r = requests.get(site.strip('\n')) </code></pre> <p>instead of:</p> <pre><code>r = requests.get(site) </code></pre>
1
2016-06-27T14:09:55Z
[ "python", "web-scraping" ]
How to format comment from bold to normal with win32?
38,055,909
<p>I just added a comment to a cell in an excel file. And somehow it turned out in bold, which I don't want. What can I do to fix it?</p> <p>My code: </p> <pre><code>excel = win32.gencache.EnsureDispatch('Excel.Application') file_location = 'C:\Users\A42918\Desktop\Test_folder\Abild, T1.xls' wb = excel.Workbooks.Open...
0
2016-06-27T13:58:16Z
38,057,389
<p>For this, you need to deal with the <code>Comment</code> object. The <code>Range</code> object representing cell "AH4" is independently formatted; changing the font formatting (e.g., bold) on the cell will not have any effect on the comment.</p> <p>This should resolve it:</p> <pre><code>excel = win32.gencache.Ensu...
0
2016-06-27T15:06:07Z
[ "python", "excel" ]
How to format comment from bold to normal with win32?
38,055,909
<p>I just added a comment to a cell in an excel file. And somehow it turned out in bold, which I don't want. What can I do to fix it?</p> <p>My code: </p> <pre><code>excel = win32.gencache.EnsureDispatch('Excel.Application') file_location = 'C:\Users\A42918\Desktop\Test_folder\Abild, T1.xls' wb = excel.Workbooks.Open...
0
2016-06-27T13:58:16Z
38,185,892
<p>This solves my problem!</p> <pre><code>excel = win32.gencache.EnsureDispatch('Excel.Application') file_location = 'C:\Users\A42918\Desktop\Test_folder\Abild, T1.xls' wb = excel.Workbooks.Open(file_location) ws = wb.Worksheets("Trelindad_utan") ws.Range('AH4').Interior.ColorIndex = 37 ws.Range('AH4').Font.Bold = T...
0
2016-07-04T13:24:41Z
[ "python", "excel" ]
Hdf5 and pickle takes more space than raw csv file
38,055,935
<p>I have a csv file (containing only numeric data) of size 18 MB. When I read it and convert to numpy array and save it in hdf5 format or pickle , it takes around 48 MB disk space. Shouldn't the data be compressed when we use pickle or hdf5? Is it better to save in hdf5 format to be consumed by tensorflow ? The Csv d...
1
2016-06-27T13:59:40Z
38,068,727
<p>Numpy array for integers defaults to int64 dtype . This was the reason the data was taking more space than the original. </p> <pre><code>310584 X 20 x 8 ~= 48 MB (8 Bytes is the size for int64) </code></pre>
0
2016-06-28T06:35:50Z
[ "python", "tensorflow", "pickle", "hdf5", "h5py" ]
Is it possible to redefine the equal operator for tuples?
38,056,067
<p>I have some code in which edges are represented as tuple</p> <pre><code>(vertex_1, vertex_2) </code></pre> <p>and I have lists of edges that represent planar embedded faces, as for the example below.</p> <p>I need to search if an edge is present in the list, but I need to return true both if a use <code>(v1, v2)<...
3
2016-06-27T14:05:29Z
38,056,202
<p>You should make a tuple subclass and change it's equality method (<code>__eq__</code>):</p> <pre><code>class UnorderedTuple(tuple): def __eq__(self, other): return len(self) == len(other) and set(self) == set(other) </code></pre> <p>will work for your case with (tuple lengths == 2 if the tuple elements...
1
2016-06-27T14:12:05Z
[ "python" ]
Is it possible to redefine the equal operator for tuples?
38,056,067
<p>I have some code in which edges are represented as tuple</p> <pre><code>(vertex_1, vertex_2) </code></pre> <p>and I have lists of edges that represent planar embedded faces, as for the example below.</p> <p>I need to search if an edge is present in the list, but I need to return true both if a use <code>(v1, v2)<...
3
2016-06-27T14:05:29Z
38,056,269
<blockquote> <p>"Is it possible to redefine the equal operator for tuples"</p> </blockquote> <p>Sort of. You can't do it on the basic <code>tuple</code> type, but you can to it on a subclass:</p> <pre><code> class MyTuple(tuple): def __eq__(self, other): orig_eq = super(MyTuple, self).__eq__(other) ...
1
2016-06-27T14:15:44Z
[ "python" ]
Is it possible to redefine the equal operator for tuples?
38,056,067
<p>I have some code in which edges are represented as tuple</p> <pre><code>(vertex_1, vertex_2) </code></pre> <p>and I have lists of edges that represent planar embedded faces, as for the example below.</p> <p>I need to search if an edge is present in the list, but I need to return true both if a use <code>(v1, v2)<...
3
2016-06-27T14:05:29Z
38,056,353
<p>You cannot override the equality method for existing types, so you would have to create your own type which would then require you to replace all your existing tuples with your custom type.</p> <p>If your main problem is just the <code>(6,1) in f1</code> use case, then maybe you should just consider creating a meth...
3
2016-06-27T14:19:27Z
[ "python" ]
Is it possible to redefine the equal operator for tuples?
38,056,067
<p>I have some code in which edges are represented as tuple</p> <pre><code>(vertex_1, vertex_2) </code></pre> <p>and I have lists of edges that represent planar embedded faces, as for the example below.</p> <p>I need to search if an edge is present in the list, but I need to return true both if a use <code>(v1, v2)<...
3
2016-06-27T14:05:29Z
38,056,392
<p>like others have posted you can use class to redefine the equal operator for tuples, but still you have to use that class you have to call it, so if you have</p> <pre><code>class new_tuple: ... </code></pre> <p>than you have to use:</p> <pre><code>tuple = (1,6) tuple = new_tuple(tuple) </code></pre> <p>i thi...
0
2016-06-27T14:21:38Z
[ "python" ]
Is it possible to redefine the equal operator for tuples?
38,056,067
<p>I have some code in which edges are represented as tuple</p> <pre><code>(vertex_1, vertex_2) </code></pre> <p>and I have lists of edges that represent planar embedded faces, as for the example below.</p> <p>I need to search if an edge is present in the list, but I need to return true both if a use <code>(v1, v2)<...
3
2016-06-27T14:05:29Z
38,057,307
<p>The general solution to this problem is to use <a href="https://en.wikipedia.org/wiki/Multiset" rel="nofollow">multisets</a>, which are sets where an element may appear more than once. The <code>collections</code> module defines a <code>Counter</code> class, which is a subclass of <code>dict</code>, that implements...
0
2016-06-27T15:01:47Z
[ "python" ]
Creating Database by exporting file from XML
38,056,090
<p>My application is to read an export file in XML and produce a properly normalized database. Well The application is running and printing results as well as storing in database but in the middle an error pops out and the program halts- Note- DataSet is proper format. It is coursera Question-</p> <pre><code>I Like To...
2
2016-06-27T14:06:27Z
38,056,542
<pre><code>cur.execute('SELECT id FROM Genre WHERE name=?',(genre,)) </code></pre> <p>Returns None (nothing), so when you try to to access the first element, you get your error.</p> <p>Since you cannot be sure that there will always be a genre to be returned, it would be cleaner to wrap these things into a try.. exce...
0
2016-06-27T14:27:00Z
[ "python", "sql", "xml", "database", "sqlite" ]
Get Mime Message isn't returning a base 64 decoded version? (Gmail API)
38,056,169
<p>In my script I need to extract a set of emails that match some query. I decided to use GMail's API python client for this. Now, my understanding was that the GetMimeMessage() was supposed to return a set of <em>decoded</em> base 64 messages. Here is my code:</p> <pre><code>def GmailInput(): credentials = get_c...
1
2016-06-27T14:10:39Z
38,099,225
<p>You can use <a href="https://developers.google.com/gmail/api/v1/reference/users/messages/get" rel="nofollow"><code>User.messages:get</code></a>. This request requires <a href="https://developers.google." rel="nofollow">authorization</a> with at least one of the following scopes.</p> <p><strong>HTTP request</strong>...
0
2016-06-29T12:14:37Z
[ "python", "gmail", "base64", "gmail-api", "google-api-python-client" ]
Threading gives typeError
38,056,227
<p>Im busy with a project for my study and I keep getting this error:</p> <pre><code>Exception in thread Thread-62: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner self.run() File "/usr/lib/python2.7/threading.py", line 754, in run self.__target(*se...
1
2016-06-27T14:13:13Z
38,056,581
<pre><code>t = threading.Thread(target=r_serv.hset("_id" + str(teller), "vt", VTHandler(r_serv.hget("_id" + str(teller), "source")))) </code></pre> <p>You are calling the <code>r_serv.hset</code> function and then assigning its return value to the <code>target</code> kwarg (which is then being call...
2
2016-06-27T14:28:12Z
[ "python", "multithreading" ]
Python, search excel sheet for specific strings in a column and extract those rows to a text file
38,056,233
<p>Here's the code I've frankensteined together from other posts,</p> <pre><code>import xlrd import os.path wb = xlrd.open_workbook(os.path.join('D:\Data','SPS1 demo data.xlsx')) wb.sheet_names() sh = #? Strings=#variables i = 1 file = open("Output.txt", "w") while sh.cell(i,3).value = (Strings): file.write(#row) ...
0
2016-06-27T14:13:42Z
38,056,526
<p>This should work. You can't assign 5 strings to a single variable, without using a list or some other data type. You can however check to see if the third cell's value (i[2] - here) is equal to any of the strings you're looking for ("string1" - "string5" - here).</p> <pre><code>import xlrd sheet_data = [] wb = x...
0
2016-06-27T14:26:30Z
[ "python", "excel", "parsing" ]
Parsing sub-properties from a list of dicts in Python
38,056,305
<p>In Python (2.7), I am parsing a list of dictionaries (that come from JSON) where each dictionary has the following format (I'm using fake key names):</p> <p><code>{'k': {'p': value_i_care_about_1, 'q': value_i_care_about_2, ... (stuff I don't want)}, ... (stuff I don't want)}</code></p> <p>where <code>...</code> r...
0
2016-06-27T14:17:01Z
38,056,833
<p>If the ordering of p and q isn't important, and if k is constant across all dicts (in order to shorten the line):</p> <pre><code>key = 'k' [(d[key].values()) for d in dicts] </code></pre> <p>If the ordering in your tuple does matter you'll have to do it your way, though if the names are constant again you could sp...
0
2016-06-27T14:40:22Z
[ "python", "json", "parsing", "dictionary", "list-comprehension" ]
Parsing sub-properties from a list of dicts in Python
38,056,305
<p>In Python (2.7), I am parsing a list of dictionaries (that come from JSON) where each dictionary has the following format (I'm using fake key names):</p> <p><code>{'k': {'p': value_i_care_about_1, 'q': value_i_care_about_2, ... (stuff I don't want)}, ... (stuff I don't want)}</code></p> <p>where <code>...</code> r...
0
2016-06-27T14:17:01Z
38,056,902
<p>If I understood you correctly, you are looking for a 'Pythonic' way to get for each 'k' a list of inner values.<br> So, for this you might want to use the following code, it is not depend on a given key/keys:</p> <pre><code>json = {'k1': {'p': 'value_i_care_about_1', 'q': 'value_i_care_about_2'}, 'k2':{'p': 'value_...
0
2016-06-27T14:42:51Z
[ "python", "json", "parsing", "dictionary", "list-comprehension" ]
Parsing sub-properties from a list of dicts in Python
38,056,305
<p>In Python (2.7), I am parsing a list of dictionaries (that come from JSON) where each dictionary has the following format (I'm using fake key names):</p> <p><code>{'k': {'p': value_i_care_about_1, 'q': value_i_care_about_2, ... (stuff I don't want)}, ... (stuff I don't want)}</code></p> <p>where <code>...</code> r...
0
2016-06-27T14:17:01Z
38,057,409
<p>I know this is longer, but it has the benefit of being relatively legible and simply extendable.</p> <pre><code># you can add any combination of fields here fields = [['k', 'p'], ['k', 'q']] result = [tuple(d[level1][level2] for level1, level2 in fields) for d in dicts] </code></pre>
1
2016-06-27T15:06:59Z
[ "python", "json", "parsing", "dictionary", "list-comprehension" ]
Parsing sub-properties from a list of dicts in Python
38,056,305
<p>In Python (2.7), I am parsing a list of dictionaries (that come from JSON) where each dictionary has the following format (I'm using fake key names):</p> <p><code>{'k': {'p': value_i_care_about_1, 'q': value_i_care_about_2, ... (stuff I don't want)}, ... (stuff I don't want)}</code></p> <p>where <code>...</code> r...
0
2016-06-27T14:17:01Z
38,133,926
<p>You can DRY off with this nested list comprehension:</p> <pre><code>result = [tuple(dd[k1][k2] for k1 in ['k'] for k2 in ['p','q']) for dd in dictlist] </code></pre>
0
2016-06-30T21:58:36Z
[ "python", "json", "parsing", "dictionary", "list-comprehension" ]
Class decorator - modification of class field changes value in base class too
38,056,407
<p>I wrote a class decorator with argument. This decorator needs to set value of class field <code>ID</code>. I am doing it in following way:</p> <pre><code>class Base: ID = "ID_Base" def __init__(self, n): self.n = n def func(self): pass def Test(cnt): def createTest(className): ...
0
2016-06-27T14:22:03Z
38,057,385
<p>The reason you got <code>ID_Base_test</code> from <code>print(Derived.ID)</code> is that there is an implicit assignment in the end of the decorating, which makes <code>Derived</code> references to <code>class Derived_Test</code>. Below code</p> <pre><code>@Test(2) class Derived(Base): pass </code></pre> <p>ki...
2
2016-06-27T15:05:51Z
[ "python", "python-decorators" ]
irregular binning with regards to the sum of a column
38,056,535
<p>I would like to bin a dataframe in pandas based on the sum of another column. </p> <p>I have the following dataframe: </p> <pre><code>time variable frequency 2 7 7 3 12 2 4 13 3 6 15 4 6 18 4 6 3 1 10 ...
0
2016-06-27T14:26:44Z
38,057,331
<p>A little brute force would get you a long way.</p> <pre><code>import numpy as np data = ((2, 7, 7), (3, 12, 2), (4, 13, 3), (6, 15, 4), (6, 18, 4), (6, 3, 1), (10, 21, 2), (11, 4, 5), (13, 6, 5), (15, 17, 6), (17, 5, 4)) freq = [data[...
0
2016-06-27T15:02:58Z
[ "python", "pandas", "dataframe", "binning" ]