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 |
|---|---|---|---|---|---|---|---|---|---|
print([[i+j for i in "abc"] for j in "def"]) | 39,373,220 | <p>I'm new to Python.</p>
<p>I stumped upon with one of this comprehension</p>
<pre><code>print([[i+j for i in "abc"] for j in "def"])
</code></pre>
<p>Could you please help me convert the comprehension in for loop?</p>
<p>I'm not getting the desired result by for loop:</p>
<pre><code>list = []
list2 = []
for j i... | -2 | 2016-09-07T14:54:52Z | 39,373,404 | <p>The easiest thing to unravel a comprehension like this is to take it one comprehension at a time and write <em>that</em> as a loop. So:</p>
<pre><code>[[i+j for i in "abc"] for j in "def"]
</code></pre>
<p>becomes:</p>
<pre><code>outer_list = []
for j in "def":
outer_list.append([i + j for i in "abc"])
</cod... | 3 | 2016-09-07T15:03:15Z | [
"python",
"list-comprehension"
] |
print([[i+j for i in "abc"] for j in "def"]) | 39,373,220 | <p>I'm new to Python.</p>
<p>I stumped upon with one of this comprehension</p>
<pre><code>print([[i+j for i in "abc"] for j in "def"])
</code></pre>
<p>Could you please help me convert the comprehension in for loop?</p>
<p>I'm not getting the desired result by for loop:</p>
<pre><code>list = []
list2 = []
for j i... | -2 | 2016-09-07T14:54:52Z | 39,373,415 | <pre><code>a = 'abc'
b = 'def'
>>> [[x+y for x in a]for y in b]
[['ad', 'bd', 'cd'], ['ae', 'be', 'ce'], ['af', 'bf', 'cf']]
</code></pre>
<h2>Loop</h2>
<pre><code>>>> for y in b:
... for x in a:
... print x+y,
...
ad bd cd ae be ce af bf cf
</code></pre>
| 1 | 2016-09-07T15:03:46Z | [
"python",
"list-comprehension"
] |
What is the encoding of the body of Gmail message? How to decode it? | 39,373,243 | <p>I am using the Python API for Gmail. I am querying for some messages and retrieving them correctly, but the body of the messages looks like total nonsense, even when the MIME type it's said to be <code>text/plain</code> or <code>text/html</code>.</p>
<p>I have been searching all over the API docs, but they keep say... | 3 | 2016-09-07T14:56:20Z | 39,373,321 | <p>It's base64. You can use base64.decodestring to read it.
The part of the message that your attached is: '---------- Forwarded message ----------\r\nFrom: LinkedIn <[email protected]>\r\nDate: Sat, Sep 3, 2016 at 9:30 AM\r\nSubject: Application for Senior Backend Develo'</p>
<p>The incorrect padding error... | 2 | 2016-09-07T14:59:52Z | [
"python",
"encoding",
"gmail-api"
] |
What is the encoding of the body of Gmail message? How to decode it? | 39,373,243 | <p>I am using the Python API for Gmail. I am querying for some messages and retrieving them correctly, but the body of the messages looks like total nonsense, even when the MIME type it's said to be <code>text/plain</code> or <code>text/html</code>.</p>
<p>I have been searching all over the API docs, but they keep say... | 3 | 2016-09-07T14:56:20Z | 39,373,410 | <pre><code>>>> "LS0tLS0tLS0tLSBGb3J3YXJkZWQgbWVzc2FnZSAtLS0tLS0tLS0tDQpGcm9tOiBMaW5rZWRJbiA8am9iLWFwcHNAbGlua2VkaW4uY29tPg0KRGF0ZTogU2F0LCBTZXAgMywgMjAxNiBhdCA5OjMwIEFNDQpTdWJqZWN0OiBBcHBsaWNhdGlvbiBmb3IgU2VuaW9yIEJhY2tlbmQgRGV2ZWxvcG==".decode('base64')
'---------- Forwarded message ----------\r\nFrom: Linked... | 0 | 2016-09-07T15:03:31Z | [
"python",
"encoding",
"gmail-api"
] |
What is the encoding of the body of Gmail message? How to decode it? | 39,373,243 | <p>I am using the Python API for Gmail. I am querying for some messages and retrieving them correctly, but the body of the messages looks like total nonsense, even when the MIME type it's said to be <code>text/plain</code> or <code>text/html</code>.</p>
<p>I have been searching all over the API docs, but they keep say... | 3 | 2016-09-07T14:56:20Z | 39,373,553 | <p>This is base64.</p>
<p>Your truncated message is:</p>
<pre><code>---------- Forwarded message ----------
From: LinkedIn <[email protected]>
Date: Sat, Sep 3, 2016 at 9:30 AM
Subject: Application for Senior Backend Develop
</code></pre>
<p>Here's some sample code:</p>
<p>I had to remove the last 3 chara... | 2 | 2016-09-07T15:10:36Z | [
"python",
"encoding",
"gmail-api"
] |
What is the encoding of the body of Gmail message? How to decode it? | 39,373,243 | <p>I am using the Python API for Gmail. I am querying for some messages and retrieving them correctly, but the body of the messages looks like total nonsense, even when the MIME type it's said to be <code>text/plain</code> or <code>text/html</code>.</p>
<p>I have been searching all over the API docs, but they keep say... | 3 | 2016-09-07T14:56:20Z | 39,374,729 | <p>Important distinction, it is <strong>web safe base64</strong> encoded (aka "base64url") . The docs are not very good on it, the MessagePartBody is best documented here:
<a href="https://developers.google.com/gmail/api/v1/reference/users/messages/attachments" rel="nofollow">https://developers.google.com/gmail/api/v1... | 1 | 2016-09-07T16:07:17Z | [
"python",
"encoding",
"gmail-api"
] |
Cannot create new ipython notebook or start jupyter | 39,373,397 | <p>Whenever I try to start Jupyter ipython notebook. I get the following error<a href="http://i.stack.imgur.com/TbhAr.png" rel="nofollow"><img src="http://i.stack.imgur.com/TbhAr.png" alt="enter image description here"></a></p>
<p>Sometimes, after restarting the system I am able to start the ipython notebook, I cannot... | 0 | 2016-09-07T15:03:00Z | 39,400,277 | <p>I used to have this issue too. It seems to be a bug because I restarted my PC and It would work normally again. It's been weeks I don't have this issue anymore and I didn't do anything to intentionally solve it.</p>
| 0 | 2016-09-08T21:12:03Z | [
"python",
"ipython",
"jupyter",
"jupyter-notebook"
] |
Craft raw wifi packet | 39,373,497 | <p>I'd like to craft single wifi packets, getting the raw binary data just before they are converted to a waveform and transmitted. As I understand it, this should be at the data link layer, and include all the headers (sync bits, CRC, etc) and the data itself. Is there a way to do this (preferably with Python)? I've l... | 0 | 2016-09-07T15:08:13Z | 39,393,537 | <p>You can dump all packet via monitor mode.<br>
For example, this code sniffing all data packets from mon0 interface:</p>
<pre><code>from scapy.all import *
def handler(pkt):
if pkt.haslayer(Dot11):
if pkt.type == 2:
pkt.show()
sniff(iface="mon0", prn=handler)
</code></pre>
| 1 | 2016-09-08T14:25:09Z | [
"python",
"wifi",
"packet"
] |
how to replace elements in xml using python | 39,373,532 | <p>sorry for my poor English. but i need your help ;( </p>
<p>i have 2 xml files.</p>
<p>one is:</p>
<pre><code><root>
<data name="aaaa">
<value>"old value1"</value>
<comment>"this is an old value1 of aaaa"</comment>
</data>
<data name="bbbb">
<value>"old value... | 1 | 2016-09-07T15:09:59Z | 39,374,035 | <p>You can use <a href="https://docs.python.org/3/library/xml.etree.elementtree.html" rel="nofollow">xml.etree.ElementTree</a> and while there are propably more elegant ways, this should work on files that fit in memory if <code>name</code>s are unique in <code>two.xml</code></p>
<pre><code>import xml.etree.ElementTre... | 0 | 2016-09-07T15:32:49Z | [
"python",
"xml"
] |
Python, how to insert value in Powerpoint template? | 39,373,550 | <p>I want to use an existing powerpoint presentation to generate a series of reports:</p>
<p>In my imagination the powerpoint slides will have content in such or similar form:</p>
<pre><code>Date of report: {{report_date}}
Number of Sales: {{no_sales}}
...
</code></pre>
<p>Then my python app opens the powerpoint, f... | 2 | 2016-09-07T15:10:34Z | 39,377,894 | <p>I tried this on a ".ppx" file I had hanging around.<br>
A microsoft office power point ".pptx" file is in ".zip" format.<br>
When I unzipped my file, I got an ".xml" file and three directories.<br>
My ".pptx" file has 116 slides comprised of 3,477 files and 22 directories/subdirectories.<br>
Normally, I would say it... | 0 | 2016-09-07T19:43:06Z | [
"python",
"powerpoint"
] |
Python, how to insert value in Powerpoint template? | 39,373,550 | <p>I want to use an existing powerpoint presentation to generate a series of reports:</p>
<p>In my imagination the powerpoint slides will have content in such or similar form:</p>
<pre><code>Date of report: {{report_date}}
Number of Sales: {{no_sales}}
...
</code></pre>
<p>Then my python app opens the powerpoint, f... | 2 | 2016-09-07T15:10:34Z | 39,381,549 | <p>You can definitely do what you want with python-pptx, just perhaps not as straightforwardly as you imagine.</p>
<p>You can read the objects in a presentation, including the slides and the shapes on the slides. So if you wanted to change the text of the second shape on the second slide, you could do it like this:</p... | 0 | 2016-09-08T02:10:05Z | [
"python",
"powerpoint"
] |
Python, how to insert value in Powerpoint template? | 39,373,550 | <p>I want to use an existing powerpoint presentation to generate a series of reports:</p>
<p>In my imagination the powerpoint slides will have content in such or similar form:</p>
<pre><code>Date of report: {{report_date}}
Number of Sales: {{no_sales}}
...
</code></pre>
<p>Then my python app opens the powerpoint, f... | 2 | 2016-09-07T15:10:34Z | 39,382,136 | <p>Ultimately, barring some other library which has additional functionality, you need some sort of brute force approach to iterate the Slides collection and each Slide's respective Shapes collection in order to identify the matching shape (unless there is some other library which has additional "Find" functionality in... | 0 | 2016-09-08T03:27:29Z | [
"python",
"powerpoint"
] |
TypeError: list indices must be integers, not tuple in Python SVD model | 39,373,557 | <p>I am testing a recommender based on SVD model. But I got an error message after running it as below: </p>
<p>Here is my testing code:</p>
<pre><code>import sys
from sys import argv
import csv
import recsys.algorithm
recsys.algorithm.VERBOSE = True
from recsys.algorithm.factorize import SVD
from recsys.datamodel.d... | 0 | 2016-09-07T15:10:42Z | 39,373,693 | <p>The TypeError is saying that you can't access element with a list when you provide it with a tuple, it needs an integer that is the position in the list.</p>
<p>Now why is this happening?</p>
<pre><code>likes.append((username,user_likes))
</code></pre>
<p>and</p>
<pre><code>for username in likes:
</code></pre>
... | 0 | 2016-09-07T15:16:42Z | [
"python",
"tuples",
"svd"
] |
TypeError: list indices must be integers, not tuple in Python SVD model | 39,373,557 | <p>I am testing a recommender based on SVD model. But I got an error message after running it as below: </p>
<p>Here is my testing code:</p>
<pre><code>import sys
from sys import argv
import csv
import recsys.algorithm
recsys.algorithm.VERBOSE = True
from recsys.algorithm.factorize import SVD
from recsys.datamodel.d... | 0 | 2016-09-07T15:10:42Z | 39,373,852 | <p>When you're iterating over list of tuples, each value is tuple itself. Your code suggests that's it's a first element of tuple (or index, I'm not quite sure - what's clear is that it's blatantly wrong).</p>
<pre><code>for username in likes:
# username is now tuple from list
for user_likes in likes[username]... | 0 | 2016-09-07T15:24:15Z | [
"python",
"tuples",
"svd"
] |
How to manage a Apache Spark context in Django? | 39,373,608 | <p>I have a Django application that interacts with a Cassandra database and I want to try using Apache Spark to run operations on this database. I have some experience with Django and Cassandra but I'm new to Apache Spark.</p>
<p>I know that to interact with a Spark cluster first I need to create a SparkContext, somet... | 1 | 2016-09-07T15:13:13Z | 39,583,879 | <p>For the last days I've been working on this, since no one answered I will post what was my approach.</p>
<p>Apparently creating a SparkContext generates a bit of overhead, so stopping the context after every operation is not a good idea. </p>
<p>Also, there is no downfall, apparently, on letting the context live w... | 0 | 2016-09-20T00:15:36Z | [
"python",
"django",
"apache",
"apache-spark"
] |
How to get a max string length in nested lists | 39,373,620 | <p>They is a follow up question to my earlier post (re printing table from a list of lists)</p>
<p>I'm trying t get a string max value of the following nested list:</p>
<pre><code>tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', '... | 3 | 2016-09-07T15:13:49Z | 39,373,664 | <p>You've done the <em>length of the maximum word</em>. This gives the wrong answer because words are ordered <a href="https://en.wikipedia.org/wiki/Lexicographical_order" rel="nofollow">lexicographically</a>:</p>
<pre><code>>>> 'oranges' > 'cherries'
True
</code></pre>
<p>What you probably wanted is the... | 4 | 2016-09-07T15:15:38Z | [
"python"
] |
How to get a max string length in nested lists | 39,373,620 | <p>They is a follow up question to my earlier post (re printing table from a list of lists)</p>
<p>I'm trying t get a string max value of the following nested list:</p>
<pre><code>tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', '... | 3 | 2016-09-07T15:13:49Z | 39,373,687 | <p>You were printing the length of the max element in each row. Python computes the <code>max</code> string element as the one that is seen last in a dictionary (lexicographic sorting). What you want instead is <code>max(len(s) for s in i)</code> instead of <code>len(max(i))</code></p>
<pre><code>for row in tableData:... | -1 | 2016-09-07T15:16:24Z | [
"python"
] |
How to get a max string length in nested lists | 39,373,620 | <p>They is a follow up question to my earlier post (re printing table from a list of lists)</p>
<p>I'm trying t get a string max value of the following nested list:</p>
<pre><code>tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', '... | 3 | 2016-09-07T15:13:49Z | 39,373,727 | <p>In string operations <code>max</code> will Returns the maximum alphabetical character from the string not in basics of length. So u have to do something like this.</p>
<pre><code>len(max(sum(tableData,[]),key=len))
</code></pre>
<p><code>sum(tableData,[])</code> will convert the <code>list of list</code> to <code>... | 0 | 2016-09-07T15:17:59Z | [
"python"
] |
Modify tf-idf vectorizer for some keywords | 39,373,683 | <p>I am creating a tf-idf matrix for finding cosine similarity. But I want some frequent words from a set to have more weightage(i.e, tf-idf value). </p>
<pre><code>tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(documents)
</code></pre>
<p>How can I modify the above tfidf_matri... | 1 | 2016-09-07T15:16:07Z | 39,390,640 | <p>I converted tfidf-matrix of csr-type to 2-D array using,</p>
<pre><code>my_matrix = tfidf_matrix.toarray()
</code></pre>
<p>Then, found out the index of keyword using,</p>
<pre><code>tfidf_vectorizer.vocabulary_.get(keyword)
</code></pre>
<p>After that, Iterated over 2-D matrix and changed the tf-idf value accor... | 0 | 2016-09-08T12:15:41Z | [
"python",
"machine-learning",
"scipy",
"nlp",
"nltk"
] |
Ansible: printing out JSON first level keys names | 39,373,733 | <p>Example :</p>
<pre><code>{
"fw1": {
"ipv4": {
"rtr": {
"ip": "1.2.3.4",
"net": "1.2.3.4",
}
}
},
"fw2": {
"ipv4": {
... | 0 | 2016-09-07T15:18:14Z | 39,374,839 | <p>You don't need to use <code>from_json</code> here:</p>
<pre><code>---
- hosts: localhost
gather_facts: True
vars:
my_json: "{{ lookup('file','test.json') }}"
tasks:
- debug:
msg: "Keys list: {{ my_json.keys() }}"
</code></pre>
| 0 | 2016-09-07T16:12:48Z | [
"python",
"json",
"ansible",
"ansible-playbook"
] |
GAE NDB Expando Model with dynamic Kind | 39,373,752 | <p>Is it possible to assign a dynamic Entity Kind to an Expando Model? For example, I want to use this model for many types of dynamic entities:</p>
<pre><code>class Dynamic(ndb.Expando):
"""
Handles all "Post types", such as Pages, Posts, Users, Products, etc...
"""
col = ndb.StringProperty()
pare... | 0 | 2016-09-07T15:18:48Z | 39,379,038 | <p>I don't know if you can do that, but it sounds dangerous, and GAE updates might break your code.</p>
<p>Using subclasses seems like a much safer alternative. Something like this:</p>
<pre><code>class Dynamic(ndb.Expando):
parent = ndb.IntegerProperty()
name = ndb.StringProperty()
slug = ndb.StringProp... | 1 | 2016-09-07T21:08:23Z | [
"python",
"google-app-engine",
"google-cloud-datastore",
"app-engine-ndb"
] |
Is pandas.DataFrame.groupby Guaranteed To Be Stable? | 39,373,820 | <p>I've noticed that there are several uses of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html"><code>pd.DataFrame.groupby</code></a> followed by an <code>apply</code> implicitly assuming that <code>groupby</code> is <a href="http://stackoverflow.com/questions/1517793/stabil... | 5 | 2016-09-07T15:22:47Z | 39,374,529 | <p>Although the docs don't state this internally, it uses stable sort when generating the groups. </p>
<p>See: </p>
<ul>
<li><a href="https://github.com/pydata/pandas/blob/master/pandas/core/groupby.py#L291" rel="nofollow">https://github.com/pydata/pandas/blob/master/pandas/core/groupby.py#L291</a> </li>
<li><a href=... | 4 | 2016-09-07T15:57:40Z | [
"python",
"pandas",
"group-by",
"language-lawyer"
] |
Python Json to array | 39,373,836 | <p>I want to put json into array.
I have 6 Json links (with the same size but different issues)</p>
<p>That was my try:</p>
<pre><code>data=('0','0')
response = urllib.urlopen(URL)
data[0] = json.loads(response.read())
response = urllib.urlopen(URL)
data[1] = json.loads(response.read())
</code></pre>
<p>Do I have to... | 0 | 2016-09-07T15:23:28Z | 39,374,937 | <p>I would strongly suggest using <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a> (the current documentation does so, too) but you <em>can</em> do:</p>
<pre><code>import json
import urllib2
urls=["http://example.com/json","https://example.com/json2"] # your urls here
data=[]
for u in... | 0 | 2016-09-07T16:17:26Z | [
"python",
"arrays",
"json"
] |
Python Json to array | 39,373,836 | <p>I want to put json into array.
I have 6 Json links (with the same size but different issues)</p>
<p>That was my try:</p>
<pre><code>data=('0','0')
response = urllib.urlopen(URL)
data[0] = json.loads(response.read())
response = urllib.urlopen(URL)
data[1] = json.loads(response.read())
</code></pre>
<p>Do I have to... | 0 | 2016-09-07T15:23:28Z | 39,375,029 | <p>Tuples are immutable which makes them great for sharing between threads, but not so good for frequent changes. Try using a list instead as they are designed for this very use case. That being said, a dictionary can be nice as well:</p>
<pre><code>import json
import urllib.request
data = {}
for url in urls:
w... | 0 | 2016-09-07T16:23:24Z | [
"python",
"arrays",
"json"
] |
Parse JSON find value and append random number? | 39,373,858 | <p>I have a JSON file with login and integer valuer (some result), like this:</p>
<pre><code>[
{
"name":"Tamara",
"results":"434.545.234.664"
},
{
"name":"Ted",
"results":"434.545.234.664"
}
]
</code></pre>
<p>I need to receive user login (na... | 0 | 2016-09-07T15:24:31Z | 39,374,135 | <p>You can <a href="https://docs.python.org/3.5/library/json.html" rel="nofollow">parse your json</a> like this</p>
<pre><code>import json
with open('yourJsonFile.json') as example_data:
data = json.load(example_data)
</code></pre>
<p>And now it's a matter of working with <code>data</code> to find whatever you n... | 0 | 2016-09-07T15:38:44Z | [
"python",
"json",
"input"
] |
Parse JSON find value and append random number? | 39,373,858 | <p>I have a JSON file with login and integer valuer (some result), like this:</p>
<pre><code>[
{
"name":"Tamara",
"results":"434.545.234.664"
},
{
"name":"Ted",
"results":"434.545.234.664"
}
]
</code></pre>
<p>I need to receive user login (na... | 0 | 2016-09-07T15:24:31Z | 39,374,249 | <p>Here's one of the zillion possible ways to code your problem:</p>
<pre><code>import json
import random
import names
random.seed(1)
data = [
{
"name": "Tamara",
"results": "434.545.234.664"
},
{
"name": "Ted",
"results": "434.545.234.664"
}
]
def foo(lst, name):
... | 1 | 2016-09-07T15:44:13Z | [
"python",
"json",
"input"
] |
max() arg is empty error when joining strings | 39,373,988 | <p>I'm new to coding and I was trying to make a script that will join the tuples inside 'sl', which are a sequence of letters, into a new tuple called 's' with the items as strings. and then print out the longest string inside s.</p>
<p>this is the code I came up with (or short version). When I try to print the max it... | 1 | 2016-09-07T15:30:27Z | 39,375,959 | <p>It works, just replace <code>()</code> with <code>[]</code></p>
<pre><code>sl = [['m','o','o','n'],['d','a','y'],['h','e','l','l','o']]
s = []
s = [''.join(i) for i in sl]
print(s)
print(max(s, key=len))
</code></pre>
| 0 | 2016-09-07T17:25:17Z | [
"python",
"join"
] |
Increment attributes of two class without modules? | 39,373,998 | <p>How to make a class which could operate like this without importing other modules?</p>
<pre><code>>>date(2014,2,2) + delta(month=3)
>>(2014, 5, 2)
>>
>>date(2014, 2, 2) + delta(day=3)
>>(2014, 2, 5)
>>date(2014, 2, 2) + delta(year=1, month=2)
>>(2015, 4, 2)
</code></pre>
<... | 0 | 2016-09-07T15:30:48Z | 39,374,238 | <p>Override the <code>__add__</code> method. In the delta class give the <code>__init__</code> default parameters so you can call it with only one or two arguments.</p>
<pre><code>class delta():
def __init__(self,year=0,month=0,day=0):
self.y = year
self.m = month
self.d = day
def __cal... | 1 | 2016-09-07T15:43:28Z | [
"python",
"class",
"attributes"
] |
Pandas: Can you access rolling window items | 39,374,020 | <p>Can you access pandas rolling window object. </p>
<pre><code>rs = pd.Series(range(10))
rs.rolling(window = 3)
#print's
Rolling [window=3,center=False,axis=0]
</code></pre>
<p>Can I get as groups?: </p>
<pre><code>[0,1,2]
[1,2,3]
[2,3,4]
</code></pre>
| 3 | 2016-09-07T15:31:51Z | 39,374,903 | <p>Here's a workaround, but waiting to see if anyone has pandas solution:</p>
<pre><code>def rolling_window(a, step):
shape = a.shape[:-1] + (a.shape[-1] - step + 1, step)
strides = a.strides + (a.strides[-1],)
return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
rolling_window(rs, 3)... | 1 | 2016-09-07T16:15:52Z | [
"python",
"pandas"
] |
Pandas: Can you access rolling window items | 39,374,020 | <p>Can you access pandas rolling window object. </p>
<pre><code>rs = pd.Series(range(10))
rs.rolling(window = 3)
#print's
Rolling [window=3,center=False,axis=0]
</code></pre>
<p>Can I get as groups?: </p>
<pre><code>[0,1,2]
[1,2,3]
[2,3,4]
</code></pre>
| 3 | 2016-09-07T15:31:51Z | 39,380,478 | <p>I will start off this by saying this is reaching in to the internal impl. But if you really really wanted to compute the indexers the same way as pandas.</p>
<p>You will need v0.19.0rc1 (just about released), you can <code>conda install -c pandas pandas=0.19.0rc1</code></p>
<pre><code>In [41]: rs = pd.Series(range... | 0 | 2016-09-07T23:33:50Z | [
"python",
"pandas"
] |
405 error when custom-defined PATCH method is called for Django REST APIView | 39,374,046 | <p>I am making an API call in the test client:</p>
<pre><code>response2 = self.client.patch('/object/update/%d/' %
object_id, {'object_attribute':4})
</code></pre>
<p>The relevant serializer and view class for the object:</p>
<pre><code>class ObjectUpdateSerializer(serializers.ModelSe... | 0 | 2016-09-07T15:33:27Z | 39,519,115 | <p>I faced the same problem. It appeared that it's not allowed to use different views for the same route:</p>
<pre><code>urlpatterns = [
# ...
url('^sessions/?$', views.TokenDelete.as_view()), # Viewer has delete()
url('^sessions/?$', views.TokenEdit.as_view()), # Viewer has patch()
]
</code></pre>
<p>T... | 0 | 2016-09-15T19:41:27Z | [
"python",
"django",
"django-rest-framework",
"http-status-code-405"
] |
Wait until process completes using Python WMI | 39,374,064 | <p>My code launches process on remote host that at the end creates txt file. I want to copy this txt file so I need to wait until the process finish. How can I do that?</p>
<pre><code>import wmi
SW_SHOWNORMAL = 1
con = wmi.WMI(ip, user=username, password=password)
process_startup = con.Win32_ProcessStartup.new()
proce... | 0 | 2016-09-07T15:34:29Z | 39,378,982 | <p>I'm actually working on a similar thing at the moment. If you haven't found your answer, check this link - <a href="http://timgolden.me.uk/python/wmi/cookbook.html#run-notepad-wait-until-it-s-closed-and-then-show-its-text" rel="nofollow">http://timgolden.me.uk/python/wmi/cookbook.html#run-notepad-wait-until-it-s-clo... | 1 | 2016-09-07T21:04:10Z | [
"python",
"process",
"wmi"
] |
Fill NaN values | 39,374,067 | <p>I have a dataframe</p>
<pre><code>TIMESTAMP P_ACT_KW PERIODE_TARIF P_SOUSCR
2016-01-01 00:00:00 116 HC 250
2016-01-01 00:10:00 121 HC 250
2016-01-01 00:20:00 121 NaN 250
</code></pre>
<p>To use this dataframe, I must to fill the NaN values by (HC or HP) based on this condition:</p>
<pre><code>If (hour extracted f... | 2 | 2016-09-07T15:34:55Z | 39,374,271 | <p>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>isin</code></a> to test for membership:</p>
<pre><code>data['PERIODE_TARIF']=np.where(data['PERIODE_TARIF'].isin([0, 1,2, 3, 4, 5, 22, 23]),'HC','HP')
</code></pre>
<p><code>in</code> doesn't understand... | 2 | 2016-09-07T15:45:42Z | [
"python",
"pandas",
"missing-data"
] |
Plotting multiple graphs does not work using pylab | 39,374,075 | <p>I want to visualize the <a href="https://en.wikipedia.org/wiki/Birthday_problem" rel="nofollow">Birthday Problem</a> with different <code>n</code>. My aim is to plot multiple graphs in the same figure but it does not work. It only plots the last graph and ignores the others. I am using the Jupyter Notebook.
This is... | 0 | 2016-09-07T15:35:17Z | 39,374,631 | <p>This isn't a problem with <code>matplotlib</code>; all the lines are there, just on top of each other (which makes perfect sense; for 100 people, the probability for only the first 20 is the same as for a group of just 20 people).</p>
<p>If I quickly plot them with a different line width:</p>
<p><a href="http://i.... | 0 | 2016-09-07T16:02:26Z | [
"python",
"matplotlib",
"jupyter"
] |
unable to install package using pip | 39,374,141 | <p>I am trying to install module using pip and I get this error:</p>
<pre class="lang-none prettyprint-override"><code>$ pip install virtualenv
Collecting virtualenv
Downloading virtualenv-15.0.3-py2.py3-none-any.whl (3.5MB)
100% |âââââââââââââââââââââââââââ... | 0 | 2016-09-07T15:38:57Z | 39,374,426 | <p>the problem is caused because you have not given the super user permission to the system. in order to make any changes into the system you should go to super user mode, for that you have to type the code as</p>
<pre><code>sudo pip install virtualenv
</code></pre>
<p>it will help you out </p>
| 0 | 2016-09-07T15:53:06Z | [
"python",
"pip"
] |
unable to install package using pip | 39,374,141 | <p>I am trying to install module using pip and I get this error:</p>
<pre class="lang-none prettyprint-override"><code>$ pip install virtualenv
Collecting virtualenv
Downloading virtualenv-15.0.3-py2.py3-none-any.whl (3.5MB)
100% |âââââââââââââââââââââââââââ... | 0 | 2016-09-07T15:38:57Z | 39,374,548 | <p>It's probably because the user you are logged as can't install to that folder.</p>
<p><strong>First option</strong>: You can do: </p>
<pre><code>sudo pip install virtualenv
</code></pre>
<p>to download as root user </p>
<p><strong>Second Option</strong>: you could do these commands in sequence in terminal:</p>
... | 0 | 2016-09-07T15:58:12Z | [
"python",
"pip"
] |
SQL / Pandas equivalent | 39,374,195 | <p>What would be the Pandas equivalent for this SQL query :</p>
<pre><code>select column1,
sum(column2) as A,
count(distinct column3) as B,
sum(column2) / count(distinct column3) as C
from table1
group by column1
</code></pre>
<p>Thanks for any help on that!!</p>
| -6 | 2016-09-07T15:41:52Z | 39,374,819 | <p>I'm not sure that the <code>sum(column2) / count(distinct column3) as C</code> part can be done in the same single step, but you can easily do it in two steps:</p>
<p>Demo:</p>
<pre><code>In [47]: df = pd.DataFrame(np.random.randint(0,5,size=(15, 3)), columns=['c1','c2','c3'])
In [48]: df
Out[48]:
c1 c2 c3
0... | 0 | 2016-09-07T16:11:53Z | [
"python",
"sql",
"sql-server",
"pandas",
"dataframe"
] |
Algorithm for checking diagonal in N queens algortihm | 39,374,235 | <p>I am trying to implement N- Queens problem in python. I need a small help in designing the algorithm to check if given a position of Queen check whether any other queen on the board is present on its diagonal or not.</p>
<p>I am trying to design a function diagonal_check(board, row, col) where board is N*N matrix o... | -4 | 2016-09-07T15:43:25Z | 39,374,469 | <p>Let the top left corner be (0,0)</p>
<p>The down-right oriented diagonal for a square (row,col) is <code>col-row+7</code></p>
<p>The up-right oriented diagonal for a square (row,col) is <code>row+col</code></p>
<p>Simply check if 2 queens have the same <code>col-row+7</code> or <code>row+col</code> should tell yo... | 0 | 2016-09-07T15:54:57Z | [
"python",
"algorithm",
"language-agnostic",
"n-queens"
] |
Algorithm for checking diagonal in N queens algortihm | 39,374,235 | <p>I am trying to implement N- Queens problem in python. I need a small help in designing the algorithm to check if given a position of Queen check whether any other queen on the board is present on its diagonal or not.</p>
<p>I am trying to design a function diagonal_check(board, row, col) where board is N*N matrix o... | -4 | 2016-09-07T15:43:25Z | 39,375,457 | <pre><code>boolean diagonalCheck(board, row, col) {
int tempRow ;
int tempCol ;
//algorithm to check left diagonal
if (row >= col) {
tempRow = row-col;
tempCol = 0;
} else {
tempRow = 0;
tempCol = col-row;
}
while (tempRow != N-1 && tempCol != ... | 0 | 2016-09-07T16:51:13Z | [
"python",
"algorithm",
"language-agnostic",
"n-queens"
] |
Python, OpenCV, Raspberry Pi-3 - Attribute Error - 'NoneType' object | 39,374,335 | <p>I am trying to track a green ball with my v2 camera module using openCV and python (using virtualenv), however I keep encountering an <strong>AttributeError: 'NoneType' object has no attribute 'shape'</strong></p>
<h1>Any help would be much appreciated!</h1>
<p>Traceback (most recent call last):</p>
<pre><code> F... | 0 | 2016-09-07T15:48:43Z | 39,389,126 | <p>For anybody experiencing the same issue I have resolved the error by typing the command:</p>
<pre><code> sudo modprobe bcm2835-v4l2
</code></pre>
<p>Works like a charm!</p>
| 0 | 2016-09-08T10:56:20Z | [
"python",
"opencv",
"raspberry-pi",
"virtualenv"
] |
Python find and replace last appearance in list | 39,374,355 | <p>In Python, I have a list of list</p>
<pre><code>list3 = ['PA0', 'PA1']
list2 = ['PB0', 'PB1']
list1 = ['PC0', 'PC1', 'PC2']
[(list1[i], list2[j], list3[k]) for i in xrange(len(list1)) for j in xrange(len(list2)) for k in xrange(len(list3))]
#Result
[('PC0', 'PB0', 'PA0'),
('PC0', 'PB0', 'PA1'),
('PC0', 'PB1', '... | 3 | 2016-09-07T15:49:27Z | 39,374,497 | <p>Process your input list in reverse, then mark the <strong>first</strong> occurrence of any value. You can use a list of sets to track what values you've already seen. Reverse the output list you build when you are done:</p>
<pre><code>seensets = [set() for _ in inputlist[0]]
outputlist = []
for entry in reversed(in... | 3 | 2016-09-07T15:56:02Z | [
"python",
"list"
] |
Python find and replace last appearance in list | 39,374,355 | <p>In Python, I have a list of list</p>
<pre><code>list3 = ['PA0', 'PA1']
list2 = ['PB0', 'PB1']
list1 = ['PC0', 'PC1', 'PC2']
[(list1[i], list2[j], list3[k]) for i in xrange(len(list1)) for j in xrange(len(list2)) for k in xrange(len(list3))]
#Result
[('PC0', 'PB0', 'PA0'),
('PC0', 'PB0', 'PA1'),
('PC0', 'PB1', '... | 3 | 2016-09-07T15:49:27Z | 39,374,713 | <p>If you are not looking for lightning speed here, you could do the following:</p>
<ol>
<li>Flatten the list using <a href="http://stackoverflow.com/a/952952/2988730">http://stackoverflow.com/a/952952/2988730</a></li>
<li>Find the unique elements</li>
<li>Find the index of the last occurrence of each unique element (... | 1 | 2016-09-07T16:06:20Z | [
"python",
"list"
] |
Python find and replace last appearance in list | 39,374,355 | <p>In Python, I have a list of list</p>
<pre><code>list3 = ['PA0', 'PA1']
list2 = ['PB0', 'PB1']
list1 = ['PC0', 'PC1', 'PC2']
[(list1[i], list2[j], list3[k]) for i in xrange(len(list1)) for j in xrange(len(list2)) for k in xrange(len(list3))]
#Result
[('PC0', 'PB0', 'PA0'),
('PC0', 'PB0', 'PA1'),
('PC0', 'PB1', '... | 3 | 2016-09-07T15:49:27Z | 39,375,340 | <p>Another approach that gathers keeps adding the indexes so you end up with the indexes for the last occurrence, <em>itertools.product</em> will also create the initial list for you:</p>
<pre><code>from itertools import product
def last_inds(prod):
# the key/value will be overwritten so we always keep the last s... | 2 | 2016-09-07T16:43:03Z | [
"python",
"list"
] |
Python ASCII Reading tables | 39,374,384 | <p>I'm really sorry for asking probably silly question but I have spend half a day and could not find reasonable solution.
I have ASCII file:</p>
<pre><code> "X" "Z" "Y"
285807.2 -1671.056 2405.91
285807.2 -1651.162 2394.932
285807.2 -1631.269 2383.... | -1 | 2016-09-07T15:51:01Z | 39,395,150 | <p>What I did. I separated columns and added to different lists. Now I have got access for different columns:</p>
<pre><code>import numpy as np
with open('C:\\Users\\Protoss\\Desktop\\Ishodnik.dat' ,'r') as f:
header1 = f.readline()
X_list=[]
Z_list=[]
V_list=[]
for line... | 0 | 2016-09-08T15:40:15Z | [
"python",
"ascii"
] |
Python ASCII Reading tables | 39,374,384 | <p>I'm really sorry for asking probably silly question but I have spend half a day and could not find reasonable solution.
I have ASCII file:</p>
<pre><code> "X" "Z" "Y"
285807.2 -1671.056 2405.91
285807.2 -1651.162 2394.932
285807.2 -1631.269 2383.... | -1 | 2016-09-07T15:51:01Z | 39,471,759 | <p>It's possible to treat the file as CSV and use <code>Sniffer</code> to autodetect the format:</p>
<pre><code>import csv
with open('C:\\Users\\Protoss\\Desktop\\Ishodnik1.dat', 'r') as f:
# Sniff to autodetect the format
dialect = csv.Sniffer().sniff(f.read(1024))
f.seek(0)
reader = csv.reader(f, di... | 0 | 2016-09-13T13:48:27Z | [
"python",
"ascii"
] |
Python bokeh apply hovertools only on model not on figure | 39,374,400 | <p>I want to have a scatter plot and a (base)line on the same figure. And I want to use <code>HoverTool</code> only on the circles of scatter but not on the line. Is it possible?</p>
<p>With the code below I get tooltips with <code>index: 0</code> and <code>(x, y): (???, ???)</code> when I hover on the line (any part ... | 0 | 2016-09-07T15:52:06Z | 39,374,741 | <p>To limit which renderers you want the HoverTool is active on (by default it's active on all) you can either set a <code>name</code> attr on your glyphs, then specify which names you want your HoverTool to be active on:</p>
<pre><code>p.circle('a', 'b', size=10, name='circle', source=source)
hover = HoverTool(names=... | 2 | 2016-09-07T16:07:56Z | [
"python",
"hover",
"tooltip",
"bokeh"
] |
How to install and cron python3 Scrapy on cloud linux | 39,374,448 | <p>I have a Scrapy spider written in python 3 and I want to run it as a cron job on my cloud Linux server (I have root access)
first, I couldn't install using <code>pip3 install scrapy</code>, I faced :</p>
<pre><code>Exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.4/tarfile.py", line 164... | -1 | 2016-09-07T15:54:06Z | 39,374,786 | <p>It appears as though you do not have the bzip module installed on your cloud server. It may very well be linked to a lack of the bzip2 library being missing.</p>
<p>In order to install it, you can type:</p>
<pre><code>apt-get install bzip2
</code></pre>
<p>You may need to prefix that command with <code>sudo</cod... | -1 | 2016-09-07T16:10:05Z | [
"python",
"linux",
"centos",
"scrapy",
"pip"
] |
List comprehension of 2+ variables in R | 39,374,587 | <p>What's the best R equivalent of the Python 2-variable list comprehension</p>
<pre><code>[datetime(y,m,15) for y in xrange(2000,2020) for m in [3,6,9,12]]
</code></pre>
<p>The result</p>
<pre><code>[datetime.datetime(2000, 3, 15, 0, 0),
datetime.datetime(2000, 6, 15, 0, 0),
datetime.datetime(2000, 9, 15, 0, 0),
... | 0 | 2016-09-07T16:00:08Z | 39,374,820 | <p>This will produce equivalent results in R</p>
<pre><code>with(expand.grid(m=c(3,6,9,12), y=2000:2020), ISOdate(y,m,15))
</code></pre>
<p>We use <code>expand.grid</code> to get all combinations of year and month, and then we just use the vectorized <code>ISOdate</code> function to get the values.</p>
| 5 | 2016-09-07T16:11:58Z | [
"python"
] |
DynamoDB Parallel Scan not splitting results | 39,374,617 | <p>I'm using the <code>Segment</code> and <code>TotalSegments</code> parameters to split my DynamoDB scan over multiple workers (as shown in the <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html#QueryAndScanParallelScan" rel="nofollow">Parallel Scan section</a> of the developer ... | 2 | 2016-09-07T16:01:36Z | 39,383,698 | <p>One thing that jumps at me is the filter expression.</p>
<p>It is possible that the items that match your filter expression are located all in the first segment.</p>
<p>It is also worth noting that a parallel scan doesn't split the items, but it splits the key-space that is searched for items. Think of it as divid... | 0 | 2016-09-08T06:13:58Z | [
"python",
"amazon-dynamodb",
"boto",
"aws-lambda"
] |
pandas apply individual logic to group | 39,374,620 | <p>If i have a pandas data frame that looks like:</p>
<pre><code>day id val
1-Jan A -5
2-Jan A -4
3-Jan A 3
1-Jan B 2
2-Jan B 1
3-Jan B -5
</code></pre>
<p>how can i add a new column where, for all rows with the same id, if val was negative on 1-Jan, all rows are "Y" and "N" if not? something... | 2 | 2016-09-07T16:01:41Z | 39,374,957 | <p>Included <code>map</code> per @Ami Tavory's suggestion</p>
<pre><code>gb = df.set_index(['day', 'id']).groupby(level='id')
s = gb.val.transform(lambda s: s.loc['1-Jan'].lt(0)).map({1: 'y', 0:'n'})
s
day id
1-Jan A y
2-Jan A y
3-Jan A y
1-Jan B n
2-Jan B n
3-Jan B n
Name: val, dtype... | 3 | 2016-09-07T16:18:22Z | [
"python",
"pandas"
] |
lxml non-recursive full tag | 39,374,683 | <p>Given the following xml:</p>
<pre><code><node a='1' b='1'>
<subnode x='25'/>
</node>
</code></pre>
<p>I would like to extract the tagname and all attributes for the first node, i.e., the verbatim code:</p>
<pre><code><node a='1' b='1'>
</code></pre>
<p>without the subnode.</p>
<p>For ... | 0 | 2016-09-07T16:04:21Z | 39,375,212 | <p>You can remove all of the subnodes.</p>
<pre><code>from lxml import etree
root = etree.fromstring("<node a='1' b='1'><subnode x='25'>some text</subnode></node>")
for subnode in root.xpath("//subnode"):
subnode.getparent().remove(subnode)
etree.tostring(root) # '<node a="1" b="1"/&g... | 1 | 2016-09-07T16:34:36Z | [
"python",
"recursion",
"lxml"
] |
Urllib problom: AttributeError: 'module' object has no attribute 'maketrans' | 39,374,783 | <p>The environment is Win10 64-bit, Python 2.7.12, Anaconda.
The code is quite simple for web-scrapy:</p>
<pre><code>import urllib
fhand = urllib.urlopen('http://www.reddit.com')
for line in fhand:
print line.strip()
</code></pre>
<p>And the result is weird:</p>
<pre><code>0.8475
Traceback (most recent call las... | 0 | 2016-09-07T16:09:50Z | 39,411,673 | <p>try Spyder, everything works.</p>
<p>still no idea for the problem.</p>
| 0 | 2016-09-09T12:30:58Z | [
"python",
"anaconda",
"urllib"
] |
Fill_in_blank_game. Unable to select level | 39,374,809 | <p>Whenever I type in one of the level options the console prints</p>
<p>"C-3PO: That entry will not compute sir." and then prmpts again.</p>
<p>So in other words I am unable to select the level of the game. I enter in Padawan for example, which is one of the selections and instead of showing the paragraph with blank... | -2 | 2016-09-07T16:11:24Z | 39,376,137 | <p>You have a few problems with your code. First <code>padawan_inputs</code>, <code>jedi_inputs</code>, and <code>master_inputs</code> should each be on a new line. Next this segment:</p>
<pre><code>print "C-3PO: You've selected " + str(choices[chosen_level]) + '!\n'
return choices[chosen_level]
</code></pre>
<p>Shou... | 0 | 2016-09-07T17:37:13Z | [
"python"
] |
How to return the Index when slicing Pandas Dataframe | 39,374,871 | <pre><code> df2= pd.DataFrame(df1.iloc[:, [n for n in random.sample(range(1, 7), 3)]])
</code></pre>
<blockquote>
<p>returns df1 rows and selected columns but it returns a generic index 0,1,2,3..etc instead
of returning the Datetime index of df1 which is what I want to keep. I tried:</p>
</blockquote>
<... | 1 | 2016-09-07T16:14:18Z | 39,374,913 | <p>what about slightly different approach?</p>
<pre><code>In [66]: df
Out[66]:
c1 c2 c3
2016-01-01 4 0 3
2016-01-02 2 3 2
2016-01-03 1 2 3
2016-01-04 3 3 0
2016-01-05 1 0 4
2016-01-06 1 1 1
2016-01-07 2 3 3
2016-01-08 2 2 2
2016-01-09 4 0 0
2016-01-10... | 0 | 2016-09-07T16:16:20Z | [
"python",
"pandas",
"indexing",
"dataframe",
"slice"
] |
How to return the Index when slicing Pandas Dataframe | 39,374,871 | <pre><code> df2= pd.DataFrame(df1.iloc[:, [n for n in random.sample(range(1, 7), 3)]])
</code></pre>
<blockquote>
<p>returns df1 rows and selected columns but it returns a generic index 0,1,2,3..etc instead
of returning the Datetime index of df1 which is what I want to keep. I tried:</p>
</blockquote>
<... | 1 | 2016-09-07T16:14:18Z | 39,375,114 | <p>Try this:</p>
<pre><code>df2 = pd.DataFrame(df1.ix[:,random.sample(range(1,7),3)])
</code></pre>
<p>This will give the result you wanted. </p>
<pre><code>df1
Out[130]:
one two
d NaN 4.0
b 2.0 2.0
c 3.0 3.0
a 1.0 1.0
df1.ix[:,random.sample(range(0,2),2)]
Out[131]:
two one
d 4.0 NaN
b 2.0 2.0... | 2 | 2016-09-07T16:28:18Z | [
"python",
"pandas",
"indexing",
"dataframe",
"slice"
] |
Python create list combination | 39,374,928 | <p>I have a dictionary contain element and sequence count of element. I want to create a list of list that combined from these elements</p>
<p>Example</p>
<pre><code>Input: dictElement = {"PA":2,"PB":2}
Expected Output:
[('PB0', 'PA0'),
('PB0', 'PA1'),
('PB1', 'PA0'),
('PB1', 'PA1')]
</code></pre>
<hr>
<pre><code>... | -5 | 2016-09-07T16:16:45Z | 39,375,044 | <p>You haven't specified in what order the keys of the dictionary should be processed in the output. If one assumes reverse sorting order, you can do this trivially with <code>itertools.product()</code>:</p>
<pre><code>from itertools import product
combinations = product(*(['{0}{1}'.format(v, i) for i in range(dictEl... | 1 | 2016-09-07T16:24:01Z | [
"python",
"combinations"
] |
Create dataframe from specific column | 39,374,995 | <p>I am trying to create a dataframe in Pandas from the <code>AB</code> column in my csv file. (AB is the 27th column).</p>
<p>I am using this line:</p>
<pre><code>df = pd.read_csv(filename, error_bad_lines = False, usecols = [27])
</code></pre>
<p>... which is resulting in this error:</p>
<pre><code>ValueError: Us... | 1 | 2016-09-07T16:20:39Z | 39,375,132 | <p>usecols uses the column name in your csv file rather than the column number.
in your case it should be usecols=['AB'] rather than usecols=[28] that is the reason of your error stating usecols do not match names.</p>
| -1 | 2016-09-07T16:29:13Z | [
"python",
"pandas"
] |
Create dataframe from specific column | 39,374,995 | <p>I am trying to create a dataframe in Pandas from the <code>AB</code> column in my csv file. (AB is the 27th column).</p>
<p>I am using this line:</p>
<pre><code>df = pd.read_csv(filename, error_bad_lines = False, usecols = [27])
</code></pre>
<p>... which is resulting in this error:</p>
<pre><code>ValueError: Us... | 1 | 2016-09-07T16:20:39Z | 39,376,419 | <p>Here is a small demo:</p>
<p>CSV file (without header, i.e. there is NO column names):</p>
<pre><code>1,2,3,4,5,6,7,8,9,10
11,12,13,14,15,16,17,18,19,20
</code></pre>
<p>We are going to read only 8-<code>th</code> column:</p>
<pre><code>In [1]: fn = r'D:\temp\.data\1.csv'
In [2]: df = pd.read_csv(fn, header=Non... | 2 | 2016-09-07T17:55:07Z | [
"python",
"pandas"
] |
using python reserved keyword as variable name | 39,375,023 | <p>im trying to send sms using a webservice , this is what webservice document suggest :</p>
<pre><code>response = client.service.SendSMS( fromNum = '09999999' ,
toNum = '0666666666666',
messageContent = 'test',
messageType = 'normal',
user = 'myusern... | 1 | 2016-09-07T16:22:29Z | 39,375,095 | <p>Maybe try it like this:</p>
<pre><code>sms_kwargs = {
'toNum': '0666666666666',
'messageContent': 'test',
'messageType': 'normal',
'user': 'myusername',
'pass': '123456'
}
response = client.service.SendSMS(**sms_kwargs)
</code></pre>
| 5 | 2016-09-07T16:27:18Z | [
"python",
"django",
"web-services",
"python-3.x"
] |
using python reserved keyword as variable name | 39,375,023 | <p>im trying to send sms using a webservice , this is what webservice document suggest :</p>
<pre><code>response = client.service.SendSMS( fromNum = '09999999' ,
toNum = '0666666666666',
messageContent = 'test',
messageType = 'normal',
user = 'myusern... | 1 | 2016-09-07T16:22:29Z | 39,375,100 | <p>You can pass in arbitrary strings as keyword arguments using the <code>**dictionary</code> call syntax:</p>
<pre><code>response = client.service.SendSMS( fromNum = '09999999' ,
toNum = '0666666666666',
messageContent = 'test',
messageType = 'normal',
... | 7 | 2016-09-07T16:27:34Z | [
"python",
"django",
"web-services",
"python-3.x"
] |
How to multiply pandas dataframes and preserve row keys | 39,375,069 | <p>I'm struggling with multiplying dataframes together and preserving the row keys.</p>
<p>I have two files, call them say F1 and F2. F1 has a multi-part group key (g1,g2,g3), a two-part Type key (k1,k2) and some weights (r1,r2). F2 has a series of values for each Type key.</p>
<p>I'd like to join them on k1 and k2, ... | 3 | 2016-09-07T16:25:39Z | 39,375,425 | <pre><code>mrg = F1.merge(F2, on=['k1', 'k2'])
mrg['r1'] = mrg.filter(like='r1').prod(1)
mrg['r2'] = mrg.filter(like='r2').prod(1)
drops = ['r1_x', 'r1_y', 'r2_x', 'r2_y']
mrg.drop(drops, axis=1)
</code></pre>
<p><a href="http://i.stack.imgur.com/NR963.png" rel="nofollow"><img src="http://i.stack.imgur.com/NR963.png"... | 2 | 2016-09-07T16:48:52Z | [
"python",
"pandas",
"dataframe"
] |
Writing to a specific dictionary inside a json file Python | 39,375,090 | <p>I have a .json file with some information </p>
<pre><code>{"items": [{"phone": "testp"}, {"phone": "Test2"}]}
</code></pre>
<p>I want to add another dictionary into the next available slot in the array with some more information. I have tried many ways however no of them work, has anyone got any ideas?</p>
| -1 | 2016-09-07T16:27:04Z | 39,375,202 | <pre><code>dictionary["items"].append(new_dictionary)
</code></pre>
<p>You access key "items" in your dictionary, which is a list of dictionaries, to that list you simply append your new dictionary</p>
| 0 | 2016-09-07T16:33:45Z | [
"python",
"json",
"dictionary"
] |
Writing to a specific dictionary inside a json file Python | 39,375,090 | <p>I have a .json file with some information </p>
<pre><code>{"items": [{"phone": "testp"}, {"phone": "Test2"}]}
</code></pre>
<p>I want to add another dictionary into the next available slot in the array with some more information. I have tried many ways however no of them work, has anyone got any ideas?</p>
| -1 | 2016-09-07T16:27:04Z | 39,375,206 | <p>You can read the json into a variable using load function.</p>
<p>And then append the value of array using </p>
<pre><code>myVar["items"].append(dictVar)
</code></pre>
| 0 | 2016-09-07T16:34:08Z | [
"python",
"json",
"dictionary"
] |
can't workout why getting a type error on __init__ | 39,375,092 | <p>Hope someone can help me...</p>
<p>Have the following:</p>
<p>smartsheet_test.py</p>
<pre><code>from pfcms.content import Content
def main():
ss = Content()
ss.smartsheet()
if __name__ == "__main__":
main()
</code></pre>
<p>content.py</p>
<pre><code>import smartsheet as ss
class Content:
""" P... | 1 | 2016-09-07T16:27:07Z | 39,375,141 | <p>You have (or had) a file called <code>smartsheet.py</code> in your current working directory. Delete or rename that file, and delete any related <code>.pyc</code> file.</p>
| 1 | 2016-09-07T16:29:34Z | [
"python",
"class",
"smartsheet-api"
] |
Repeat list if index range is out of bounds | 39,375,122 | <p>I have a Python list</p>
<pre><code>a = [1, 2, 3, 4]
</code></pre>
<p>and I'd like to get a range of indices such that if I select the indices <code>0</code> through <code>N</code>, I'm getting (for <code>N=10</code>) the repeated</p>
<pre><code>[1, 2, 3, 4, 1, 2, 3, 4, 1, 2]
</code></pre>
<p>I could of cour... | 2 | 2016-09-07T16:28:44Z | 39,375,166 | <p>You can simply use the modulo operator when accessing the list, i.e.</p>
<pre><code>a[i % len(a)]
</code></pre>
<p>This will give you the same result, but doesn't require to actually store the redundant elements.</p>
| 6 | 2016-09-07T16:31:20Z | [
"python"
] |
Repeat list if index range is out of bounds | 39,375,122 | <p>I have a Python list</p>
<pre><code>a = [1, 2, 3, 4]
</code></pre>
<p>and I'd like to get a range of indices such that if I select the indices <code>0</code> through <code>N</code>, I'm getting (for <code>N=10</code>) the repeated</p>
<pre><code>[1, 2, 3, 4, 1, 2, 3, 4, 1, 2]
</code></pre>
<p>I could of cour... | 2 | 2016-09-07T16:28:44Z | 39,375,175 | <p>You can use <a href="https://docs.python.org/3.6/library/itertools.html#itertools.cycle" rel="nofollow"><code>itertools.cycle</code></a> and <a href="https://docs.python.org/3.6/library/itertools.html#itertools.islice" rel="nofollow"><code>itertools.islice</code></a>:</p>
<pre><code>from itertools import cycle, isl... | 4 | 2016-09-07T16:31:45Z | [
"python"
] |
Repeat list if index range is out of bounds | 39,375,122 | <p>I have a Python list</p>
<pre><code>a = [1, 2, 3, 4]
</code></pre>
<p>and I'd like to get a range of indices such that if I select the indices <code>0</code> through <code>N</code>, I'm getting (for <code>N=10</code>) the repeated</p>
<pre><code>[1, 2, 3, 4, 1, 2, 3, 4, 1, 2]
</code></pre>
<p>I could of cour... | 2 | 2016-09-07T16:28:44Z | 39,375,447 | <pre><code>>>> a = [1, 2, 3, 4]
>>> (a*3)[:-2]
>>> [1, 2, 3, 4, 1, 2, 3, 4, 1, 2]
</code></pre>
| 0 | 2016-09-07T16:50:02Z | [
"python"
] |
Repeat list if index range is out of bounds | 39,375,122 | <p>I have a Python list</p>
<pre><code>a = [1, 2, 3, 4]
</code></pre>
<p>and I'd like to get a range of indices such that if I select the indices <code>0</code> through <code>N</code>, I'm getting (for <code>N=10</code>) the repeated</p>
<pre><code>[1, 2, 3, 4, 1, 2, 3, 4, 1, 2]
</code></pre>
<p>I could of cour... | 2 | 2016-09-07T16:28:44Z | 39,375,520 | <p>Thought I would offer a solution using the <code>*</code> operator for lists.</p>
<pre><code>import math
def repeat_iterable(a, N):
factor = N / len(a) + 1
repeated_list = a * factor
return repeated_list[:N]
</code></pre>
<p><strong>Sample Output:</strong></p>
<pre><code>>>> print repeat_ite... | 1 | 2016-09-07T16:54:52Z | [
"python"
] |
Repeat list if index range is out of bounds | 39,375,122 | <p>I have a Python list</p>
<pre><code>a = [1, 2, 3, 4]
</code></pre>
<p>and I'd like to get a range of indices such that if I select the indices <code>0</code> through <code>N</code>, I'm getting (for <code>N=10</code>) the repeated</p>
<pre><code>[1, 2, 3, 4, 1, 2, 3, 4, 1, 2]
</code></pre>
<p>I could of cour... | 2 | 2016-09-07T16:28:44Z | 39,376,351 | <p>How about faking it? Python is good at faking.</p>
<pre><code>class InfiniteList(object):
def __init__(self, data):
self.data = data
def __getitem__(self, i):
return self.data[i % len(self.data)]
x = InfiniteList([10, 20, 30])
x[0] # 10
x[34] # 20
</code></pre>
<p>Of course, you could ad... | 0 | 2016-09-07T17:51:41Z | [
"python"
] |
Repeat list if index range is out of bounds | 39,375,122 | <p>I have a Python list</p>
<pre><code>a = [1, 2, 3, 4]
</code></pre>
<p>and I'd like to get a range of indices such that if I select the indices <code>0</code> through <code>N</code>, I'm getting (for <code>N=10</code>) the repeated</p>
<pre><code>[1, 2, 3, 4, 1, 2, 3, 4, 1, 2]
</code></pre>
<p>I could of cour... | 2 | 2016-09-07T16:28:44Z | 39,384,792 | <p>One easy way is to use modulo with list comprehensions à la </p>
<pre><code>a = [1, 2, 3 ,4]
[k % len(a) for k in range(10)]
</code></pre>
| 1 | 2016-09-08T07:19:33Z | [
"python"
] |
Is there a way to reduce the amount of code for RMSProp | 39,375,173 | <p>I have some code for a simple recurrent neural network and would like to know if there is a way for me to reduce the amount of code necessary for my update stage. The code I have so for:</p>
<pre><code>class RNN(object):
def__init___(self, data, hidden_size, eps=0.0001):
self.data = data
self.hi... | 1 | 2016-09-07T16:31:39Z | 39,376,556 | <p>Judging from your question, I am guessing that you are trying to improve readability/elegance over any other kind of optimization here.</p>
<p>You can introduce a function to implement the update rule, then call it once for each variable. The trick here is that Python lets you access attributes by name, so you can ... | 1 | 2016-09-07T18:05:16Z | [
"python"
] |
Python netcdf plot data onto grid | 39,375,227 | <p>I am using Lat, Lon data and would like to average all the sample_data within a grid cell (say 1km x 1km) uniformly across the whole area, and then plot it similar to this post, but with a basemap, I'm a bit stuck where to start:
<a href="http://stackoverflow.com/questions/25071968/heatmap-with-text-in-each-cell-wi... | 0 | 2016-09-07T16:35:34Z | 39,376,054 | <p>Well, you can get the maximum and minimum of latitude and longitude. </p>
<p>And then get the age of <code>sample_data</code> at a particular time <code>t</code> using:</p>
<pre><code>data_within_box = sample_data[minLat:maxLat,minLon:maxLon,:,t]
avg_age = numpy.average(data_within_box)
</code></pre>
| 0 | 2016-09-07T17:31:26Z | [
"python",
"matplotlib",
"grid",
"netcdf"
] |
Python netcdf plot data onto grid | 39,375,227 | <p>I am using Lat, Lon data and would like to average all the sample_data within a grid cell (say 1km x 1km) uniformly across the whole area, and then plot it similar to this post, but with a basemap, I'm a bit stuck where to start:
<a href="http://stackoverflow.com/questions/25071968/heatmap-with-text-in-each-cell-wi... | 0 | 2016-09-07T16:35:34Z | 40,142,235 | <p>This is a crude way of doing it:</p>
<pre><code>lat_1 = 58
lat_2 = 60
lon_1 = 2
lon_2 = 5
size = 0
age2 = 0
for parts in range(10):
for length in range(len(lon)):
if lon[length,parts] < lon_2:
if lon[length,parts] > lon_1:
if lat[length,parts] > lat_1:
... | 0 | 2016-10-19T22:01:05Z | [
"python",
"matplotlib",
"grid",
"netcdf"
] |
Run a .bat file from a Python CGI file with Apache Webserver | 39,375,244 | <p>This might be really easy. But its just not working for me. </p>
<p>I have a .bat file I would like to run, which performs stuff on the Server, and should send an email with an Attachement.</p>
<p>The .bat file works fine, it sends the email with the log and everything. </p>
<p>Now I would like to run that file ... | 2 | 2016-09-07T16:36:18Z | 39,375,547 | <p>You can invoke the batch file with <code>cmd.exe</code>:</p>
<pre><code>...
cmd = r'c:\Windows\System32\cmd.exe'
batDir = r'C:\Path\to\batchfolder'
batName = r'batch.bat'
p = Popen(r"{0} /C {1}\{2}".format(cmd,batDir,batName), cwd=batDir)
...
</code></pre>
| 0 | 2016-09-07T16:56:15Z | [
"python",
"windows",
"apache",
"batch-file"
] |
In python, append dictionary value with each element in array | 39,375,250 | <p>Hi and thank you so much for your help!</p>
<p>I am sure this is a dumb question but I am trying to append a dictionary value with the elements within an array. Right now I can only get it to load the entire array of elements as one entry instead of separate values. Sorry if I am not explaining this well. Here is a... | -2 | 2016-09-07T16:36:49Z | 39,375,322 | <p>If you want to append an entire list to an existing list, you can just use <code>extend()</code>:</p>
<pre><code>a = [4,5,6]
d = {'index': [1,2,3]}
d['index'].extend(a)
</code></pre>
<p>output:</p>
<pre><code>{'index': [1, 2, 3, 4, 5, 6]}
</code></pre>
<p>If you want to end up with a list containing two lists, [... | 3 | 2016-09-07T16:42:11Z | [
"python",
"arrays",
"dictionary",
"append"
] |
Training TensorFlow to predict a sum | 39,375,283 | <p>The TensorFlow provided examples are a little complicated for getting started, so I am trying to teach TensorFlow train a neural network to predict the sum of three binary digits. The network gets two of them as inputs; the third one is unknown. So an "optimal" network would guess that the sum will be the sum of the... | 2 | 2016-09-07T16:39:27Z | 39,376,780 | <p>I'm not sure whether this code is what you wanted to get, but i hope you would find it useful anyway. Mean squared error is actually decreasing along the iterations, though I haven't tested it for making predictions, so it's up to you!</p>
<pre><code>import tensorflow as tf
import numpy as np
from random import r... | 1 | 2016-09-07T18:22:28Z | [
"python",
"tensorflow"
] |
Pandas optimization for multiple records | 39,375,285 | <p>I have a file with around 500K records.
Each record needs to be validated.
Records are de duplicated and store in a list:</p>
<pre><code>with open(filename) as f:
records = f.readlines()
</code></pre>
<p>The validation file I used is stored in a Pandas Dataframe
This DataFrame contains around 80K records and 9... | 0 | 2016-09-07T16:39:34Z | 39,382,590 | <p>While no data is available, consider this untested approach with a couple of left join merges of both data pieces and then run the validation steps. This would avoid any looping and run conditional logic across columns:</p>
<pre><code>import pandas as pd
import numpy as np
with open('RecordsValidate.txt') as f:
... | 2 | 2016-09-08T04:25:22Z | [
"python",
"pandas"
] |
Attendees in Google Calendar not always in the same order | 39,375,401 | <p>So I've just started using the google calendar api and I've had good results so far. I add attendees with their name and email in the <code>events</code> dictionary, like so</p>
<pre><code>events = {
# other stuff here and then this
'items': [
# lots of stuff here,... | -1 | 2016-09-07T16:47:17Z | 39,380,726 | <p>So, as @Colonel Thirty Two pointed out, while lists preserve order, how google return data into a list may not be in the same order as it was submitted to them. This order inconsistency with attendees is inconvenient if you are wanting to count on that order for the retrieval of attendees with something like</p>
<p... | 0 | 2016-09-08T00:09:35Z | [
"python",
"python-2.7",
"google-calendar"
] |
Python: Create list from function that returns single item or another list | 39,375,420 | <p>(Python 3.5). </p>
<p><strong>Problem Statement:</strong> Given a function that returns either an item or a list of items, is there a single line statement that would initialize a new list from the results of calling the aforementioned function?</p>
<p><strong>Details:</strong> I've looked at the documents on pyth... | 2 | 2016-09-07T16:48:37Z | 39,375,493 | <p>If you're looking for a one-liner about listifying the result of a function call:</p>
<p>Let's say there's a function called <code>func</code> that returns either an item or a list of items:</p>
<pre><code>elem = func()
answer = elem if isinstance(elem, list) else [elem]
</code></pre>
<p>That being said, you shou... | 4 | 2016-09-07T16:53:19Z | [
"python",
"list"
] |
Python: Create list from function that returns single item or another list | 39,375,420 | <p>(Python 3.5). </p>
<p><strong>Problem Statement:</strong> Given a function that returns either an item or a list of items, is there a single line statement that would initialize a new list from the results of calling the aforementioned function?</p>
<p><strong>Details:</strong> I've looked at the documents on pyth... | 2 | 2016-09-07T16:48:37Z | 39,375,494 | <p>You may check it like in one line as:</p>
<pre><code> if item: # Check whether it is not None or empty list
# Check if it is list. If not, append it to existing list after converting it to list
_new_list.extend(item if isiinstance(item, list) else [item])
</code></pre>
| 1 | 2016-09-07T16:53:22Z | [
"python",
"list"
] |
Python: Create list from function that returns single item or another list | 39,375,420 | <p>(Python 3.5). </p>
<p><strong>Problem Statement:</strong> Given a function that returns either an item or a list of items, is there a single line statement that would initialize a new list from the results of calling the aforementioned function?</p>
<p><strong>Details:</strong> I've looked at the documents on pyth... | 2 | 2016-09-07T16:48:37Z | 39,375,873 | <p>Another way of doing this in a single line is</p>
<pre><code>def force_list(item_or_list=[]):
return item_or_list if type(item_or_list) is list else [item_or_list]
</code></pre>
<p>print force_list("test")</p>
<blockquote>
<p>test</p>
</blockquote>
<p>print force_list(["test","test2"])</p>
<blockquote>
... | 0 | 2016-09-07T17:20:33Z | [
"python",
"list"
] |
Using a function to calculate new column values from old column values in pandas row by row | 39,375,460 | <p>I know there are many questions on this topic, but none of the suggested answers seem to work in this case, which I thought was trivial, but has been killing me for 2 days now.</p>
<p>This is my first effort to use pandas to process an export file from an eye-tracker. The export file contains 50 or so columns and 2... | 0 | 2016-09-07T16:51:23Z | 39,375,711 | <p>There's an easy way to achieve your goal while operating on whole columns.</p>
<pre><code>dfd.replace({-1:np.nan}, inplace=True)
dfd['PupilAvg'] = dfd.mean(axis=1)
</code></pre>
<p>If you need to retain the original -1 values for some reason, just copy them first and then proceed. Everything in pandas is easier wi... | 0 | 2016-09-07T17:08:48Z | [
"python",
"pandas",
"dataframe",
"calculated-columns"
] |
Using XML ElementTree to create list of objects with atrributes | 39,375,482 | <p>I use the python requests module to get XML from the TeamCity rest api that looks like this:</p>
<pre><code><triggers count="10">
<trigger id="TRIGGER_1240" type="buildDependencyTrigger">
<properties count="2">
<property name="afterSuccessfulBuildOnly" value="true"/>
<... | 0 | 2016-09-07T16:52:38Z | 39,375,528 | <p>Not directly answering the question, but you may be reinventing the wheel here, check <a href="http://lxml.de/objectify.html" rel="nofollow"><code>lxml.objectify</code> package</a>:</p>
<blockquote>
<p>The main idea is to hide the usage of XML behind normal Python
objects, sometimes referred to as data-binding.... | 0 | 2016-09-07T16:55:26Z | [
"python",
"xml",
"class",
"object",
"elementtree"
] |
Using XML ElementTree to create list of objects with atrributes | 39,375,482 | <p>I use the python requests module to get XML from the TeamCity rest api that looks like this:</p>
<pre><code><triggers count="10">
<trigger id="TRIGGER_1240" type="buildDependencyTrigger">
<properties count="2">
<property name="afterSuccessfulBuildOnly" value="true"/>
<... | 0 | 2016-09-07T16:52:38Z | 39,376,275 | <p>Simple syntax mistake:</p>
<pre><code>for triggerProperty in trigger.iter('property'):
propertyName = triggerProperty.get('name')
propertyValue = triggerProperty.get('value')
propDict = {propertyName : propertyValue}
triggerName.add_property(propDict)
</code></pre>
<p>I was iteratin... | 0 | 2016-09-07T17:45:45Z | [
"python",
"xml",
"class",
"object",
"elementtree"
] |
Renaming files in Python: No such file or directory | 39,375,483 | <p>If I try to rename files in a directory, for some reason I get an error.
I think the problem may be that I have not inserted the directory in the proper format ?</p>
<p>Additional info:
python 2 &
linux machine</p>
<blockquote>
<p>OSError: [Errno 2] No such file or directory</p>
</blockquote>
<p>Though it p... | 0 | 2016-09-07T16:52:42Z | 39,375,596 | <p><code>os.rename()</code> is expecting the full path to the file you want to rename. <code>os.listdir</code> only returns the filenames in the directory. Try this</p>
<pre><code>import os
baseDir = "/home/fanna/Videos/strange/"
for i in os.listdir( baseDir ):
os.rename( baseDir + i, baseDir + i[:-17] )
</code></... | 3 | 2016-09-07T16:59:20Z | [
"python"
] |
Renaming files in Python: No such file or directory | 39,375,483 | <p>If I try to rename files in a directory, for some reason I get an error.
I think the problem may be that I have not inserted the directory in the proper format ?</p>
<p>Additional info:
python 2 &
linux machine</p>
<blockquote>
<p>OSError: [Errno 2] No such file or directory</p>
</blockquote>
<p>Though it p... | 0 | 2016-09-07T16:52:42Z | 39,375,598 | <p>Suppose there is a file <code>/home/fanna/Videos/strange/name_of_some_video_file.avi</code>, and you're running the script from <code>/home/fanna</code>.</p>
<p><code>i</code> is <code>name_of_some_video_file.avi</code> (the name of the file, not including the full path to it). So when you run</p>
<pre><code>os.re... | 2 | 2016-09-07T16:59:23Z | [
"python"
] |
Improve the quality of the letters in a image | 39,375,498 | <p>I'm working with images that have text. The problem is that these images are receipts, and after a lot of transformations, the text lost quality.
I'm using python and opencv.
I was trying with a lot of combinations of morphological transformations from the doc <a href="http://docs.opencv.org/3.0-beta/doc/py_tutoria... | 1 | 2016-09-07T16:53:38Z | 39,376,668 | <p>Did you consider the neighboring pixels and add sum of them.</p>
<p>For example:</p>
<pre><code>n = numpy.zeros((3,3))
s = numpy.zeros((3,3))
w = numpy.zeros((3,3))
e = numpy.zeros((3,3))
n[0][1] = 1
s[2][1] = 1
w[1][0] = 1
e[1][2] = 1
img_n = cv2.erode(img, n, iterations=1)
img_s = cv2.erode(img, s, iterations=... | 0 | 2016-09-07T18:13:44Z | [
"python",
"image",
"opencv",
"letters"
] |
Improve the quality of the letters in a image | 39,375,498 | <p>I'm working with images that have text. The problem is that these images are receipts, and after a lot of transformations, the text lost quality.
I'm using python and opencv.
I was trying with a lot of combinations of morphological transformations from the doc <a href="http://docs.opencv.org/3.0-beta/doc/py_tutoria... | 1 | 2016-09-07T16:53:38Z | 39,386,810 | <p>In my experience erode impairs OCR quality. If you have grayscale image (not binary) you can use better binarization algorithm. I use SAUVOLA algorithm for binarization. If you have only binary image the best thing you can do is removing the noise (remove all small dots). </p>
| 0 | 2016-09-08T09:04:27Z | [
"python",
"image",
"opencv",
"letters"
] |
Is this approach "vectorized" - used against medium dataset it is relatively slow | 39,375,546 | <p>I have this data frame:</p>
<pre><code>df = pd.DataFrame({'a' : np.random.randn(9),
'b' : ['foo', 'bar', 'blah'] * 3,
'c' : np.random.randn(9)})
</code></pre>
<p>This function:</p>
<pre><code>def my_test2(row, x):
if x == 'foo':
blah = 10
if x == 'bar':
blah = 20
... | 2 | 2016-09-07T16:56:10Z | 39,376,939 | <p>As Andrew, Ami Tavory and Sohier Dane have already mentioned in comments there are two "slow" things in your solution:</p>
<ol>
<li><code>.apply()</code> is generally slow as it loops under the hood.</li>
<li><code>.apply(..., axis=1)</code> is <strong>extremely</strong> slow (even compared to <code>.apply(..., axi... | 2 | 2016-09-07T18:34:59Z | [
"python",
"pandas",
"dataframe"
] |
How to return (a varying number of) objects with their original name in a function in Python | 39,375,580 | <p>I'm very new to Python. I'm looking to return a varying number of objects (will eventually be <code>lists</code> or <code>pandas</code>), ideally with their original name.</p>
<p>So far I'm looking at something like this:</p>
<pre><code>def function(*Args):
Args = list(Args)
for i in range(len(Args)):
... | 0 | 2016-09-07T16:58:17Z | 39,375,656 | <p>Are you just looking to return the tuple?</p>
<pre><code>def function(*Args):
Args = list(Args)
for i in range(len(Args)):
Args[i] += 1
print Args[i]
return Args
a, b, c, d = function(a, b, c, d)
</code></pre>
| 0 | 2016-09-07T17:04:14Z | [
"python",
"args"
] |
How to return (a varying number of) objects with their original name in a function in Python | 39,375,580 | <p>I'm very new to Python. I'm looking to return a varying number of objects (will eventually be <code>lists</code> or <code>pandas</code>), ideally with their original name.</p>
<p>So far I'm looking at something like this:</p>
<pre><code>def function(*Args):
Args = list(Args)
for i in range(len(Args)):
... | 0 | 2016-09-07T16:58:17Z | 39,387,916 | <p>In the meantime I tried it as @Xavier C. suggested and it seems to work. the lists/input arguments i would name after the industry and would therefore like to preseve. Is there any way to achieve that?</p>
<pre><code>def BBGLiveRequest(*args):
data = []
for i in range(len(args)):
print args[i]
... | 0 | 2016-09-08T09:57:11Z | [
"python",
"args"
] |
Is it possible to stack line graphs with df.plot() and if not how can it be done? | 39,375,618 | <p><a href="http://i.stack.imgur.com/2M0iT.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/2M0iT.jpg" alt="enter image description here"></a></p>
<p>I want to create something like this figure with a dataframe that contains 9 columns.</p>
| -1 | 2016-09-07T17:01:13Z | 39,375,976 | <p>Use the area type:</p>
<pre><code>df.plot(kind='area')
</code></pre>
<p>Starting pandas version 0.17:</p>
<pre><code>df.plot.area()
</code></pre>
| 1 | 2016-09-07T17:26:54Z | [
"python",
"pandas"
] |
How to see the plot made in python using pandas and matplotlib | 39,375,660 | <p>I am following the tutorial <a href="http://ahmedbesbes.com/how-to-score-08134-in-titanic-kaggle-challenge.html" rel="nofollow">http://ahmedbesbes.com/how-to-score-08134-in-titanic-kaggle-challenge.html</a> and following is my code</p>
<pre><code>from IPython.core.display import HTML
HTML("""
<style>
.output_... | 2 | 2016-09-07T17:04:24Z | 39,375,729 | <p>Try using <code>plt.show()</code> at the end.</p>
<p>EDIT:</p>
<p>Also, you may need to add <code>%matplotlib inline</code> as explained here: <a href="http://stackoverflow.com/questions/19410042/how-to-make-ipython-notebook-matplotlib-plot-inline">How to make IPython notebook matplotlib plot inline</a></p>
| 1 | 2016-09-07T17:09:53Z | [
"python",
"matplotlib"
] |
translate() takes exactly one argument (2 given) in python error | 39,375,712 | <pre><code>import os
import re
def rename_files():
# get the files from dir
file_list=os.listdir(r"C:\OOP\prank")
print(file_list)
saved_path=os.getcwd()
print("current working directory"+saved_path)
os.chdir(r"C:\OOP\prank")
#rename the files
for file_name in file_list:
print("... | -2 | 2016-09-07T17:08:56Z | 39,375,924 | <p>Instead of translate why not just do this:</p>
<pre><code>os.rename(file_name,''.join([i for i in file_name if not i.isdigit()]))
</code></pre>
| 0 | 2016-09-07T17:23:25Z | [
"python",
"string",
"file"
] |
translate() takes exactly one argument (2 given) in python error | 39,375,712 | <pre><code>import os
import re
def rename_files():
# get the files from dir
file_list=os.listdir(r"C:\OOP\prank")
print(file_list)
saved_path=os.getcwd()
print("current working directory"+saved_path)
os.chdir(r"C:\OOP\prank")
#rename the files
for file_name in file_list:
print("... | -2 | 2016-09-07T17:08:56Z | 39,375,994 | <p><code>str.translate</code> requires a <code>dict</code> that maps unicode ordinals to other unicode oridinals (or <code>None</code> if you want to remove the character). You can create it like so:</p>
<pre><code>old_string = "file52.txt"
to_remove = "0123456789"
table = {ord(char): None for char in to_remove}
new_s... | 1 | 2016-09-07T17:27:53Z | [
"python",
"string",
"file"
] |
django-tinymce widget not outputting correct error message | 39,375,745 | <p>I just set up django-tinymce and made some changes to my form to do it. However, now my form is no longer outputting the correct error message.</p>
<p>My form:</p>
<pre><code>TITLE_LENGTH_ERROR = "This title is too long, please make it 200 characters or less."
TITLE_EMPTY_ERROR = "Youâll have to add a title."
TE... | 0 | 2016-09-07T17:11:16Z | 39,392,900 | <p>Ok so a little more explanation and a couple links that might help shed some light on this. In the official Django documentation (<a href="https://docs.djangoproject.com/en/1.10/ref/forms/fields/" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/forms/fields/</a>) there is an example of using form field va... | 1 | 2016-09-08T13:56:49Z | [
"python",
"django",
"django-forms",
"tinymce",
"django-tinymce"
] |
Is that Insertionsort? | 39,375,805 | <p>I really need your help, I am learning sorting-algorithms and i tried to make an Insertionsort-Algorithm. So could you please tell me whether this is an Insertionsort-Algorithm or not?</p>
<pre><code>def insertsort(l):
for k in range(len(l)):
for i in range(1,len(l)):
if l[i]<l[i-1]:
... | -2 | 2016-09-07T17:16:29Z | 39,375,992 | <p>yes, it is insertion sort. The pseudocode is as follows:</p>
<pre><code>1. for j = 2 to n
2. key â A [j]
3. // Insert A[j] into the sorted sequence A[1..j-1]
4. j â i â 1
5. while i > 0 and A[i] > key
6. A[i+1] â A[i]
7. i â... | 0 | 2016-09-07T17:27:51Z | [
"python",
"algorithm",
"sorting"
] |
Is that Insertionsort? | 39,375,805 | <p>I really need your help, I am learning sorting-algorithms and i tried to make an Insertionsort-Algorithm. So could you please tell me whether this is an Insertionsort-Algorithm or not?</p>
<pre><code>def insertsort(l):
for k in range(len(l)):
for i in range(1,len(l)):
if l[i]<l[i-1]:
... | -2 | 2016-09-07T17:16:29Z | 39,376,568 | <p>I do not think so. You used two nested <strong>for</strong> loops and a <strong>while</strong>. In the pseudocode provided by @dreadedHarvester and the implementation provided in <a href="https://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort#Python" rel="nofollow">RosettaCode</a> just one <strong>for</stron... | 0 | 2016-09-07T18:06:39Z | [
"python",
"algorithm",
"sorting"
] |
django rest framework manually display 404 page | 39,375,826 | <p>So I have typical generic view:</p>
<pre><code>class FooListAPIView(generics.ListAPIView):
serializer_class = FooSerializer
lookup_fields = ('area_id', 'category_id', )
def get_queryset(self):
area = Area.objects.get(pk=self.kwargs.get('area_id'))
area_tree = area.get_tree(parent=area) ... | 2 | 2016-09-07T17:17:40Z | 39,376,960 | <p>The problem here is that <code>get_queryset</code> doesn't really expect any failures. In your case, although you are returning a queryset, you seem to be hitting the database with the <code>Area.objects.get(pk=self.kwargs.get('area_id'))</code> call. When this fails, it violates the I/O defined by <code>get_queryse... | 0 | 2016-09-07T18:36:10Z | [
"python",
"django",
"django-rest-framework"
] |
Create pandas dataframe column from another column that has dictionary keys | 39,375,878 | <p>I have dataframe and a dict. These look like,</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'first':['john','oliver','sarah']})
df1_map = {'john': 'anderson', 'oliver': 'smith', 'sarah' : 'shively'}
print (df1)
print (df1_map)
first
0 john
1 oliver
2 sarah
{'oliver': 'smith', 'sarah': 'shively',... | 2 | 2016-09-07T17:20:52Z | 39,375,928 | <p>You can just map dictionaries values directly to the keys with:</p>
<pre><code>df1['last'] = df1['first'].map(df1_map)
</code></pre>
<p>result is:</p>
<pre><code>Out[6]:
first last
0 john anderson
1 oliver smith
2 sarah shively
</code></pre>
| 5 | 2016-09-07T17:23:43Z | [
"python",
"pandas"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.