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
Sudden reference warning in PyCharm
37,550,356
<p>Basically I have been using PyCharm for awhile now, and I have been working with some code. I was showing this code to some team mates of mine, and then when I opened up the code again when I got back to my desk I had some reference warnings:</p> <p><a href="http://i.stack.imgur.com/EMHsA.png" rel="nofollow"><img s...
0
2016-05-31T15:52:50Z
37,550,896
<p>This is a common error in most of the <a href="/questions/tagged/jetbrain-ide" class="post-tag" title="show questions tagged &#39;jetbrain-ide&#39;" rel="tag">jetbrain-ide</a>s and <a href="/questions/tagged/android-studio" class="post-tag" title="show questions tagged &#39;android-studio&#39;" rel="tag"><img src="/...
0
2016-05-31T16:18:47Z
[ "python", "pygame", "pycharm" ]
Kivy application lifecycle (widget duplicating itself on each redraw)
37,550,363
<p>I've been looking at Kivy as a way of dynamically drawing widgets driven from a web API hosted in the same application. I'm still very new to the topic and I've run into a problem with the lifecycle of the Kivy framework. In summary what I'm trying to achieve is to send a kv string using an API call which is setup u...
0
2016-05-31T15:53:18Z
37,550,582
<p>Your kv file includes both a root widget and a normal kv rule, so every time you load it you add another identical rule to the CountdownTimer. All of these identical rules are applied, one after the other, when it's instantiated.</p> <p>Instead, put the kv for the widget you want to load into its own file (or just ...
0
2016-05-31T16:03:43Z
[ "python", "python-2.7", "kivy", "kivy-language" ]
Calling "return render" won't work when calling from an outside method (Django, views.py)
37,550,402
<p>Very first question here.</p> <p>I am having trouble creating a reusable method to use in my views.py file for handling user authentication. I have created and imported a utils.py file that looks like this:</p> <pre><code>from django.shortcuts import render from django.contrib.auth.forms import AuthenticationForm ...
0
2016-05-31T15:55:18Z
37,550,548
<p>If you return from <code>check_log_in()</code> but do nothing with the returned value, execution of your <code>new()</code> view is going to continue.</p> <p>You need to check if <code>check_log_in()</code> returned something and if it did, return that from your <code>new()</code> view:</p> <pre><code>def new(requ...
1
2016-05-31T16:02:10Z
[ "python", "django" ]
CSV partitioning, map and filter with spark
37,550,429
<p>I'm having some problems with spark in order to filter big data files.</p> <p>Having a matrix of NxM dimensions (excluding headers and other tags) inside a CSV file, I need to filter each column resulting in the number of the row if the filtering function is true.</p> <p>Firstly, I load the file with databricks pa...
0
2016-05-31T15:56:35Z
37,551,302
<p>If you load data with an integer schema, you can use a sum it will be more efficient than string comparisons.</p> <pre><code>sc.textFile(yourfile).map(lambda line: [int(x) for x in line.split(";")]) </code></pre>
0
2016-05-31T16:41:38Z
[ "python", "csv", "apache-spark", "pyspark" ]
Show mail sent through SMTP server in my IMAP "Sent" mailbox
37,550,483
<p>I am able to send a mail using a SMTP server:</p> <pre><code>self.smtp_connection.sendmail( 'my_smtp_username@provider.com', recipients, # list of To, Cc and Bcc mails mime_message.as_string() ) </code></pre> <p>But I can't see the mail sent in the "Sent" box in the 'my_smtp_username@provider.com' IMA...
0
2016-05-31T15:58:57Z
37,550,484
<p>The SMTP and IMAP protocols are <strong>two distincts things</strong>: mails sent through the SMTP server are not visible by the IMAP one.</p> <p>Thus, you need to simulate this behaviour yourself, by sending the mail to your own address (but without adding you in the "To:" header of the MIME object) and then move ...
1
2016-05-31T15:58:57Z
[ "python", "smtplib", "imaplib" ]
Python Pinging -t
37,550,487
<p>I have a batch program that simply pings in loop with 'ping adress -t'. Adress being whatever I'm trying to ping at the time.</p> <p>I'd like to do something similiar with python, but without the popup of a command prompt window and thus I'd like to avoid anything that would do this. I want a way to print it ONLY t...
-1
2016-05-31T15:59:14Z
37,550,535
<p>What about:</p> <pre><code>import subprocess subprocess.call(["ping", "-t"]) </code></pre>
0
2016-05-31T16:01:45Z
[ "python" ]
AND query in elasticsearch python
37,550,617
<p>Records Stored in Elasticsearch:</p> <pre><code>"hits" : [ { "_index" : "test", "_type" : "test_doc", "_id" : "AVUHBSESPB1nLi5k2Dxp", "_score" : 1.0, "_source":{"valid": true,"action_taken": false} }, { "_index" : "test", "_type" : "test_doc", "_id" : "AVUHBI1IPB1...
1
2016-05-31T16:05:08Z
37,557,015
<p>The request you're sending to ElasticSearch doesn't look like a valid query. ES requires queries to be formatted in a specific way:</p> <pre><code>"query": { "match": { "content": term } } </code></pre> <p>Based on this, I believe your need to change the <code>q</code> param.</p> <p>For ElasticSea...
1
2016-05-31T23:02:44Z
[ "python", "python-2.7", "elasticsearch" ]
How to use the resample.sum() method of the Dataframe with irregular timestamps while doing an interpolation in the overlaps?
37,550,680
<p>I have a set of data set like below. It has a start time and end time. For each row, there are corespondent values.</p> <pre><code>Block_start Block_end Total Coal Waste 01/20/2016 5:00 01/20/2016 5:23 1284 0 1284 01/20/2016 5:23 01/20/2016 6:44 5755 0 5755 01/20/2016 6:...
0
2016-05-31T16:07:43Z
37,551,892
<p>Not sure about the desired outcome, but I believe if you just want to get the interpolation between value for a desired range, there is no need to do a sum.</p> <p>Starting with this DataFrame (make sure Block_end is your DatetimeIndex)</p> <pre><code>df Out[175]: Block_start Total Coa...
0
2016-05-31T17:16:45Z
[ "python", "pandas", "dataframe", "interpolation", "resampling" ]
Buildozer Android Kivy Fail on importing requirement
37,550,690
<p>I have tried to import a python module on a kivy app for android, anyway whenever i add a requirement in buildozer.spec the build fails out putting this:</p> <pre><code># Run 'pip install --download-cache=/home/arctia/.buildozer/cache --target=/home/arctia/Scrivania/Kivy/Programs/Domo_Skills/.buildozer/applibs open...
1
2016-05-31T16:08:17Z
37,550,810
<p>Make sure your buildozer and python-for-android are up to date, this is fixed in the master branches. For buildozer, you should be able to get the latest stable release. For python-for-android, delete the .buildozer directory in your build dir and run buildozer again, it should fetch the newest version.</p>
1
2016-05-31T16:14:10Z
[ "android", "python", "pip", "kivy", "buildozer" ]
Python: TypeError: __init__() takes exactly 5 arguments (6 given)
37,550,715
<p>I've been having this issue with this code, and I'm not sure why I'm still getting this TypeError here. I have the following Animal class, which is the base class for the Dog class defined below it. I want to create a Dog object which inherits from this Animal class.</p> <p>Here's the Animal class:</p> <pre><code>...
0
2016-05-31T16:09:33Z
37,550,782
<p>Problem lays in <code>__init__</code> method of superclass. <code>super()</code> call implicitly passes <code>self</code> as first argument. Simply use:</p> <pre><code>def __init__(self, name, height, weight, sound, owner): self.__owner = owner super(Dog, self).__init__(name, height, weight, sound) </code><...
2
2016-05-31T16:13:13Z
[ "python", "class", "inheritance" ]
python optimal way to write dict into html table
37,550,928
<p>I m a python beginner and I'm trying to learn how to do this the optimal way. I have a list composed by few dicts. I have a fuction to search a value, and return the whole dict if found. # I m not so proud of my else as well... It will then print a table with containing a column with the keys and one with the value...
0
2016-05-31T16:20:24Z
37,551,942
<p>Since you seem to be looking for code suggestions here are mine:</p> <p>1) Don't define your data structure across multiple variables, use a single compound data structure;</p> <p>2) Don't write the raw HTML yourself, use one of the many Python HTML helper modules.</p> <p>Combining my suggestions above, I come up...
1
2016-05-31T17:19:24Z
[ "python", "html", "list", "dictionary" ]
Extracting parts of JSON from json.loads list in python
37,550,934
<p>I have ~100k JSON files, each containing JSON which I am looping through to create a bag of words model - very simple. Each JSON file looks like this:</p> <pre><code>[{"tokens":[{"word":"Voices","lemma":"voice","pos":"NNS","ner":"O"},{"word":"from","lemma":"from","pos":"IN","ner":"O"},{"word":"Russia","lemma":"Russ...
0
2016-05-31T16:20:41Z
37,551,112
<p>with d=[{'tokens': [{'lemma': 'voice', 'ner': 'O', 'word': 'Voices', 'pos': 'NNS'}, {'lemma': 'from', 'ner': 'O', 'word': 'from', 'pos': 'IN'}, {'lemma': 'Russia', 'ner': 'LOCATION', 'word': 'Russia', 'pos': 'NNP'}], 'dependencies': [{'dep': 2, 'head': 0, 'label': 'prep_from'}]}]</p> <p>this worked for me</p> ...
1
2016-05-31T16:31:26Z
[ "python", "arrays", "json", "dictionary", "nlp" ]
Python reading from file into list then use line as list too and reach each char
37,551,121
<p>I want to read a line from a file and make operation on specific char on that line. I read line as in <a href="http://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list-with-python">link on stackoverflow</a></p> <p>But there is a problem for me because I want to reach every single char ...
0
2016-05-31T16:32:14Z
37,551,286
<p>each <code>kelime</code> it's a list. you should do:</p> <pre><code>harf = kelime[0][2:5] </code></pre>
1
2016-05-31T16:40:44Z
[ "python", "list", "file", "python-3.x", "io" ]
Python reading from file into list then use line as list too and reach each char
37,551,121
<p>I want to read a line from a file and make operation on specific char on that line. I read line as in <a href="http://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list-with-python">link on stackoverflow</a></p> <p>But there is a problem for me because I want to reach every single char ...
0
2016-05-31T16:32:14Z
37,551,307
<p><code>kelime</code> is a one-element <code>list</code> where the sole element is a <code>str</code> containing the first line. But you're manipulating it as if you expect it to be a <code>str</code> (or a <code>list</code> of the individual characters).</p> <p>If you want a <code>str</code>, use:</p> <pre><code>ke...
2
2016-05-31T16:41:51Z
[ "python", "list", "file", "python-3.x", "io" ]
Serving python CGI script with Apache2
37,551,222
<p>I'm trying to call a Python script from a webpage, and apache2 is not actioning the script. The files are:</p> <p><strong>test.py</strong></p> <pre><code>#!/usr/bin/env python print "Content-type: text/html\n\n" print "&lt;h1&gt;Hello World&lt;/h1&gt;" </code></pre> <p><strong>index.html</strong></p> <pre><code...
0
2016-05-31T16:37:12Z
37,552,065
<p>As discussed in the comments. This directory configuration looks like a plain copy from an example, and your Web root is probably somewhere else. </p> <pre><code>&lt;VirtualHost *:80&gt; &lt;directory "/var/www/htdocs"&gt; AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwner...
0
2016-05-31T17:26:10Z
[ "python", "apache2", "cgi" ]
How To Skip Functions?
37,551,263
<p>I have this piece of code below. When / If the program arrives at the <code>if</code> statement: <code>if stocklevel &lt; 1:</code>, I need to move straight to the <code>repeat</code> function.</p> <pre><code>def checkstocklevel(code): with open('stockcontrol.csv',newline='') as f: for line in f: if cod...
1
2016-05-31T16:39:27Z
37,551,423
<p>You're going to have to change your design a bit. You're telling the code to run each of the steps no matter what, so after the repeat function ends the code will still perform all the other steps. One way to fix this is to move the stock level if statement out of the function, ie:</p> <pre><code>while repeatchoice...
1
2016-05-31T16:48:33Z
[ "python", "function" ]
How To Skip Functions?
37,551,263
<p>I have this piece of code below. When / If the program arrives at the <code>if</code> statement: <code>if stocklevel &lt; 1:</code>, I need to move straight to the <code>repeat</code> function.</p> <pre><code>def checkstocklevel(code): with open('stockcontrol.csv',newline='') as f: for line in f: if cod...
1
2016-05-31T16:39:27Z
37,551,435
<p>You can let your <code>checkstockLevel</code> function (which I'm guessing the first code snippet is from) return a boolean value (maybe in addition to what it is already returning) and then work with that. So something like this:</p> <pre><code>def checkstocklevel(socklevel): #maybe do something (I don't know ...
1
2016-05-31T16:49:09Z
[ "python", "function" ]
scan function in theano, recurrent neural net
37,551,270
<p>I've been trying to use scan in theano for implementing a RNN (the example is adapted from here: <a href="https://github.com/valentin012/conspeech/blob/master/rnn_theano.py" rel="nofollow">https://github.com/valentin012/conspeech/blob/master/rnn_theano.py</a>)</p> <pre><code>def forward_prop_step(x_t, s_t_prev, U, ...
0
2016-05-31T16:39:33Z
37,555,106
<p>Form the implementation is not clear to tell what's wrong in your code. Could you check the line here </p> <pre><code>o_t = T.nnet.softmax(T.dot(o_t_prev,Q)+T.dot(s_t,V)) </code></pre> <p>what is Q dimension and if it is applicable to be added to <code>s_t</code></p>
0
2016-05-31T20:30:47Z
[ "python", "theano", "recurrent-neural-network" ]
Building Json with string interpolation in python
37,551,359
<p>I have the following :</p> <pre><code> max_id = 10 for i in range(max_id): payload = "{\"text\": R%s,\"count\":\"1 \",}" %(i) print(payload) </code></pre> <p>I want to iterate through this , and have the value of the json payload be set to "R1", "R2" ... Upon debugging the output is:</p> <p...
0
2016-05-31T16:44:49Z
37,551,417
<p>Don't do this with string interpolation. Use an actual JSON dumper:</p> <pre><code>import json payload = json.dumps({"text": 'R'+str(i), "count": "1 "}) </code></pre> <p>If you really wanted to do it with string interpolation, you could add the missing quotes to the format string, but it's not a good habit to get ...
4
2016-05-31T16:48:18Z
[ "python", "json" ]
Python 3.5.1: How Do You Convert Each Number In A List To Tuples After They Were Appended To That List?
37,551,438
<p>How I can convert each item in a list into tuples after they were appended to that list? I have this list:</p> <pre><code>Cards = [] </code></pre> <p>I want to append 100 cards to the Card list without having to do this:</p> <pre><code>Card = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,...] </code></pre> <p>So I did ...
0
2016-05-31T16:49:17Z
37,551,499
<p>Try a list comprehension for fast and pythonic list of single element tuples:</p> <pre><code>Cards = [(i,) for i in range(1, 101)] </code></pre> <p>Sample session:</p> <pre><code>&gt;&gt;&gt; Cards = [(i,) for i in range(1, 101)] &gt;&gt;&gt; Cards [(1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,), (10,), (11...
3
2016-05-31T16:52:50Z
[ "python", "list", "tuples", "python-3.5" ]
Python 3.5.1: How Do You Convert Each Number In A List To Tuples After They Were Appended To That List?
37,551,438
<p>How I can convert each item in a list into tuples after they were appended to that list? I have this list:</p> <pre><code>Cards = [] </code></pre> <p>I want to append 100 cards to the Card list without having to do this:</p> <pre><code>Card = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,...] </code></pre> <p>So I did ...
0
2016-05-31T16:49:17Z
37,551,502
<p>Try this:</p> <pre><code>Cards = [] for i in range(1, 101): Cards.append((i,)) </code></pre> <p>Note that a tuple is usually 2 items, so when you print the array there will be an extra comma. Might be better to use a 1 dimensional array instead, ie:</p> <pre><code>Cards.append([i]) </code></pre>
2
2016-05-31T16:52:59Z
[ "python", "list", "tuples", "python-3.5" ]
Imported var on python/Django it's empty
37,551,463
<p>I'm new with Django and I'm trying to access a varible from other file. But I don't get his value. I don't use DJango auth system, I log in to an IDP and the IDP send back the tokenId, uid plus some more data.</p> <p>On the fileA.py I have:</p> <pre><code>......... tokenId = '' ......... def validateToken(tokenId)...
2
2016-05-31T16:50:36Z
37,552,766
<p>Thanks to Daniel Roseman to give me the hint of use sessions. I have solved my problem.</p> <p>On fileA I added:</p> <pre><code>def login(request): ........... global tokenId &lt;-------- deteled tokenId = value/returned/from/server request.session['tokenId'] = tokenId &lt;-------- added return ...
0
2016-05-31T18:08:38Z
[ "python", "django", "import" ]
Is there a way to calculate similarity between one sparse vector and matrix?
37,551,487
<p>How to calculate the (e.g., cosine) similarity between one sparse vector and a matrix (i.e., an array of sparse vectors)? <br> Is this possible using scikit-learn, scipy, numpy, etc.? If possible, the similarity metric should be easily changeable.</p>
0
2016-05-31T16:52:05Z
37,554,731
<p>If you are interested in calculating the cosine similarity, it can be done by using <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.pairwise_distances.html#sklearn.metrics.pairwise.pairwise_distances" rel="nofollow"><code>cosine-similarity</code></a> metric functionality present in...
0
2016-05-31T20:06:03Z
[ "python", "numpy", "scipy", "scikit-learn", "sparse-matrix" ]
Repeated addition of line when using for-else loop
37,551,515
<p>I have a function</p> <pre><code>def static_nat_fwsm_check(mapped_to_real_address_pairs,FWSM_ACLs): amended_static_nat_acl=[] for acl_line in FWSM_ACLs: for i,j in mapped_to_real_address_pairs: if j in acl_line: amended_static_nat_acl.append('!STATIC NAT SUBSTITUTION FOR '+acl_line) am...
0
2016-05-31T16:53:58Z
37,566,802
<p>User error. I used a previous function to generate input for this function. Loosely defined regex, plus an ACL name that was a subset of other ACL names caused the duplicate output.</p>
0
2016-06-01T11:02:02Z
[ "python", "tuples", "for-else" ]
How to know when a program finished when they run in background?
37,551,691
<p>I'm using ArcGIS 10.2 to create an interface. I'm using Python 2.7 to call and run Gams in background using</p> <pre><code>import subprocess subprocess.check_call([r"C:\GAMS\win64\24.4\gamside.exe",r"C:\Users\sofia\Downloads\file_name.gms"]) </code></pre> <p>After gams runs, it exports excel files and I need a way...
-1
2016-05-31T17:03:17Z
37,551,760
<p>From the <a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow">manual</a>:</p> <blockquote> <p><strong>subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)</strong> </p> <p>Run command with arguments. Wait for command to complete. If the return code was zer...
1
2016-05-31T17:07:38Z
[ "python", "python-2.7", "subprocess", "arcgis", "arcpy" ]
Correcting an old python code for creating Image
37,551,722
<p>as the title suggest, I have here an old piece of python code that was working in the previous version (2.7) but isn't anymore. The code defines a function that creates, from a given array containing 0, 1 and 2 only, an RGB image with the three colors in the "colors" RGB tuples array. Here's the code :</p> <pre><co...
-4
2016-05-31T17:05:02Z
37,552,419
<p>As mentioned above, Python 3 strings are Unicode strings (whereas Python 2 strings are bytearrays). Since the interpreter can't convert a 'bytes' object to a str <em>implicitly</em>, do it <em>explicitly</em>.</p>
0
2016-05-31T17:46:57Z
[ "python", "python-2.7", "python-3.x" ]
Correcting an old python code for creating Image
37,551,722
<p>as the title suggest, I have here an old piece of python code that was working in the previous version (2.7) but isn't anymore. The code defines a function that creates, from a given array containing 0, 1 and 2 only, an RGB image with the three colors in the "colors" RGB tuples array. Here's the code :</p> <pre><co...
-4
2016-05-31T17:05:02Z
37,552,885
<p>Normal strings in Python 2 are simple byte strings, but in Python 3 they are Unicode strings. So to do this sort of byte-level manipulation in Python 3 you can't use normal strings, you need to use the Python 3 <code>bytes</code> object; there is also a <code>bytearray</code> object that is useful for these sorts of...
0
2016-05-31T18:15:59Z
[ "python", "python-2.7", "python-3.x" ]
How to send multiple messages to eventhub using python
37,551,807
<p>I already send batch messages using C# libs. I want to do the same thing using python, how to do it? Actually I'm able to send single messages but batch send will increase my throughtput. This is the code:</p> <pre><code>from azure.servicebus import ServiceBusService key_name = 'RootManageSharedAccessKey' # Share...
0
2016-05-31T17:10:49Z
37,558,418
<p>Try to replace the event content with the format like this, </p> <p><code>[{"Body":"Message1"},{"Body":"Message2"},{"Body":"Message3"}]</code></p> <p>So the complete code will be like this,</p> <pre><code>from azure.servicebus import ServiceBusService key_name = 'RootManageSharedAccessKey' # SharedAccessKeyName ...
2
2016-06-01T02:22:40Z
[ "python", "azure", "azure-eventhub" ]
Why does my word counter output the line ` 1`?
37,551,845
<p>Do you know why do I have a "1" printed in the second row of output?</p> <pre><code>def word_map(string): dict = {} for word in string.split(): word = filter(str.isalnum, word).lower() word = word.split() if word in dict: dict[word] +=1 else: dict[word...
2
2016-05-31T17:13:30Z
37,551,885
<p>Because one of the elements of the split is <code>','</code> which gets filtered to <code>''</code>.</p> <p>So you're doing <code>dict[''] = 1</code>.</p> <p>Assuming you're trying to count the words in a sentence, you need to either check if the word is valid after you filter it, or while you're printing. For exa...
5
2016-05-31T17:16:30Z
[ "python", "string", "dictionary" ]
Why does my word counter output the line ` 1`?
37,551,845
<p>Do you know why do I have a "1" printed in the second row of output?</p> <pre><code>def word_map(string): dict = {} for word in string.split(): word = filter(str.isalnum, word).lower() word = word.split() if word in dict: dict[word] +=1 else: dict[word...
2
2016-05-31T17:13:30Z
37,551,911
<p>I think it is being printed for ",". You have total 10 words including "," (let us consider "," as a word). So if you see all the counts, that should give the answer.</p>
0
2016-05-31T17:17:49Z
[ "python", "string", "dictionary" ]
Why does my word counter output the line ` 1`?
37,551,845
<p>Do you know why do I have a "1" printed in the second row of output?</p> <pre><code>def word_map(string): dict = {} for word in string.split(): word = filter(str.isalnum, word).lower() word = word.split() if word in dict: dict[word] +=1 else: dict[word...
2
2016-05-31T17:13:30Z
37,552,165
<p>The following solution also works:</p> <pre><code>def word_map(string): word_dict = {} for word in string.split(): word = filter(str.isalnum, word).lower() word = word.strip() if word != '': if word in word_dict.keys(): word_dict[word] +=1 else...
0
2016-05-31T17:32:10Z
[ "python", "string", "dictionary" ]
Turn Every 2 rows of Dataframe into 1 row x 2 columns
37,551,890
<p>I have a Dataframe (df) that looks like this:</p> <pre><code> date ID Team P F T TO 0 20160101 537 Bobcats 5 10 0 3 1 20160101 538 Spartans8 10 1 4 2 20160101 539 Tigers 7 8 2 3 3 20160101 540 Vikings 10 5 0 1 4 20160101 541 Smurfs 5 3 0 2 5 ...
0
2016-05-31T17:16:38Z
37,552,220
<p>One way to do it is just to figure out the opponent for each team and then merge the table to itself. I'm assuming based on your example that ID 2n-1 played against ID 2n. If that's not true, adjust this accordingly (e.g. you can compute the opponent based on the index).</p> <pre><code>D['ID_opp']=D['ID'].apply(lam...
1
2016-05-31T17:35:20Z
[ "python", "pandas" ]
It displays that one of my variables is not defined when from what i can see it is
37,551,893
<p>This is the error which comes up:</p> <pre><code>What type of device is it?phone What make of phone is it? [Iphone, Samsung or other]samsung Traceback (most recent call last): File "C:\Users\Chris\Documents\Chris\School\School\computing\task 3 testing.py", line 79, in &lt;module&gt; if ('4') in model_iphone: ...
-4
2016-05-31T17:16:47Z
37,552,764
<p>It's kind of hard to follow what's going on in your code, but from what I can see, it looks like you're never making the variable <code>model_iphone</code>. Instead it seems like, since you're inputting "samsung", the code is making a variable called <code>model_samsung</code>, which does the same thing. Instead of ...
2
2016-05-31T18:08:08Z
[ "python" ]
B-splines with Scipy : can I add a datapoint without full recompute?
37,552,035
<p>I have a bspline created with scipy.interpolate.splrep with points (x_0,y_0) to (x_n,y_n). Usual story. But I would like to add a data point (x_n+1,y_n+1) and appropriate knot without recomputing the entire spline. Can anyone think of a way of doing this elegantly? </p> <p>I could always take the knot list returned...
0
2016-05-31T17:24:28Z
37,553,823
<p>Short answer: No.</p> <p>Spline construction is a global process, so if you add a data point, you really need to recompute the whole spline. Which involves solving an N-by-N linear system etc. </p> <p>If you're adding many knots sequentially, you probably can construct a process where you're using a factorization ...
0
2016-05-31T19:11:26Z
[ "python", "numpy", "scipy", "bspline" ]
Convert a RDD of Tuples of Varying Sizes to a DataFrame in Spark
37,552,052
<p>I am having difficulty in converting an RDD of the follwing structure to a dataframe in spark using python.</p> <pre><code>df1=[['usr1',('itm1',2),('itm3',3)], ['usr2',('itm2',3), ('itm3',5),(itm22,6)]] </code></pre> <p>After converting, my dataframe should look like the following:</p> <pre><code> usr1 usr...
0
2016-05-31T17:25:33Z
37,554,299
<p>With data like this:</p> <pre><code>rdd = sc.parallelize([ ['usr1',('itm1',2),('itm3',3)], ['usr2',('itm2',3), ('itm3',5),('itm22',6)] ]) </code></pre> <p>flatten the records:</p> <pre><code>def to_record(kvs): user, *vs = kvs # For Python 2.x use standard indexing / splicing for item, value in vs: ...
2
2016-05-31T19:39:52Z
[ "python", "apache-spark", "tuples", "pyspark" ]
How to copy a file to the memory in Python on Windows
37,552,092
<p>I made a desktop app on Python and I need to give the user the ability to copy files shown on the app window , <strong>not windows explorer</strong> , so they can paste them where they desire.</p> <p>Just like the <em>"right click and copy"</em> or <em>"ctrl+V"</em> in Windows. I've only found a python function for...
0
2016-05-31T17:27:23Z
37,558,499
<p>The clipboard format that you need is <a href="https://msdn.microsoft.com/en-us/library/bb776902#CF_HDROP" rel="nofollow"><code>CF_HDROP</code></a>. For example:</p> <pre><code>import ctypes from ctypes import wintypes import pythoncom import win32clipboard class DROPFILES(ctypes.Structure): _fields_ = (('pFil...
1
2016-06-01T02:35:03Z
[ "python", "windows", "memory", "copy-paste" ]
Multiple Subprocesses Printing to File
37,552,194
<p>I currently have a problem when using two subprocesses (I will add more when I get this fixed) to print to a file. Im getting the sum from awk and now i'm trying to print it to a file and its not printing right. Im using Python 2.6 and there is no way to upgrade. I am closing my files at the end of my program too, s...
0
2016-05-31T17:33:34Z
37,552,608
<p>You need to make sure you're not writing to the file the same time the started process is. To do so, make sure to flush the file before starting a process, and to wait for the process to finish before writing to it again.</p> <pre><code>with open("SomeFileName.%s" % strDateForm, 'w+') as search_file: search_fi...
0
2016-05-31T17:58:52Z
[ "python", "subprocess" ]
selenium losses sessions when going to a new page
37,552,298
<p>I am using the following to sign in and then go to the page. the code signs me in fine but when i go to the new page the sessions on the logged in user are lost.</p> <p>I how can solve this?</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys import time browser = webdrive...
1
2016-05-31T17:39:29Z
37,552,456
<p>I think you are <em>not waiting for the form submission to be completed</em>. You should look into using <a href="http://selenium-python.readthedocs.org/waits.html#explicit-waits" rel="nofollow"><code>WebDriverWait</code> and a set of built-in expected conditions</a> to wait for the form submission results.</p>
2
2016-05-31T17:49:09Z
[ "python", "selenium", "selenium-webdriver" ]
Sanitized input for subprocess with shell=True in python
37,552,338
<p>I have python script, which has code.</p> <pre><code>... ... p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) output, error = p.communicate() ... ... </code></pre> <p>When I run <a href="https://github.com/openstack...
0
2016-05-31T17:42:10Z
37,634,075
<blockquote> <p>So, user enter command which he want to run</p> </blockquote> <p>If the user already may run any command including <code>bash</code> then the <code>bandit</code> 's warning about <code>shell=True</code> is not applicable.</p> <p>The warning would make sense if the user were allowed only to choose so...
1
2016-06-04T19:14:47Z
[ "python", "shell", "subprocess", "openstack", "popen" ]
Display website in browser after submitting a form using Python
37,552,378
<p>I'm looking to use Python (working in 2.7) to:</p> <ol> <li>Open a website (specifically <a href="http://nunuku.caltech.edu/cgi-bin/getcssconedb_release_img.cgi" rel="nofollow">http://nunuku.caltech.edu/cgi-bin/getcssconedb_release_img.cgi</a>).</li> <li>Input form data on that page based on strings the Python scri...
1
2016-05-31T17:44:15Z
37,555,057
<p>As I can see You are intrested in displaying page with values not just getting the data for sent request. Your's idea isn't bad, but mechanize as You see isn't using any of actual Browser instance. Mechanize is </p> <blockquote> <p>programmatic web browsing</p> </blockquote> <p>And I'm guessing you are looking ...
2
2016-05-31T20:27:37Z
[ "python", "python-2.7", "mechanize" ]
Can't find element by id in IE
37,552,451
<p>I'm trying to use Selenium to do some scraping. The following code works great in the Firefox driver, but not in the IE driver. </p> <pre><code>from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait username = 'test@example.com' browser = webdriver.Ie() browser.wait = WebDriverWait...
0
2016-05-31T17:48:57Z
37,552,708
<p>Can you try using </p> <pre class="lang-py prettyprint-override"><code>browser.execute_script("document.getElementById('email').value='test@test.com'") </code></pre>
-1
2016-05-31T18:04:44Z
[ "python", "selenium", "web-scraping" ]
python android module does not work
37,552,503
<p>I am making an app with pgs4a but the app crashes just after the loading screen. I ran adb logcat and it came up with the error:</p> <pre><code>AttributeError: 'module' object has no attribute 'map_key' </code></pre> <p>If I remove all the lines that refer to the android module the app works but obviously you cann...
0
2016-05-31T17:52:35Z
37,763,902
<p>I am using RAPT not pgs4a and they use different methods for mapping keys. See <a href="https://github.com/renpytom/rapt-pygame-example/blob/master/main.py" rel="nofollow">RAPT documentation</a>.</p>
0
2016-06-11T12:47:19Z
[ "android", "python", "python-2.7" ]
Issue with saving dynamic model object in Django (with djano-tenant-schema)
37,552,545
<p>I am having issue in dynamically generating user for my Django app, where I'm using the django-tenant-schemas for multi tenancy.</p> <p>Following is my views snippet:</p> <pre><code>def RegisterView(request): if request.method == 'POST': response_data = {} domain = request.POST.get('domain') schema = r...
0
2016-05-31T17:55:10Z
37,553,495
<p>That's probably happening because you are instantiating your <strong>Client</strong> model on your <strong>client</strong> variable but instead of using the instance of the class, you are assigning the data directly to the Class. You should save() your object and not the Class itself (as you can see <a href="https:/...
0
2016-05-31T18:51:48Z
[ "python", "django", "dynamic", "model", "multi-tenant" ]
Access to a specific table in html tag
37,552,550
<p>I am going to use beautifulsoup to find a table that defined in the “content logical definition” in the following links: </p> <pre><code>1) https://www.hl7.org/fhir/valueset-account-status.html 2) https://www.hl7.org/fhir/valueset-activity-reason.html 3) https://www.hl7.org/fhir/valueset-age-units.html </code...
0
2016-05-31T17:55:29Z
37,555,942
<p>It looks like the problem with alecxe's code is that it returns a table that is a direct sibling of h2, but the one you want is actually within a div (which is h2's sibling). This worked for me:</p> <pre><code>import requests from bs4 import BeautifulSoup urls = [ 'https://www.hl7.org/fhir/valueset-account-sta...
0
2016-05-31T21:29:24Z
[ "python", "html", "mysql", "beautifulsoup", "bs4" ]
Python Regex for finding the name and the following numbers multiple times
37,552,620
<p>I need to parse an output text file that has a lot of information, specifically about weighing and calibrating masses. There is a data table in this text file that has the name of the mass being tested, its nominal weight, density, and other properties of the mass. </p> <p><a href="http://i.stack.imgur.com/r7nxF.pn...
0
2016-05-31T17:59:56Z
37,553,478
<p>You will need to loop through your file and process each line of input but this should work. Let me know if it does not, along with some real data.txt. You can add more groups to this and make them optional by placing a + at the end of the group to handle additional columns of data.</p> <pre><code>import re p = re...
0
2016-05-31T18:51:10Z
[ "python", "regex", "parsing" ]
Double parameterization
37,552,629
<p>So I have a set of tests where I'd like to test multiple versions of a solution. Currently I have </p> <pre><code>import pytest import product_not_at_index functions_to_test = [ product_not_at_index.product_not_at_index_n_squared, product_not_at_index.product_not_at_index, ] def run_test(function_input,...
1
2016-05-31T18:00:23Z
37,552,630
<p>The solution I ended up using is this one</p> <pre><code>import pytest import product_not_at_index functions_to_test = [product_not_at_index.product_not_at_index_n_squared] test_data = [ ([], []), ([1], [1]), ([1, 1], [1, 1]), ([1, 7, 3, 4], [84, 12, 28, 21]), ] # TODO: turn into a list compreh...
1
2016-05-31T18:00:23Z
[ "python", "unit-testing", "py.test" ]
Run python code from a certain point
37,552,632
<p>I am going some data analysis with python, and it involves reading data at the beginning of the script. I am currently debugging it, and it is cumbersome to wait for the data file to read each time. Is there any way that I can do something similar to a breakpoint which python will not need to read the data each time...
-4
2016-05-31T18:00:29Z
37,552,873
<p>It sounds from your question like you have some lines at the beginning of a script which you do not want to process each time you run the script. That particular scenario is not really something that makes a lot of sense from a scripting point of view. Scripts are read from the top down unless you call a function or...
0
2016-05-31T18:15:39Z
[ "python", "python-3.x" ]
How can I recursively find the *directories* containing a file of a certain type?
37,552,695
<p>I have a set of .bam, files scattered inside a tree of folders. Not every directory contains such a file. I know how to recursively get the path of the files themselves using glob, but not the directory containing them.</p> <pre><code>import glob2 bam_files = glob2.glob('/data2/**/*.bam') print bam_files </code><...
3
2016-05-31T18:03:45Z
37,552,814
<p>Use a set and <code>os.path.dirname()</code> [<a href="https://docs.python.org/2/library/os.path.html#os.path.dirname]" rel="nofollow">https://docs.python.org/2/library/os.path.html#os.path.dirname]</a>:</p> <pre><code>import glob2 import os bam_dirs = {os.path.dirname(p) for p in glob2.glob('/data2/**/*.bam')} pr...
4
2016-05-31T18:11:26Z
[ "python", "glob" ]
Django REST replace empty to default
37,552,699
<p>I have a Django REST API set up and it works properly for valid incoming requests. In some of the requests, some of the fields are empty. Is there a way to provide default replacement values for those empty fields in the serializer, so that they would pass the validation test? For example, I have the following seria...
0
2016-05-31T18:03:57Z
37,553,217
<p>You are having this error because <code>0</code> is not decimal. Try <code>default=0.0</code> or <code>default=None</code></p> <p><strong>Update</strong></p> <blockquote> <p>An example incomplete request would look like:</p> <pre><code>[{"myfield0":3, "myfield1":""}, {"myfield0":4, "myfield1":5}] </code></pre> ...
1
2016-05-31T18:36:27Z
[ "python", "django", "django-rest-framework" ]
Subtracting Two Columns with a Groupby in Pandas
37,552,727
<p>I have a <code>dataframe</code> and would like to subtract two columns of the previous row, provided that the previous row has the same <code>Name</code> value. If it does not, then I would like it yield <code>NAN</code> and fill with <code>-</code>. My <code>groupby</code> expression yields the error, <code>TypeErr...
2
2016-05-31T18:05:55Z
37,552,768
<p>You can add <code>lambda x</code> and change <code>df['Value']</code> to <code>x['Value']</code>, similar with <code>Value1</code> and last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>:</p> <pre><code>df['diff'] = df.gr...
1
2016-05-31T18:08:40Z
[ "python", "python-2.7", "pandas" ]
Subtracting Two Columns with a Groupby in Pandas
37,552,727
<p>I have a <code>dataframe</code> and would like to subtract two columns of the previous row, provided that the previous row has the same <code>Name</code> value. If it does not, then I would like it yield <code>NAN</code> and fill with <code>-</code>. My <code>groupby</code> expression yields the error, <code>TypeErr...
2
2016-05-31T18:05:55Z
37,552,816
<p>you can also do it this way:</p> <pre><code>In [76]: df['diff'] = (-df.groupby('Names')[['Value1','Value']].shift(1).diff(axis=1)['Value1']).fillna(0) In [77]: df Out[77]: Names Value Value1 diff 0 Person A 5 8 0.0 1 Person A 13 11 -3.0 2 Person B 11 32 0.0 3 Person B...
1
2016-05-31T18:11:39Z
[ "python", "python-2.7", "pandas" ]
Regular expression python dataframe element
37,552,745
<p>I had a question (answered excellently) here: <a href="http://stackoverflow.com/questions/37484646/python-parse-dataframe-element">Python parse dataframe element</a></p> <p>Unfortunately, my data source has other conditions which need handled.</p> <p>Current pattern is</p> <pre><code>pattern = r'([^\(]+)(\(([^,]...
1
2016-05-31T18:06:54Z
37,552,999
<p>Add a non-capturing group for the second number and the comma and then add a <code>?</code> zero or one token after it, like below.</p> <pre><code>([^\(]+)(\(([^,]*)(?:,(.*))?\))? (?: )? &lt;= this part means that the comma and everything following it is optiona...
1
2016-05-31T18:22:33Z
[ "python", "regex", "parsing", "pandas" ]
Regular expression python dataframe element
37,552,745
<p>I had a question (answered excellently) here: <a href="http://stackoverflow.com/questions/37484646/python-parse-dataframe-element">Python parse dataframe element</a></p> <p>Unfortunately, my data source has other conditions which need handled.</p> <p>Current pattern is</p> <pre><code>pattern = r'([^\(]+)(\(([^,]...
1
2016-05-31T18:06:54Z
37,553,121
<p>If you are just trying to extract the number between the brackets you can use a much simple version:</p> <pre><code>In [2]: rgx=re.compile("\w+\((?P&lt;num&gt;\d*\,*\d*)") In [5]: m=rgx.match("VARCHAR(22,22)") In [10]: m.groupdict() Out[10]: {'num': '22,22'} In [16]: m=rgx.match("VARCHAR(22)") In [17]: m.groupdict...
1
2016-05-31T18:29:31Z
[ "python", "regex", "parsing", "pandas" ]
Interpreter written in Python not working properly
37,552,800
<p>No, I'm not done with my interpreter questions yet. Sorry.</p> <p>So I've written another interpreter for a programming language I made up in Python. The programming language has an interesting concept: you only get some basic commands. To "get" more complex commands, you have to write functions and combine the sim...
0
2016-05-31T18:10:44Z
37,553,274
<p>When solving these kinds of problems it is imperative to be able to see what is going on while the program is running. You can e.g. use a debugger or you can go with the age old debug print method (like I've done below).</p> <p>I've extended the interpreter with a <code>p</code> command that prints the <code>acc</...
2
2016-05-31T18:39:22Z
[ "python", "function", "dictionary", "interpreter" ]
Psychopy-moving textstim with endpoint
37,552,811
<p>I am working in psychopy and I would like to have a text stim slide from one position to another over the course of several frames. I have tried the [frameN,0] in the position section for the text stim but I am unsure how to set an endpoint (time/ frames and position).Thanks for help in advance! </p>
0
2016-05-31T18:11:17Z
37,554,393
<p>Start by calculating the step size for each frame. It's just the difference between the end and start coordinates divided by the number of frames. <code>numpy</code> arrays comes in handy here although you could do it in base python as well:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np s...
1
2016-05-31T19:45:59Z
[ "python", "text", "psychopy" ]
Python: Import Excel Data and lookup values in Dictionary
37,552,812
<p>Total beginner to python: Trying to import excel values from a column. Lookup the imported values in python dictionary (was able to create this) and then write the results into the excel file and see if they match to another column in the file. </p>
0
2016-05-31T18:11:18Z
37,553,049
<p>You can use a module called <code>pandas</code>.</p> <pre><code>pip install pandas </code></pre> <p>To read the file use the following:</p> <pre><code>import pandas as pd file = pd.ExcelFile('path/to/excelsheet/').parse('sheet_you_want_to_use') # 'Sheet 1' for Sheet 1 </code></pre> <p>you can now access the colu...
0
2016-05-31T18:25:18Z
[ "python", "lookup" ]
Not able to click on link in webpage using selenium webdriver
37,552,888
<p>I want to click on "Wireless" link in my router web page using selenium python webdriver. Below is the html:</p> <pre><code> &lt;html&gt; &lt;head&gt; &lt;frameset framespacing="0" frameborder="0" border="0" rows="50,*,15"&gt; &lt;frame noresize="" marginheight="0" marginwidth="0" target="_sel...
0
2016-05-31T18:16:06Z
37,553,945
<p>The issue seems to be with quotes. Use the following syntax:</p> <pre><code>driver.find_element_by_xpath("//a[@href='wlswitchinterface0.wl']").click() </code></pre>
0
2016-05-31T19:18:09Z
[ "python", "selenium", "xpath", "selenium-webdriver" ]
Not able to click on link in webpage using selenium webdriver
37,552,888
<p>I want to click on "Wireless" link in my router web page using selenium python webdriver. Below is the html:</p> <pre><code> &lt;html&gt; &lt;head&gt; &lt;frameset framespacing="0" frameborder="0" border="0" rows="50,*,15"&gt; &lt;frame noresize="" marginheight="0" marginwidth="0" target="_sel...
0
2016-05-31T18:16:06Z
37,554,244
<p>The problem is not the quotes, but is because you're inside a frame. </p> <p>First, you need to switch inside his:</p> <pre><code>frame = driver.find_element_by_xpath("//frame[@name='menufrm']") driver.switch_to_frame(frame) </code></pre> <p>Now, you can access your link:</p> <pre><code>driver.find_element_by_xp...
1
2016-05-31T19:36:46Z
[ "python", "selenium", "xpath", "selenium-webdriver" ]
Convert QPixmap to Numpy
37,552,924
<p>To convert numpy matrix to QPixmap, I use this function:</p> <pre><code>def np2qpixmap(np_img): frame = cv2.cvtColor(np_img, cv2.COLOR_BGR2RGB) img = QtGui.QImage(frame, frame.shape[1], frame.shape[0], QtGui.QImage.Format_RGB888) return QtGui.QPixmap.fromImage(img) </code></pre> <p>Now how to do the in...
0
2016-05-31T18:17:51Z
37,588,267
<p>Here is a function I wrote for some hobby project a while ago...</p> <pre><code>import copy import numpy as np def qt_image_to_array(img, share_memory=False): """ Creates a numpy array from a QImage. If share_memory is True, the numpy array and the QImage is shared. Be careful: make sure the n...
0
2016-06-02T09:46:30Z
[ "python", "numpy", "pyqt4" ]
cv2.imread fails in script, not on command line
37,552,975
<p><code>cv2.imread("some.jpg")</code> fails to read many different jpgs. I have checked a million different things: </p> <ol> <li><strong>Run the same exact code in a terminal - reads and opens images just fine</strong></li> <li>I checked version numbers of both python and cv2 - they are exactly the same:<code>3.4.3...
2
2016-05-31T18:21:14Z
37,554,112
<p>The script might be executed as a different user, with different privileges or at a different location than executing the code on the command line.</p> <ul> <li>Check existence of file <strong>in the code</strong> with <code>os.path.isfile</code></li> <li>provide details on the script (language) and how you start i...
3
2016-05-31T19:29:03Z
[ "python", "opencv", "opencv3.0" ]
Python not looping though lines in file
37,553,020
<p>For whatever reason almost nothing is happening when I run this program. It seems incredibly straight forward and simple and It's driving me insane that It is not working.</p> <pre><code>fin = open("input.txt", 'r') print("asd;lkfja;sdlkfj") read = True for line in fin.readlines(): print(line) begCommen...
-3
2016-05-31T18:23:41Z
37,553,074
<p>You're calling readlines at every iteration, break that out of the for loop.</p> <pre><code>lines = file.readlines() for line in lines: </code></pre>
-3
2016-05-31T18:26:59Z
[ "python" ]
Python not looping though lines in file
37,553,020
<p>For whatever reason almost nothing is happening when I run this program. It seems incredibly straight forward and simple and It's driving me insane that It is not working.</p> <pre><code>fin = open("input.txt", 'r') print("asd;lkfja;sdlkfj") read = True for line in fin.readlines(): print(line) begCommen...
-3
2016-05-31T18:23:41Z
37,553,567
<p>Try placing the full (absolute) path to your file in the <code>open()</code> statement:</p> <pre><code>fin = open("/full/working/path/to/the/file/input.txt","r") #(try C:/full/working/[...] for windows builds) #continue code... </code></pre> <p>When using <code>open()</code>, python assumes the current working di...
0
2016-05-31T18:56:32Z
[ "python" ]
Python BadYieldError when yielding Future
37,553,080
<p>I'm fairly new to programming using coroutines and I'm trying to build a database interface for a custom database for a Tornado web server using Python 2.7.10. However, I keep getting a <code>BadYieldError</code>. I feel that this is probably me not understanding how to fully use <code>tornado.gen.coroutine</code> w...
0
2016-05-31T18:27:16Z
37,556,203
<p>Either turn <code>testGet</code> into a coroutine like this so that it returns a future:</p> <pre><code>@gen.coroutine def testGet(query): gen.sleep(2) raise gen.Return(query) </code></pre> <p>Or don't use <code>yield</code> on it: <code>d = testGet(key)</code>. </p> <p>If you do either, the code works. Y...
1
2016-05-31T21:50:58Z
[ "python", "tornado", "future", "yield", "coroutine" ]
Error in importing PIRT( Python Image Registration Toolkit) in python
37,553,102
<p>So, i have install the PIRT package for image registration. But i am not able to import it in my python. It is showing some error :</p> <pre><code>&gt;&gt;&gt; import pirt Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/osboxes/pirt/pirt/__init__.py", line 36, in &...
0
2016-05-31T18:28:27Z
37,553,624
<p>Note :</p> <p>it got solved by just building with </p> <pre><code>python setup.py build_ext --inplace </code></pre>
0
2016-05-31T19:00:13Z
[ "python", "python-3.x", "cython", "cythonize" ]
pandas column name assignment read_csv
37,553,298
<p>I have a csv file as follows:</p> <pre><code>0 5 1 10 2 15 3 20 4 25 </code></pre> <p>I want to save it as a dataframe with x,y axes as names, then plot it. However when I assign <code>x</code>,<code>y</code> I get a messed up DataFrame, what is happening?</p> <pre><code>column_names = ['x','y'] x = pd.read_csv('...
1
2016-05-31T18:40:31Z
37,553,329
<p>Add parameter <code>sep="\s+"</code> or <code>delim_whitespace=True</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a>:</p> <pre><code>import pandas as pd import io temp=u"""0 5 1 10 2 15 3 20 4 25""" #after testing replace io.Str...
1
2016-05-31T18:42:35Z
[ "python", "csv", "pandas", "dataframe" ]
pandas column name assignment read_csv
37,553,298
<p>I have a csv file as follows:</p> <pre><code>0 5 1 10 2 15 3 20 4 25 </code></pre> <p>I want to save it as a dataframe with x,y axes as names, then plot it. However when I assign <code>x</code>,<code>y</code> I get a messed up DataFrame, what is happening?</p> <pre><code>column_names = ['x','y'] x = pd.read_csv('...
1
2016-05-31T18:40:31Z
37,562,372
<p>You could try this : </p> <pre><code>import pandas as pd column_names = ['x','y'] df = pd.read_csv('csv-file.csv,header=None) df.columns = column_names </code></pre>
0
2016-06-01T07:41:43Z
[ "python", "csv", "pandas", "dataframe" ]
Optional Parenthesis in Regex
37,553,317
<p>Using the following string in python </p> <pre><code>1 - GENERAL 1 1.1 RELATED DOCUMENTS 1 1.2 SUMMARY 1 1.3 DEFINITIONS 1 1.4 INFORMATIONAL SUBMITTALS 2 1.5 GENERAL COORDINATION PROCEDURES 2 1.6 COORDINATION DRAWINGS 3 1.7 REQUESTS FOR INFORMATION (RFIs) 4 1.8 PROJECT...
1
2016-05-31T18:41:36Z
37,553,364
<p>There are mainly three parts contained in your string. </p> <blockquote> <p>First is section which is mainly composed of digits followed by decimal and digits</p> <p>Second is anything upto page number. This mainly starts from word</p> <p>Third is page number in the last which is <em>usually</em> digits...
2
2016-05-31T18:45:07Z
[ "python", "regex" ]
Optional Parenthesis in Regex
37,553,317
<p>Using the following string in python </p> <pre><code>1 - GENERAL 1 1.1 RELATED DOCUMENTS 1 1.2 SUMMARY 1 1.3 DEFINITIONS 1 1.4 INFORMATIONAL SUBMITTALS 2 1.5 GENERAL COORDINATION PROCEDURES 2 1.6 COORDINATION DRAWINGS 3 1.7 REQUESTS FOR INFORMATION (RFIs) 4 1.8 PROJECT...
1
2016-05-31T18:41:36Z
37,553,771
<p>I'd recommend something like this</p> <pre><code> ^\s*([\d.]+)[\s-]*\s+(.+?)\s+(\d+)$ </code></pre> <p>Since you said you are in python, this affords you some more abilities when it comes to things like comments. For example:</p> <pre><code> ^\s*(?#Section)([\d.]+)[\s-]*\s+(?#Title)(.+?)\s+(?#Page)(\d+)$ </...
0
2016-05-31T19:08:44Z
[ "python", "regex" ]
No such File or Directory Exception
37,553,343
<p>I am a relative newbie to Python, and I have searched and while there are many posts regarding the error, none appear to address my requirement.</p> <p>Briefly, I am writing code to hourly reports. I intend to have 4 days of reports archived in the folder. At the beginning of my code I have one line that deletes al...
1
2016-05-31T18:43:21Z
37,554,002
<p>Figures that I would wrestle with this for a couple of days and then figure it out 30 min after I post the question. Here's the solution:</p> <p>if not listdir("insert the work path here"): --the command I want to execute if the dir is not empty-- Else: --whatever code you want to execute when dir is empty--...
1
2016-05-31T19:21:58Z
[ "python", "exception" ]
No such File or Directory Exception
37,553,343
<p>I am a relative newbie to Python, and I have searched and while there are many posts regarding the error, none appear to address my requirement.</p> <p>Briefly, I am writing code to hourly reports. I intend to have 4 days of reports archived in the folder. At the beginning of my code I have one line that deletes al...
1
2016-05-31T18:43:21Z
37,578,023
<p>If the file it wants to delete is not in the directory, I want that to be okay and the program to continue processing the next command instead of aborting the process. In short I want to check to see if the file is there and if it isn't skip the rm code and process the rest of the script.</p>
1
2016-06-01T20:18:02Z
[ "python", "exception" ]
Python Applymap taking time to run
37,553,397
<p>I have a matrix of data ( 55K X8.5k) with counts. Most of them are zeros, but few of them would be like any count. Lets say something like this: </p> <pre><code> a b c 0 4 3 3 1 1 2 1 2 2 1 0 3 2 0 1 4 2 0 4 </code></pre> <p>I want to binaries the cell values. </p> <p>I did the following: </p> <...
-1
2016-05-31T18:46:57Z
37,553,473
<p><strong>UPDATE:</strong></p> <p>read <a href="https://github.com/pydata/pandas/issues/3699" rel="nofollow">this topic</a> and <a href="https://github.com/pydata/pandas/issues/12712" rel="nofollow">this issue</a> in regards to your error</p> <p>Try to save your DF as HDF5 - it's much more convenient.</p> <p>You ma...
3
2016-05-31T18:50:42Z
[ "python", "pandas", "dataframe" ]
Python Applymap taking time to run
37,553,397
<p>I have a matrix of data ( 55K X8.5k) with counts. Most of them are zeros, but few of them would be like any count. Lets say something like this: </p> <pre><code> a b c 0 4 3 3 1 1 2 1 2 2 1 0 3 2 0 1 4 2 0 4 </code></pre> <p>I want to binaries the cell values. </p> <p>I did the following: </p> <...
-1
2016-05-31T18:46:57Z
37,553,638
<p>You could use a scipy sparsematrix. This would make the calculations only relevant to the data that is actually there instead of operating on all the zeros.</p>
0
2016-05-31T19:01:03Z
[ "python", "pandas", "dataframe" ]
Django Model form with read only properties
37,553,430
<p>first of all let me explain the scenario: I'm working in a CRUD with Django 1.8.7, Python 2.7 and bootstrap as frontend. In the List of this CRUD when the user pressed the Add button a modal will open with a combo for the user to select what kind of item he wants to create. The user selects the option and the next f...
0
2016-05-31T18:48:33Z
37,570,646
<p>Just define the field again just before meta.</p> <pre><code>class MyForm(ModelForm): inp_type = forms.CharField(widget = forms.TextInput(attrs={'readonly':'readonly'})) class meta: model = MyModel exclude = ['id'] </code></pre>
0
2016-06-01T13:48:33Z
[ "python", "django", "forms" ]
Django Model form with read only properties
37,553,430
<p>first of all let me explain the scenario: I'm working in a CRUD with Django 1.8.7, Python 2.7 and bootstrap as frontend. In the List of this CRUD when the user pressed the Add button a modal will open with a combo for the user to select what kind of item he wants to create. The user selects the option and the next f...
0
2016-05-31T18:48:33Z
37,578,253
<p>I have found the way. First you have to create a custom widget that will render the way you want. In my case the original widget was a combo (select), so I found this widget:</p> <pre><code>class ReadOnlySelect(Select): def render(self, name, value, attrs=None, choices=()): final_attrs = self.build_attr...
0
2016-06-01T20:32:18Z
[ "python", "django", "forms" ]
How do I override a function of a python library?
37,553,545
<p>I am using a python library where I need to override one of the functions. Let's call this module.py</p> <pre><code>def dump(nodes, args = 'bleh' ): ...validation checks for node in nodes: print(node, someother_args) def print_node(node, someother_args): ...prints in some way i don't want </code></p...
0
2016-05-31T18:54:58Z
37,553,637
<p>You can create a class by yourself that inherits from intended module, and override the function in any way you want. Then you can use your object instead of <code>module.py</code>.</p> <pre><code>class my_class(module): def __init__(self, *args, **kwargs): super(my_class, self).__init__(*args, **kwargs...
0
2016-05-31T19:01:01Z
[ "python", "python-2.7" ]
3.5: Type Hinting and Method Overloading
37,553,551
<p>Edit: I misunderstood the feature currently. <a href="https://www.python.org/dev/peps/pep-0484/#function-method-overloading" rel="nofollow">It's not designed for multiple dispatch</a>:</p> <blockquote> <p>NOTE: While it would be possible to provide a multiple dispatch implementation using this syntax, its impleme...
2
2016-05-31T18:55:23Z
37,553,800
<p>Untyped Python does not support overloading. Your second <code>__init__</code> is overwriting the first one, thus the error. You need to write a single <code>__init__</code> with runtime type-checking:</p> <pre><code>def __init__(self, arg1, arg2=None): if isinstance(arg1, gitlab.Gitlab) and arg2 is None: ...
1
2016-05-31T19:10:10Z
[ "python", "python-3.5" ]
Assert that a PropertyMock was called on a specific instance
37,553,552
<p>I have successfully mocked a property with <code>PropertyMock</code>, but I can't figure out how to check which instance of the class has had that property called. How can I assert that the property was called on one object, but not on another?</p> <p>Here's an example where I want to assert that <code>foo1.is_big<...
0
2016-05-31T18:55:23Z
37,554,078
<p>Maybe there's a better way, but I got it to work by creating a subclass of <code>PropertyMock</code> that records the instance that it was called on as one of the parameters to the mock call.</p> <pre><code>from mock import PropertyMock, patch class Foo(object): def __init__(self, size): self.size = s...
0
2016-05-31T19:26:33Z
[ "python", "unit-testing", "mocking" ]
Check if Sympy Expression is Nan?
37,553,588
<p>How do I check if a sympy expression evaluates to nan?</p> <p>I simply need to do something like this:</p> <pre><code>if is_nan( expression ): #Do stuff </code></pre>
4
2016-05-31T18:58:02Z
37,553,814
<p>In sympy, you can check for equality with the sympy nan object:</p> <pre><code>&gt;&gt;&gt; alpha = sympy.nan &gt;&gt;&gt; alpha == sympy.nan True </code></pre> <p>In numpy, you cannot check for equality with the numpy nan object:</p> <pre><code>&gt;&gt;&gt; alpha = numpy.nan &gt;&gt;&gt; alpha == numpy.nan False...
4
2016-05-31T19:10:58Z
[ "python", null, "sympy" ]
Check if Sympy Expression is Nan?
37,553,588
<p>How do I check if a sympy expression evaluates to nan?</p> <p>I simply need to do something like this:</p> <pre><code>if is_nan( expression ): #Do stuff </code></pre>
4
2016-05-31T18:58:02Z
37,603,147
<p>In SymPy, <code>==</code> always checks structural equality (that is, if two expressions are exactly equal). This works even for nan, so there is no need for a separate <code>isnan</code> function (strictly speaking, SymPy's nan isn't an IEEE 754 nan). </p>
1
2016-06-02T22:27:43Z
[ "python", null, "sympy" ]
Attempting to store an object, but cannot pickle ttk class
37,553,643
<p>I am attempting to store a filepath to a file so that when my application is opened, the filepath can be loaded back in and not have to be re-entered. To do this, I am trying to use the pickle module to "dump" the data to a file. However, I get the following error:</p> <pre><code> Traceback (most recent call last)...
0
2016-05-31T19:01:21Z
37,554,362
<p>This button calls askfile and sends it a StringVar()</p> <pre><code>ttk.Button(mainframe, text="Browse", command=lambda:askfile(usbpath)).grid(column=2,row=2,sticky = E) </code></pre> <p>the function then tries to pickle the StringVar, not the filename</p> <pre><code>def askfile(pathtype): ## pathtype=StrinVar ...
1
2016-05-31T19:43:35Z
[ "python", "tkinter", "pickle" ]
plotting multiple pandas series with different length in one chart
37,553,651
<p>I have 10 Panda Series in all with different length, now I want to plot all 10 as box-plots in one chart where x-axis shows the series name.</p> <p>This would be a standard operation as described <a href="http://pandas.pydata.org/pandas-docs/stable/visualization.html" rel="nofollow">here</a> if all series had the s...
0
2016-05-31T19:02:12Z
37,554,024
<p>The differing length series will not be a problem. Pandas will automatically fill in the missing values with NA.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import pandas as pd np.random.seed(100) s1 = pd.Series(np.random.randn(5)) s2 = pd.Series(np.random.randn(10)) s3 = pd.Series(np.random....
3
2016-05-31T19:23:18Z
[ "python", "pandas" ]
Serializing and deserializing datetimefield type object (Django app)
37,553,665
<p>In a Django app of mine, I have a datetime object that I need to serialize and then deserialize. When I try it, I get the error:</p> <blockquote> <p>ValueError: time data '2016-05-31T18:57:17.280939+00:00' does not match format '%Y-%m-%d %H:%M:%S.%f'</p> </blockquote> <p>My code to serialize and deserialize is...
0
2016-05-31T19:02:43Z
37,553,959
<p><code>timeobj = datetime.strptime(timestring, "%Y-%m-%dT%H:%M:%S.%f+00:00")</code></p> <p>(adds a <code>T</code> as the date/time separator, and hard codes the utc offset string part)</p> <p>will resolve your problem ... and I guess its reasonably safe ... personally I always go with </p> <pre><code>from dateutil...
1
2016-05-31T19:19:17Z
[ "python", "django", "datetime", "serialization" ]
Serializing and deserializing datetimefield type object (Django app)
37,553,665
<p>In a Django app of mine, I have a datetime object that I need to serialize and then deserialize. When I try it, I get the error:</p> <blockquote> <p>ValueError: time data '2016-05-31T18:57:17.280939+00:00' does not match format '%Y-%m-%d %H:%M:%S.%f'</p> </blockquote> <p>My code to serialize and deserialize is...
0
2016-05-31T19:02:43Z
37,554,010
<p>So there are two things going on here:</p> <ol> <li><p>Your format string has a space between <code>%d</code> and <code>%H</code> but the test string has a <code>T</code>.</p></li> <li><p>Python's <code>datetime.datetime.strptime</code> does not work with timezone names/offsets. From the <a href="https://docs.pytho...
0
2016-05-31T19:22:21Z
[ "python", "django", "datetime", "serialization" ]
WebKit2.JavascriptResult.get_value() throws exception "TypeError: Couldn't find foreign struct converter for 'JavaScriptCore.Value'".
37,553,701
<p>I am writing a python3 + webkit2 + gtk3 based GUI. Everything works fine, but when I tried to use WebKit2.WebView.run_javascript_finish() in a callback function, getting the return (a WebKit2.JavascriptResult objetc), e extrat the value with WebKit2.JavascriptResult.get_value(), I received a "TypeError: Couldn't fin...
1
2016-05-31T19:04:56Z
38,041,497
<p>Unfortunately, using the JavaScriptCore library isn't supported in Python.</p> <p>The definitions in <code>gi.repository.JavaScriptCore</code> only include opaque definitions for <code>JavaScriptCore.Value</code> and <code>JavaScriptCore.GlobalContext</code> in order to provide type information for functions that u...
0
2016-06-26T17:59:38Z
[ "python", "webkit", "gtk", "pygobject", "javascriptcore" ]
Where is this Python syntax error?
37,553,739
<p>I'm coming back to Python and there's at least one point where I'm making a syntax error in a 0.9.x Pinax installation. What I am trying to do here is add an additional layer of filtering (on top of the default optional filtering that provides functionality allowing the user to either see all blog entries, or all of...
0
2016-05-31T19:06:37Z
37,553,788
<pre><code>[blog in blogs.objects.all() if custom.threshold_check(request.user, blog)] </code></pre> <p>This isn't valid Python. Perhaps you meant:</p> <pre><code>[blog for blog in blogs.objects.all() if custom.threshold_check(request.user, blog)] </code></pre>
4
2016-05-31T19:09:41Z
[ "python", "django", "pinax", "pinax-blogs" ]
Optimize add row in xls file with xlwt
37,553,767
<p>I have a big problem with a large xls file. When my app add a new stats record (a new row at the end of the file) there is a very long time (one minute). If I replace it with an empty xls file this work the best (1-2 seconds). So I'm trying to optimize this if possible.</p> <p>I use something like:</p> <pre><code>...
2
2016-05-31T19:08:35Z
37,641,892
<p>Probably not the answer you want to hear but there is hardly anything to optimize.</p> <pre><code>import xlwt, xlrd from xlutils.copy import copy as copy from time import time def add_stats_record(): #Open for read start_time = time() rb = xlrd.open_workbook(STATS_FILE, formatting_info=True) sheet_...
3
2016-06-05T12:26:43Z
[ "python", "xlrd", "xlwt" ]
Schedule python scripts to run in AWS
37,553,776
<p>I have 3 python scripts which I want to schedule to run at different times in AWS. Currently, I have those 3 scripts residing in an EC2 instance and I use <code>cron</code> to run them. The first and second scripts download some data to a specific directory on the EC2 box (say at <code>/home/ec2-user/data</code>). T...
0
2016-05-31T19:08:56Z
37,554,715
<p>Yes you can use aws lambda for this. You can use s3 for your data storage needs.</p> <p>One limitation you may need to consider is the max time allowed for execution of the job would be 300 seconds.</p> <p>Reference: <a href="http://docs.aws.amazon.com/lambda/latest/dg/with-scheduled-events.html" rel="nofollow">ht...
2
2016-05-31T20:05:16Z
[ "python", "amazon-web-services", "cron", "aws-lambda" ]
Schedule python scripts to run in AWS
37,553,776
<p>I have 3 python scripts which I want to schedule to run at different times in AWS. Currently, I have those 3 scripts residing in an EC2 instance and I use <code>cron</code> to run them. The first and second scripts download some data to a specific directory on the EC2 box (say at <code>/home/ec2-user/data</code>). T...
0
2016-05-31T19:08:56Z
37,555,745
<p>Check the Worker Environment from AWS Elastic Beanstalk. This will start an EC2 and a SQS queue, automatically managed by AWS EB - <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features-managing-env-tiers.html" rel="nofollow">Docs</a>, and a simple <a href="https://medium.com/@joelennon/runni...
0
2016-05-31T21:14:51Z
[ "python", "amazon-web-services", "cron", "aws-lambda" ]
Redirect to OAuth URL with headers
37,553,888
<p>I'm trying to write a Python 3.5 Flask application that redirects a user to an OAuth URL, for authentication / authorization. As part of that redirection, I have to include the <code>Authorization</code> header. The built-in <code>redirect()</code> method in Flask doesn't seem to support adding HTTP headers.</p> <p...
0
2016-05-31T19:14:40Z
37,557,023
<p>You will need to build your own response object to add headers. You can check out the docs here: <a href="http://docs.python-requests.org/en/master/api/#requests.Response" rel="nofollow">http://docs.python-requests.org/en/master/api/#requests.Response</a></p> <p>A simple example for your use case would be something...
0
2016-05-31T23:04:33Z
[ "python", "python-3.x", "oauth", "flask" ]
Aggregating distinct values from a child table as an attribute on a parent table in sqlalchemy
37,553,919
<p>I have a one-to-many relationship set up like this in sqlalchemy:</p> <pre><code>from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, ForeignKey Base = declarative_base() class Status(Base): __tablename__ = 'status' name = Column(String(32), primary_key=...
0
2016-05-31T19:16:33Z
37,556,927
<p>I solved this by using <code>group_concat</code>. The results come back as a comma-separated string, but that's ok.</p> <pre><code>Task.statuses = column_property( select([func.group_concat(distinct(Chunk.status))]).\ where(Chunk.taskId == Task.id).\ correlate(Task.__table__) ) </code></pre>
0
2016-05-31T22:51:26Z
[ "python", "sqlalchemy" ]
Tkinter destroy button crate by a loop
37,553,931
<p>I want to crate a reminder to remind me of the time I have chosen in the combobox by pressing the confirmed button. I put the time in a label and also crate a delete button that can delete the label and button itself in the same row by a loop.It works if there's only one label,but if I increased the number of it it ...
0
2016-05-31T19:17:30Z
37,554,135
<pre><code>self.savelabel_list.remove(self.savelabel_list[idx]) </code></pre> <p>Do not change the list. If you delete label/button #1, then label #2 becomes #1, and so when you press the button to delete label #2, it deletes label #3 because everything has moved up. Also, note that every time you call "save()" it c...
0
2016-05-31T19:30:04Z
[ "python", "function", "button", "tkinter", "destroy" ]
Permission error, pip install
37,553,953
<p>I just started with a new build of fedora, and I am trying to pip install pew, so that I can work on some virtual python environments.</p> <p>The pip install went correctly, at least I think so.</p> <pre><code>&gt;&gt;&gt; pip -V pip 7.1.0 from /usr/lib/python2.7/site-packages (python 2.7) </code></pre> <p>I know...
1
2016-05-31T19:18:40Z
38,640,537
<p>Forgot I had even asked this, but I needed to "sudo su" because I was trying to install the python packages to somewhere requiring root.</p> <p>The more permanent fix was to use <a href="https://github.com/berdario/pew" rel="nofollow">pew</a> to manage my python environments. In the context of a pew environment, I ...
0
2016-07-28T15:21:00Z
[ "python", "permissions", "pip", "fedora" ]
TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30
37,553,985
<p>Encountering a pretty frustrating error that pops up whenever one of my api endpoints is accessed. To give context, the application I am working on a <strong>Flask</strong> app using <strong>SQLAlchemy</strong> that stores data in a <strong>PostgreSQL</strong> database set to hold 1000 connections. </p> <p>One of t...
0
2016-05-31T19:20:50Z
37,557,144
<p>I think that you are going about this in a bit of a roundabout way. Here are some suggestions on getting the most out of your postgres connections (I have used this configuration in production).</p> <ol> <li>I would be using the <a href="http://flask-sqlalchemy.pocoo.org/2.1/" rel="nofollow">Flask-SQLAlchemy</a> ex...
1
2016-05-31T23:21:27Z
[ "python", "postgresql", "flask", "sqlalchemy", "elastic-beanstalk" ]
Scraping one page with scrapy
37,554,029
<p>I have a long stream of URLs that I need to scrape and extract data, I want to use scrapy for that.</p> <p>Say I have a Twisted reactor setup and I creating spider</p> <pre><code>runner = CrawlerRunner(scrapy_settings) d = runner.crawl(spider_cls) </code></pre> <p>Is there a way I can send URLs to spider so it'll...
1
2016-05-31T19:23:36Z
37,554,522
<p>The <a href="http://doc.scrapy.org/en/latest/topics/api.html?highlight=crawlerrunner#scrapy.crawler.CrawlerRunner.crawl" rel="nofollow"><code>crawl()</code> method</a> can take additional arguments:</p> <pre><code>d = runner.crawl(spider_cls, start_urls=["url"]) </code></pre>
1
2016-05-31T19:53:59Z
[ "python", "scrapy" ]
Jumping in Pygame
37,554,130
<p>I am trying to make a game like geometry dash in pygame. I have everything done except the jumping part. I need it so that when the character is on a square block he can jump up, but cannot double jump in mid air. Right now I have it so that the character is able to jump on the ground but as soon as the character to...
0
2016-05-31T19:29:52Z
38,275,042
<p>I don't know if you're indention is wrong just in this post or in your game, but according to this post, onblock will always be False after every loop. This might be the problem.</p> <p>The other possible problem might be that you are placing your character 1 pixel above the platform when a collision happens. This ...
0
2016-07-08T20:38:19Z
[ "python", "pygame" ]
Constructing Proper Python Facade Class with Super?
37,554,187
<p>I thought I had a handle on Multiple Inheritance with Super() and was trying to use it inside a Facade class, but I am running into a weird bug. I'm using a well made Python Workflow software called Fireworks, but the structures of the classes and Workflow Tasks are pretty rigid so I was creating a Facade class for...
2
2016-05-31T19:33:18Z
37,556,234
<p>Mutable default arguments in python don't work like you expect them to; Your function definition(irrelevant arguments are omitted):</p> <pre><code>def __init__(self, ..., isp={}, ...): &lt;CODE&gt; </code></pre> <p>Is equivalent to this:</p> <pre><code>DEFAULT_ISP = {} def __init__(self, ..., isp=DEFAULT_ISP, ...
1
2016-05-31T21:53:26Z
[ "python", "inheritance", "super", "facade", "method-resolution-order" ]
Initialization of a list of dictionaries
37,554,239
<p>I want to take input from the user and initialize a list of dictionaries. I have the following block which works fine.</p> <pre><code>people = [] for p in range(3): cell = {"name": "","age" : 0, "education" : "","height" : 0} cell["name"] = input("name:") cell["age"] = int(input("age:")) cell["educ...
0
2016-05-31T19:36:34Z
37,554,355
<p>The important part is this line:</p> <pre><code>cell = {"name": "","age" : 0, "education" : "","height" : 0} </code></pre> <p>here you <strong>create</strong> a dictionary and save a reference to it under <code>cell</code></p> <p>If you do this before the loop (like in your second example) you have only created <...
3
2016-05-31T19:42:51Z
[ "python", "dictionary" ]
Initialization of a list of dictionaries
37,554,239
<p>I want to take input from the user and initialize a list of dictionaries. I have the following block which works fine.</p> <pre><code>people = [] for p in range(3): cell = {"name": "","age" : 0, "education" : "","height" : 0} cell["name"] = input("name:") cell["age"] = int(input("age:")) cell["educ...
0
2016-05-31T19:36:34Z
37,554,363
<p>This is the difference between passing by value and passing by reference. Passing by reference, or a pointer in other language terms, means the variable points to a spot in memory. In Python, dictionaries behave this way, which means that since you are, in the second version, changing what exists in the dictionary t...
1
2016-05-31T19:43:41Z
[ "python", "dictionary" ]
Initialization of a list of dictionaries
37,554,239
<p>I want to take input from the user and initialize a list of dictionaries. I have the following block which works fine.</p> <pre><code>people = [] for p in range(3): cell = {"name": "","age" : 0, "education" : "","height" : 0} cell["name"] = input("name:") cell["age"] = int(input("age:")) cell["educ...
0
2016-05-31T19:36:34Z
37,554,364
<blockquote> <p>shouldn't the previous value been erased and the new one to take it's place?</p> </blockquote> <p>No! This is because every loop modifies the <strong>same object since the reference is not changing</strong>. This is why you have the last iteration values showing up three times.</p> <p>Try:</p> <pre...
1
2016-05-31T19:43:47Z
[ "python", "dictionary" ]
How to Process Row Pairs Preserving an ID Column without Dictionaries using Pandas?
37,554,460
<p>I'm searching for a better solution to a data processing problem I've encountered in my research. I have a Pandas DataFrame and I'm trying to extract all values of a particular column (Z) within a group (Frame), preserving the ID pairs given by a different column (Name). The final result doesn't have to be a Pandas ...
1
2016-05-31T19:50:00Z
37,556,561
<p>Here's a pandas approach that's accomplished in two steps:</p> <ol> <li>Get the pairs of names and Z values for each Frame group.</li> <li>Combine the Z value components for each pair of names.</li> </ol> <p><strong>Step 1</strong></p> <p>To get the pairs of names and z values, I'm going to write a helper functio...
1
2016-05-31T22:18:50Z
[ "python", "pandas" ]