title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
python pandas dtypes detection from sql | 39,298,989 | <p>I am quite troubled by the behaviour of Pandas DataFrame about Dtype detection.</p>
<p>I use 'read_sql_query' to retrieve data from a database to build a DataFrame, and then dump it into a csv file.</p>
<p>I don't need any transformation. Just dump it into a csv file and change date fields in the form : <strong>'%... | 0 | 2016-09-02T18:50:06Z | 39,353,121 | <p>Thanks to Boud and Parfait. Their answers are right : </p>
<p>All my tests shows that missing date fields can make Dtype detection to fail.</p>
<p>read_sql_query() has a parameter to define fields with date type. I guess to cure this problem.</p>
<p>Sadly, since now, I have been using a complete generic treatment... | 0 | 2016-09-06T15:51:17Z | [
"python",
"sql",
"csv",
"pandas",
"dataframe"
] |
scraping css values using scrapy framework | 39,299,005 | <p>Is there a way to scrap css values while scraping using python scrapy framework or by using php scraping.
any help will be appreaciated</p>
| -2 | 2016-09-02T18:50:46Z | 39,299,392 | <p>scrapy.Selector allows you to use xpath to extract properties of HTML elements including CSS.</p>
<p>e.g. <a href="https://github.com/okfde/odm-datenerfassung/blob/master/crawl/dirbot/spiders/data.py#L83" rel="nofollow">https://github.com/okfde/odm-datenerfassung/blob/master/crawl/dirbot/spiders/data.py#L83</a></p>... | 0 | 2016-09-02T19:18:22Z | [
"python",
"scrapy"
] |
scraping css values using scrapy framework | 39,299,005 | <p>Is there a way to scrap css values while scraping using python scrapy framework or by using php scraping.
any help will be appreaciated</p>
| -2 | 2016-09-02T18:50:46Z | 39,299,996 | <p>Yes, please check the documentation for <a href="http://doc.scrapy.org/en/latest/topics/selectors.html" rel="nofollow">selectors</a> basically you've two methods <code>response.xpath()</code> for <a href="https://www.w3.org/TR/xpath" rel="nofollow">xpath</a> and <code>response.css()</code> for <a href="https://www.w... | 0 | 2016-09-02T20:06:55Z | [
"python",
"scrapy"
] |
SQLite multiple conditions in WHERE LIKE | 39,299,072 | <p>Is there anyway to have multiple conditions in a WHERE x LIKE %x% statement without using OR?</p>
<p>Basically I want to be able to select something where column1 LIKE %something% AND column2 LIKE %check1% OR %check2% OR %check3%</p>
<p>However, using OR removes my first previous check for column1 but I need this ... | 1 | 2016-09-02T18:55:31Z | 39,299,123 | <p>What about:</p>
<pre><code>SELECT id FROM test WHERE
column1 LIKE '%bob%' AND
(column2 LIKE '%something%' OR
column2 LIKE '%somethingdifferent%' OR
column2 LIKE '%somethingdifferent2%')
</code></pre>
<p>It's logically equivalent...</p>
<p>You can also use a RegEx: see <a href="http://stackoverflow.... | 3 | 2016-09-02T18:59:42Z | [
"python",
"database",
"sqlite"
] |
Iterate and assign value - Python - Numpy | 39,299,187 | <p>I´m a newbie in Python.</p>
<p>I´m trying to do something like this. Iterate an array, compare the value with a constant and assign values to another array.</p>
<p><img src="http://i.stack.imgur.com/r0Sqk.jpg" alt="What I´m trying to do"></p>
<p>Thanks in advance!</p>
<p>Regards</p>
<p>Eduardo</p>
| 0 | 2016-09-02T19:03:52Z | 39,299,213 | <pre><code>a1 = numpy.array(range(10))
a2 = numpy.array(range(15,25))
print a2[a1==5]
print a2[a1 >= 8]
print a2[a1 < 5]
</code></pre>
<p>etc...</p>
| 0 | 2016-09-02T19:05:47Z | [
"python",
"arrays",
"loops",
"numpy"
] |
Iterate and assign value - Python - Numpy | 39,299,187 | <p>I´m a newbie in Python.</p>
<p>I´m trying to do something like this. Iterate an array, compare the value with a constant and assign values to another array.</p>
<p><img src="http://i.stack.imgur.com/r0Sqk.jpg" alt="What I´m trying to do"></p>
<p>Thanks in advance!</p>
<p>Regards</p>
<p>Eduardo</p>
| 0 | 2016-09-02T19:03:52Z | 39,299,308 | <pre><code>// A is the original list
// constant - f(y)
newList = list()
for i in A:
if i < constant: newList.append(i)
else: newList.append(constant)
</code></pre>
| -1 | 2016-09-02T19:13:02Z | [
"python",
"arrays",
"loops",
"numpy"
] |
Iterate and assign value - Python - Numpy | 39,299,187 | <p>I´m a newbie in Python.</p>
<p>I´m trying to do something like this. Iterate an array, compare the value with a constant and assign values to another array.</p>
<p><img src="http://i.stack.imgur.com/r0Sqk.jpg" alt="What I´m trying to do"></p>
<p>Thanks in advance!</p>
<p>Regards</p>
<p>Eduardo</p>
| 0 | 2016-09-02T19:03:52Z | 39,299,545 | <p>The question needs to be more specific BTW look how the element of a numpy <code>array</code> are accessed and modified:</p>
<pre><code>>>> # generating a random numpy array
... np_array = numpy.random.randint(0,100,10)
>>> np_array
45: array([22, 71, 40, 83, 33, 52, 29, 31, 77, 87])
>>> ... | 0 | 2016-09-02T19:31:30Z | [
"python",
"arrays",
"loops",
"numpy"
] |
django:adding more than one value in model field | 39,299,190 | <p>i want to create a app for classroom in which their only one teacher and students can be more than one.a nd student can be in more than one class. i want to store usernames of students in one classroom. is there any model field i can use to store usernames of students.
my code so far:</p>
<p>models.py </p>
<pre><c... | 0 | 2016-09-02T19:04:05Z | 39,299,242 | <p>Create a Student model and add a many to many key to a ClassRoom instance. In that way you are telling "<strong>A student may have several classroom and a classroom may have many students</strong>"</p>
<pre><code>class ClassRoom(models.Model):
teacher = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
... | 1 | 2016-09-02T19:08:11Z | [
"python",
"django",
"django-models",
"django-forms",
"django-views"
] |
django:adding more than one value in model field | 39,299,190 | <p>i want to create a app for classroom in which their only one teacher and students can be more than one.a nd student can be in more than one class. i want to store usernames of students in one classroom. is there any model field i can use to store usernames of students.
my code so far:</p>
<p>models.py </p>
<pre><c... | 0 | 2016-09-02T19:04:05Z | 39,299,267 | <p>You should create a separate model for storing students, but even more than that - you should really start with the Django tutorial on their official site. </p>
<p>But your problem is solved accordingly: </p>
<pre><code>from django.db import models
from django.conf import settings
class ClassRoom(models.Model):... | 1 | 2016-09-02T19:09:52Z | [
"python",
"django",
"django-models",
"django-forms",
"django-views"
] |
How to configure a package in PyPI to install only with pip3 | 39,299,320 | <p>I distributed my package written in Python 3 on PyPI. It can be installed by both <code>pip2</code> and <code>pip3</code>. How can I configure the package to only be available in Python 3; i.e. to install only with <code>pip3</code>?</p>
<p>I've already added these classifiers in <code>setup.py</code> file:</p>
<p... | 1 | 2016-09-02T19:13:47Z | 39,299,963 | <p>I'm not sure if such an option exists. What you could do though is manually enforce it by checking that the version of python in which it is installed is larger than the version you want to dictate:</p>
<pre><code>from sys import version_info
class NotSupportedException(BaseException): pass
if version_info.major ... | 2 | 2016-09-02T20:04:09Z | [
"python",
"python-3.x",
"pypi"
] |
Is there a reliable way to get the path of the caller module from a Python function that is executed within a Sphinx conf.py? | 39,299,411 | <p>I'm running some custom Python code in Sphinx and <strong>need to get the path to the caller module</strong>. (Essentially this is the caller's <code>__file__</code> object; I need to interpret a filename relative to this location.)</p>
<p>I can get the filename from <code>inspect.stack()</code> as per <a href="ht... | -1 | 2016-09-02T19:19:46Z | 39,299,596 | <p>you can get what you want using the <code>traceback</code> module. I've written this sample code in PyScripter:</p>
<pre><code>import traceback,sys
def demo():
for file,line,w1,w2 in traceback.extract_stack():
sys.stdout.write(' File "{}", line {}, in {}\n'.format(file,line,w1))
def foo():
demo()
... | 3 | 2016-09-02T19:35:52Z | [
"python",
"python-sphinx"
] |
Is there a reliable way to get the path of the caller module from a Python function that is executed within a Sphinx conf.py? | 39,299,411 | <p>I'm running some custom Python code in Sphinx and <strong>need to get the path to the caller module</strong>. (Essentially this is the caller's <code>__file__</code> object; I need to interpret a filename relative to this location.)</p>
<p>I can get the filename from <code>inspect.stack()</code> as per <a href="ht... | -1 | 2016-09-02T19:19:46Z | 39,299,892 | <p>Bah, I'm just going to get around the issue by allowing callers to pass in their <code>__file__</code> value :-(</p>
<p>my function:</p>
<pre><code>def do_something(app, filename, relroot=None):
if relroot is None:
relroot = '.'
else:
relroot = os.path.dirname(relroot)
path = os.path.join(rel... | 0 | 2016-09-02T19:58:33Z | [
"python",
"python-sphinx"
] |
coloring cells in excel with pandas | 39,299,509 | <p>I need some help here. So i have something like this </p>
<pre><code>import pandas as pd
path = '/Users/arronteb/Desktop/excel/ejemplo.xlsx'
xlsx = pd.ExcelFile(path)
df = pd.read_excel(xlsx,'Sheet1')
df['is_duplicated'] = df.duplicated('#CSR')
df_nodup = df.loc[df['is_duplicated'] == False]
df_nodup.to_excel('ejem... | 1 | 2016-09-02T19:28:08Z | 39,299,584 | <p>You can create a function to do the highlighting...</p>
<pre><code>def highlight_cells():
# provide your criteria for highlighting the cells here
return ['background-color: yellow']
</code></pre>
<p>And then apply your highlighting function to your dataframe...</p>
<pre><code>df.style.apply(highlight_cell... | 2 | 2016-09-02T19:34:35Z | [
"python",
"excel",
"pandas",
"duplicates",
"highlight"
] |
coloring cells in excel with pandas | 39,299,509 | <p>I need some help here. So i have something like this </p>
<pre><code>import pandas as pd
path = '/Users/arronteb/Desktop/excel/ejemplo.xlsx'
xlsx = pd.ExcelFile(path)
df = pd.read_excel(xlsx,'Sheet1')
df['is_duplicated'] = df.duplicated('#CSR')
df_nodup = df.loc[df['is_duplicated'] == False]
df_nodup.to_excel('ejem... | 1 | 2016-09-02T19:28:08Z | 39,299,648 | <p>I just had this same problem and I just solved it this week. My problem was not getting the includes to work properly to get the online code that I found working properly.</p>
<p>I am going to assume you mean change the background color not change the font color. If I am wrong clarify your request.</p>
<p>My sol... | 1 | 2016-09-02T19:39:55Z | [
"python",
"excel",
"pandas",
"duplicates",
"highlight"
] |
Can't access a file in another directory using python object | 39,299,593 | <p>I wanted to implement a classification application using python 2 and before classification done text should be preprocessed. Classifier and Preprocessor are in different packages. Then I created a object of <code>preprocessing class</code> in class in classification package.</p>
<p>here is my project explorer</p>
... | 0 | 2016-09-02T19:35:40Z | 39,299,816 | <p>Please check that the file is in the same path as path of the current executed file.
Here is idea:
<a href="http://stackoverflow.com/questions/2632199/how-do-i-get-the-path-of-the-current-executed-file-in-python">How do I get the path of the current executed file in python?</a></p>
| 0 | 2016-09-02T19:52:58Z | [
"python",
"utf-8"
] |
Trying to output the x most common words in a text file | 39,299,600 | <p>I'm trying to write a program that will read in a text file and output a list of most common words (30 as the code is written now) along with their counts. so something like:</p>
<pre><code>word1 count1
word2 count2
word3 count3
... ...
... ...
wordn countn
</code></pre>
<p>in order of count1 > count2 > count3... | 0 | 2016-09-02T19:36:39Z | 39,299,630 | <p>Use the <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a> class.</p>
<pre><code>from collections import Counter
for word, count in Counter(words).most_common(30):
print(word, count)
</code></pre>
<p>Some unsolicited advice: Don... | 2 | 2016-09-02T19:38:42Z | [
"python",
"sorting",
"dictionary",
"tuples",
"sorted"
] |
Trying to output the x most common words in a text file | 39,299,600 | <p>I'm trying to write a program that will read in a text file and output a list of most common words (30 as the code is written now) along with their counts. so something like:</p>
<pre><code>word1 count1
word2 count2
word3 count3
... ...
... ...
wordn countn
</code></pre>
<p>in order of count1 > count2 > count3... | 0 | 2016-09-02T19:36:39Z | 39,299,860 | <p>First method as others have suggested i.e. by using <code>most_common(...)</code> doesn't work according to your needs cause it returns the <em>nth first most common words</em> and not the words whose count is less than or equal to <code>n</code>:</p>
<p>Here's using <code>most_common(...)</code>: note it just prin... | 0 | 2016-09-02T19:56:31Z | [
"python",
"sorting",
"dictionary",
"tuples",
"sorted"
] |
Trying to output the x most common words in a text file | 39,299,600 | <p>I'm trying to write a program that will read in a text file and output a list of most common words (30 as the code is written now) along with their counts. so something like:</p>
<pre><code>word1 count1
word2 count2
word3 count3
... ...
... ...
wordn countn
</code></pre>
<p>in order of count1 > count2 > count3... | 0 | 2016-09-02T19:36:39Z | 39,300,055 | <p>Using <code>itertools</code>' <code>groupby</code>:</p>
<pre class="lang-py prettyprint-override"><code>from itertools import groupby
words = sorted([w.lower() for w in open("/path/to/file").read().split()])
count = [[item[0], len(list(item[1]))] for item in groupby(words)]
count.sort(key=lambda x: x[1], reverse =... | 1 | 2016-09-02T20:11:03Z | [
"python",
"sorting",
"dictionary",
"tuples",
"sorted"
] |
How to scrape data from multiple wikipedia pages with python? | 39,299,658 | <p>I want grab the age, place of birth and previous occupation of senators.
Information for each individual senator is available on Wikipedia, on their respective pages, and there is another page with a table that lists all senators by the name.
How can I go through that list, follow links to the respective pages of ea... | 3 | 2016-09-02T19:40:27Z | 39,320,281 | <p>Ok, so I figured it out (thanks to a comment pointing me to BeautifulSoup).</p>
<p>There is actually no big secret to achieve what I wanted. I just had to go through the list with BeautifulSoup and store all the links, and then open each stored link with <code>urllib2</code>, call BeautifulSoup on the response, and... | 0 | 2016-09-04T18:39:43Z | [
"python",
"wikipedia"
] |
How to check if character exists in DataFrame cell | 39,299,703 | <p>After creating the three-rows DataFrame:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'a': ['1-2', '3-4', '5-6']})
</code></pre>
<p>I check if there is any cell equal to '3-4':</p>
<pre><code>df['a']=='3-4'
</code></pre>
<p><a href="http://i.stack.imgur.com/7UYJY.png" rel="nofollow"><img src="http://i.s... | 3 | 2016-09-02T19:44:11Z | 39,299,761 | <p>Use <code>str</code> and <code>contains</code>:</p>
<pre><code>In [5]: df['a'].str.contains('-')
Out[5]:
0 True
1 True
2 True
Name: a, dtype: bool
</code></pre>
| 4 | 2016-09-02T19:48:55Z | [
"python",
"pandas",
"dataframe"
] |
Python: Update serialized object | 39,299,705 | <p>I am trying to perform a simple task:<br>
1. De-serialize a previously serialized object<br>
2. Updating this object<br>
3. Serializing it back for later use </p>
<p>I tried to do it with <code>pickle</code> with no luck.<br>
I start by doing this: </p>
<pre><code>empty_list = []
f = open('backup.p', 'wb')
pickl... | 0 | 2016-09-02T19:44:17Z | 39,299,824 | <p>After this:</p>
<pre><code>f = open('backup.p', 'rb+')
l = pickle.load(f)
</code></pre>
<p>you've positioned the file object <code>f</code> at a point in the file after the pickle of <code>empty_list</code>. That means when you dump another object to the file:</p>
<pre><code>pickle.dump(l, f)
</code></pre>
<p>t... | 3 | 2016-09-02T19:53:37Z | [
"python",
"serialization",
"deserialization",
"pickle"
] |
Count most frequent word in row by R | 39,299,811 | <p>There is a table shown below </p>
<pre><code> Name Mon Tue Wed Thu Fri Sat Sun
1 John Apple Orange Apple Banana Apple Apple Orange
2 Ricky Banana Apple Banana Banana Banana Banana Apple
3 Alex Apple Orange Orange Apple Apple Orange Orange
4 Robbin Apple Apple ... | 1 | 2016-09-02T19:52:39Z | 39,303,113 | <p>If we need the "Count" and "Names" corresponding to the <code>max</code> "Count", we loop through the rows of the dataset (using <code>apply</code> with <code>MARGIN = 1</code>), use <code>table</code> to get the frequency, extract the maximum value from it and the <code>names</code> corresponding to the maximum val... | 3 | 2016-09-03T04:03:54Z | [
"python",
"pyspark",
"rpy2",
"word-frequency"
] |
Count most frequent word in row by R | 39,299,811 | <p>There is a table shown below </p>
<pre><code> Name Mon Tue Wed Thu Fri Sat Sun
1 John Apple Orange Apple Banana Apple Apple Orange
2 Ricky Banana Apple Banana Banana Banana Banana Apple
3 Alex Apple Orange Orange Apple Apple Orange Orange
4 Robbin Apple Apple ... | 1 | 2016-09-02T19:52:39Z | 39,304,465 | <p>Another approach would be to loop over all unique fruits as follows</p>
<pre><code>fruits_unique <- unique(unlist(dat[-1]))
occurence <- sapply(fruits_unique, function(x) rowSums(dat[,-1] == x))
# Using this data to create the resulting columns
ind <- apply(occurence,1,which.max)
dat$Names <- fruits_un... | 2 | 2016-09-03T07:35:43Z | [
"python",
"pyspark",
"rpy2",
"word-frequency"
] |
Scapy not picking up a single ARP request | 39,299,825 | <p>I have the following running (finally after installing libnet etc) on my Mac trying to listen for a Dash button's MAC address:</p>
<pre><code>from scapy.all import *
def arp_display(pkt):
if pkt[ARP].op == 1: #who-has (request)
if pkt[ARP].psrc == '0.0.0.0': # ARP Probe
print ("ARP Probe from: " + pkt[... | 0 | 2016-09-02T19:53:37Z | 39,787,889 | <p>The new buttons don't put out the same ARP request as the old ones. Remove this line and it should work.</p>
<pre><code>if pkt[ARP].psrc == '0.0.0.0': # ARP Probe
</code></pre>
| 0 | 2016-09-30T09:14:07Z | [
"python",
"networking",
"iot",
"scapy",
"hacking"
] |
How do I import module in jupyter notebook directory into notebooks in lower directories? | 39,299,838 | <p>I have used jupyter notebook for data analysis for quite sometime. I would like to develop a module in my jupyter notebook directory and be able to import that new module into notebooks. My jupyter notebook file directory can be represented as follows;</p>
<pre><code>Jupyter notebooks\
notebook1.ipynb
new... | 1 | 2016-09-02T19:54:43Z | 39,311,677 | <p>You need to make sure that the parent directory of <code>new_module</code> is on your python path. For a notebook that is one level below <code>new_module</code>, this code will do the trick:</p>
<pre><code>import os
import sys
nb_dir = os.path.split(os.getcwd())[0]
if nb_dir not in sys.path:
sys.path.append(n... | 2 | 2016-09-03T21:55:59Z | [
"python",
"python-3.x",
"ipython",
"python-import",
"jupyter-notebook"
] |
django equivalent to sqlalchemy's sessionmaker | 39,299,852 | <p>I'm new to Django 1.9 (fairly new to flask, as well), and am trying to populate my models.py much in the same way that sqlite sessionmaker does it. </p>
<p>this is a snip of my models.py:</p>
<pre><code>@python_2_unicode_compatible
class Location(models.Model):
def __str__(self):
return self.location_text
loc... | 1 | 2016-09-02T19:55:52Z | 39,300,619 | <p>If i get you right, you want to save objects in one query.</p>
<p>This could be done with <a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/#django.db.models.query.QuerySet.bulk_create" rel="nofollow"><code>bulk_create</code></a></p>
<blockquote>
<p>This method inserts the provided list of obje... | 0 | 2016-09-02T20:58:20Z | [
"python",
"django",
"sqlalchemy"
] |
django equivalent to sqlalchemy's sessionmaker | 39,299,852 | <p>I'm new to Django 1.9 (fairly new to flask, as well), and am trying to populate my models.py much in the same way that sqlite sessionmaker does it. </p>
<p>this is a snip of my models.py:</p>
<pre><code>@python_2_unicode_compatible
class Location(models.Model):
def __str__(self):
return self.location_text
loc... | 1 | 2016-09-02T19:55:52Z | 39,302,902 | <pre><code>loc1 = Location.objects.create(location_text="Indonesia")
cap = Countries.objects.create(capitals="Jakarta", location=loc1)
</code></pre>
<p>That's all.</p>
| 0 | 2016-09-03T03:16:02Z | [
"python",
"django",
"sqlalchemy"
] |
wxPython - if condition = False then skip some lines or exit without closing Main Frame | 39,299,853 | <p>in my <code>wxApp</code> that is currently under development, I have bind a button to call a new frame. However I want to put condition in my def that is actually calling the new frame and if that fails the def method should simple exit but not close the main Frame. So basically something like <code>Exit Sub</code> ... | 0 | 2016-09-02T19:55:53Z | 39,302,701 | <p>Replace</p>
<pre><code>exit()
</code></pre>
<p>with</p>
<pre><code>return
</code></pre>
<p><a href="http://stackoverflow.com/questions/18863309/the-equivalent-of-a-goto-in-python">The equivalent of a GOTO in python</a></p>
| 1 | 2016-09-03T02:27:06Z | [
"python",
"if-statement",
"wxpython",
"goto"
] |
Finding particular column value via regex | 39,299,879 | <p>I have a txt file containing multiple rows as below. </p>
<pre><code>56.0000 3 1
62.0000 3 1
74.0000 3 1
78.0000 3 1
82.0000 3 1
86.0000 3 1
90.0000 3 1
94.0000 3 1
98.0000 3 1
102.0000 ... | 0 | 2016-09-02T19:57:58Z | 39,299,939 | <p>You probably don't need a regex for this. You can <em>strip</em> trailing whitespaces from the right side of the line and then check the last character:</p>
<pre><code>if line.rstrip()[-1] == "0": # since your last column only contains 0 or 1
...
</code></pre>
| 2 | 2016-09-02T20:02:29Z | [
"python",
"regex"
] |
Finding particular column value via regex | 39,299,879 | <p>I have a txt file containing multiple rows as below. </p>
<pre><code>56.0000 3 1
62.0000 3 1
74.0000 3 1
78.0000 3 1
82.0000 3 1
86.0000 3 1
90.0000 3 1
94.0000 3 1
98.0000 3 1
102.0000 ... | 0 | 2016-09-02T19:57:58Z | 39,300,024 | <p>Just split line and read value from list.</p>
<pre><code>>>> line = "56.0000 3 1"
>>> a=line.split()
>>> a
['56.0000', '3', '1']
>>> print a[2]
1
>>>
</code></pre>
<p><strong>Summary:</strong></p>
<pre><code>f = open("sample.txt",'r')
for line in f:
t... | 1 | 2016-09-02T20:08:49Z | [
"python",
"regex"
] |
Converting from Excel to HDF5 using Pandas | 39,299,911 | <p>I want to extract the content of an Excel document into a pandas dataframe and then write that dataframe into an HDF5 file. To do so, I've done this:</p>
<pre><code>xls_df = pd.read_excel(fn_xls)
xls_df.to_hdf(fn_h5, 'table', format='table', mode='w')
</code></pre>
<p>This results in the following error: </p>... | 0 | 2016-09-02T19:59:51Z | 39,314,740 | <p>The mixed string and integer data types in column "Col4" are cause an error when converting to HDF5 in "table" format.</p>
<p>To save in hdf5 "tables" format you need to convert the numbers in Col4 to floats (and strings to NaN):</p>
<p><code>df["Col4"] = pd.to_numeric(df["Col4"], errors="coerce")</code></p>
<p>O... | 0 | 2016-09-04T07:54:26Z | [
"python",
"excel",
"pandas",
"dataframe",
"hdf5"
] |
Checking if the value of a string is true - python | 39,299,917 | <p>I am trying to see if a string is true or false but im stuck... In the following code I have made a list of statements that I want to evaluate, I have put them in strings because the variables need to be declared after the list is .(Reason is that the list of statements to be evaluated are being passed as a paramete... | -2 | 2016-09-02T20:00:24Z | 39,299,958 | <p><code>exec</code> is a function in python3.x<sup>1</sup> that returns <code>None</code> so you'll always have a falsy result. You probably want <code>eval</code>.</p>
<p>Also be careful here. Do not use this unless you completely trust the input strings as it will allow execution of arbitrary code otherwise.</p>
... | 4 | 2016-09-02T20:03:48Z | [
"python",
"string",
"list",
"loops",
"if-statement"
] |
Accessing columns with MultiIndex after using pandas groupby | 39,300,049 | <p>I am using the df.groupby() method: </p>
<pre><code>g1 = df[['md', 'agd', 'hgd']].groupby(['md']).agg(['mean', 'count', 'std'])
</code></pre>
<p>It produces exactly what I want!</p>
<pre><code> agd hgd
mean count std mean count std
md ... | 3 | 2016-09-02T20:10:10Z | 39,300,083 | <p>1) You can rename the columns and proceed as normal (will get rid of the multi-indexing)</p>
<pre><code>g1.columns = ['agd_mean', 'agd_std','hgd_mean','hgd_std']
</code></pre>
<p>2) You can keep multi-indexing and use both levels in turn (<a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html#basic-ind... | 1 | 2016-09-02T20:13:27Z | [
"python",
"pandas",
"group-by"
] |
Accessing columns with MultiIndex after using pandas groupby | 39,300,049 | <p>I am using the df.groupby() method: </p>
<pre><code>g1 = df[['md', 'agd', 'hgd']].groupby(['md']).agg(['mean', 'count', 'std'])
</code></pre>
<p>It produces exactly what I want!</p>
<pre><code> agd hgd
mean count std mean count std
md ... | 3 | 2016-09-02T20:10:10Z | 39,301,351 | <p>It is possible to do what you are searching for and it is called <code>transform</code>. You will find an example that does exactly what you are searching for in the pandas documentation <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#transformation" rel="nofollow">here</a>.</p>
| 0 | 2016-09-02T22:15:48Z | [
"python",
"pandas",
"group-by"
] |
paho MQTT on_message returning a funny message - python | 39,300,102 | <p>some help please :)
I just started to play with MQTT in python.
When I run the following program:</p>
<pre><code>import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("watchdog/#")
def on_message(client, userdata, msg):
... | 1 | 2016-09-02T20:15:09Z | 39,355,723 | <p>As Moses Koledoye says, b is for bytes - this means that what you are printing is the string version of a set of bytes. If you changed the str(msg.payload) to simply msg.payload, you will get a different output.</p>
<p>But you haven't talked about what the message payload is, so you may still get gibberish out pri... | 1 | 2016-09-06T18:36:39Z | [
"python",
"mqtt"
] |
ImportError: No module named qgis.core ubuntu 16.04 python 2.7 qgis 2.16.2 | 39,300,116 | <p>I keep getting this error in python from trying to call qgis from a script.</p>
<p>The code is:</p>
<pre><code>from qgis.core import *
from qgis.analysis import *
</code></pre>
<p>I have read every posting on SO about this; wiped QGIS and reinstalled. Reset my PYTHON_PATH and QGIS_PREFIX variables to the correc... | 0 | 2016-09-02T20:16:17Z | 39,330,862 | <p>I had the same problem but it was with Windows 7. Following the last point called Running Custom Applications in <a href="http://docs.qgis.org/2.8/en/docs/pyqgis_developer_cookbook/intro.html" rel="nofollow">http://docs.qgis.org/2.8/en/docs/pyqgis_developer_cookbook/intro.html</a> I solved it. </p>
<p>You will need... | 0 | 2016-09-05T12:41:31Z | [
"python",
"ubuntu",
"qgis"
] |
ImportError: No module named qgis.core ubuntu 16.04 python 2.7 qgis 2.16.2 | 39,300,116 | <p>I keep getting this error in python from trying to call qgis from a script.</p>
<p>The code is:</p>
<pre><code>from qgis.core import *
from qgis.analysis import *
</code></pre>
<p>I have read every posting on SO about this; wiped QGIS and reinstalled. Reset my PYTHON_PATH and QGIS_PREFIX variables to the correc... | 0 | 2016-09-02T20:16:17Z | 39,341,243 | <p>Finally got it working. Had to completely wipe and reinstall QGIS twice and separately remove python-qgis. Also had to uninstall anaconda. After the second fresh install of QGIS I've gotten it working.</p>
<p>No other changes to my configuration.</p>
| 0 | 2016-09-06T05:30:15Z | [
"python",
"ubuntu",
"qgis"
] |
Visual Studio Code - python console | 39,300,131 | <p>I'm using visual studio code with standard python extension, my issue is that when I run the code the python interpreter instantly closes right after and I only see the output which means that if I create some data structure I have to create it every single time. Is it possible to leave the console open after runnin... | -1 | 2016-09-02T20:17:48Z | 39,311,974 | <p>When you run a program, it runs until it ends. Then it closes. If you want it to stay live longer, you can make a program which does not stop until told so, e.g.</p>
<pre><code>while True:
something = raw_input('Write something: ')
print('You wrote: %s' % something)
if something == 'bye':
print ... | 1 | 2016-09-03T22:48:54Z | [
"python",
"vscode"
] |
Pandas - Concat strings after groupby in column, ignore NaN, ignore duplicates | 39,300,163 | <p>Depending on the query, my DF can have a column with strings or a column with NaN.</p>
<p>Ex:</p>
<pre><code> ID grams Projects
0 891 4.0 NaN
1 725 9.0 NaN
</code></pre>
<p>or</p>
<pre><code> ID grams Projects
0 890 1.0 P1, P2
1 724 1.0... | 2 | 2016-09-02T20:19:44Z | 39,300,358 | <p>I think this should help: </p>
<pre><code>import numpy
df_new = df.replace(numpy.nan,' ', regex=True)
</code></pre>
<p>EDIT:</p>
<p>I think this <a href="http://stackoverflow.com/questions/25401295/using-python-to-remove-duplicated-contents-in-cells-in-excel">solution</a> could work for you (just as an alterna... | 1 | 2016-09-02T20:36:34Z | [
"python",
"python-3.x",
"pandas",
null,
"missing-data"
] |
Pandas - Concat strings after groupby in column, ignore NaN, ignore duplicates | 39,300,163 | <p>Depending on the query, my DF can have a column with strings or a column with NaN.</p>
<p>Ex:</p>
<pre><code> ID grams Projects
0 891 4.0 NaN
1 725 9.0 NaN
</code></pre>
<p>or</p>
<pre><code> ID grams Projects
0 890 1.0 P1, P2
1 724 1.0... | 2 | 2016-09-02T20:19:44Z | 39,300,572 | <p>Say you start with</p>
<pre><code>In [37]: df = pd.DataFrame({'a': [1, 1, 2, 2], 'b': [1, None, 2, 4], 'c': ['foo', 'sho', 'sha', 'bar']})
In [43]: df
Out[43]:
a b c
0 1 1.0 foo
1 1 NaN foo
2 2 2.0 sha
3 2 4.0 bar
</code></pre>
<p>Then you can apply the same function to either <code>b</code>... | 2 | 2016-09-02T20:53:56Z | [
"python",
"python-3.x",
"pandas",
null,
"missing-data"
] |
Extracting IP addresses from a file | 39,300,166 | <p>I'm trying to extract IP addresses from an <code>asp</code> file in Python, the file looks something like this:</p>
<pre><code>onInternalNet = (
isInNet(hostDNS, "147.163.1.0", "255.255.0.0") ||
isInNet(hostDNS, "123.264.0.0", "255.255.0.0") ||
isInNet(hostDNS, "137.5.0.0", "255.0.0.0") ||
... | 0 | 2016-09-02T20:20:11Z | 39,300,245 | <p><code>re.compile</code> was expecting an appropriate <code>flags</code> parameter (an integer) of which <code>line</code> (a string) is not. </p>
<p>You should be doing <code>re.match</code> not <code>re.compile</code>:</p>
<blockquote>
<p><a href="https://docs.python.org/2/library/re.html#re.compile" rel="nofol... | 2 | 2016-09-02T20:27:26Z | [
"python",
"python-2.7",
"extract",
"ipv4"
] |
Extracting IP addresses from a file | 39,300,166 | <p>I'm trying to extract IP addresses from an <code>asp</code> file in Python, the file looks something like this:</p>
<pre><code>onInternalNet = (
isInNet(hostDNS, "147.163.1.0", "255.255.0.0") ||
isInNet(hostDNS, "123.264.0.0", "255.255.0.0") ||
isInNet(hostDNS, "137.5.0.0", "255.0.0.0") ||
... | 0 | 2016-09-02T20:20:11Z | 39,300,328 | <p>Your initial error </p>
<pre><code>TypeError: unsupported operand type(s) for &: 'str' and 'int'
</code></pre>
<p>is caused by exactly what @Moses said in his answer. flags are supposed to be int values, not strings.</p>
<hr>
<p>You should compile your regex once. Also, you need to use an open file handle ... | 1 | 2016-09-02T20:34:07Z | [
"python",
"python-2.7",
"extract",
"ipv4"
] |
Extracting IP addresses from a file | 39,300,166 | <p>I'm trying to extract IP addresses from an <code>asp</code> file in Python, the file looks something like this:</p>
<pre><code>onInternalNet = (
isInNet(hostDNS, "147.163.1.0", "255.255.0.0") ||
isInNet(hostDNS, "123.264.0.0", "255.255.0.0") ||
isInNet(hostDNS, "137.5.0.0", "255.0.0.0") ||
... | 0 | 2016-09-02T20:20:11Z | 39,300,353 | <p>Please check the below code:</p>
<p>Did couple of changes</p>
<ol>
<li>re.compile - Regex should be complied first and then can be used with 'match/search/findall'.</li>
<li>Regex was not proper. While writing regex we need to consider from the start of line. Regex didn't match words in between line directly.</li>... | 1 | 2016-09-02T20:36:06Z | [
"python",
"python-2.7",
"extract",
"ipv4"
] |
python dataframe convert column to row | 39,300,265 | <p>Attempting to convert a single dataframe column into a row. I've seen multiple responses to similar questions, but most of the questions pertain to multiple columns and rows. I can't find the simple solution to converting the following:</p>
<pre><code>value
</code></pre>
<p>0 A<br>
1 B<br>
2 C<br>
3 D<br... | 0 | 2016-09-02T20:28:53Z | 39,300,527 | <p>To transpose the <code>value</code> dataframe</p>
<p><code>value1 = value.transpose()</code></p>
| 0 | 2016-09-02T20:49:54Z | [
"python",
"dataframe"
] |
How many session objects are needed for synchronous in-graph replication? | 39,300,401 | <p>When using synchronous in-graph replication I only call <code>tf.Session.run()</code> once.</p>
<p><strong>Question 1:</strong> Do I still have to create a new session object for each worker and have to pass the URL of the master server (the one that calls <code>tf.Session.run()</code>) as the session target?</p>
... | 0 | 2016-09-02T20:39:44Z | 39,300,842 | <p>If you are using "in-graph replication", the graph contains multiple copies of the computational nodes, typically with one copy per device (i.e. one per worker task if you're doing distributed CPU training, or one per GPU if you're doing distributed or local multi-GPU training). Since all of the replicas are in the ... | 2 | 2016-09-02T21:18:34Z | [
"python",
"tensorflow"
] |
Saving tweets to different files using Python | 39,300,456 | <p>I am relatively new to python and trying to download tweets and save them to different text files. I want the file name to be dynamic and hence tried to modify code according to my requirement. Below, is the code that I am trying to modify:-</p>
<pre><code>class StdOutListener(StreamListener):
def on_data(self, dat... | 0 | 2016-09-02T20:44:24Z | 39,300,616 | <p>A loop to increment i each time a file exist does not exist: your mechanism only works with file of index 1, it creates a file of index 2, then stops there.</p>
<p>Fix: I have added a loop which breaks as soon as a "free" filename is found. Check better way to get file size and code is much much more compact. Teste... | 0 | 2016-09-02T20:58:12Z | [
"python",
"python-2.7",
"twitter",
"tweepy"
] |
How to generate mazes with fixed entry and exit points? | 39,300,491 | <p>I have read about the Depth-First search algorithm to create and solve mazes. However, I have not found anything on creating mazes with fixed entry and exit. On each maze the entry would always be at (0, 1) and the exit at the opposite side on both axis.</p>
<p>During the generation of the maze, every cell should b... | 0 | 2016-09-02T20:47:11Z | 39,300,710 | <p>I've made grid-based mazes before using a breadth-first search, but a similar algorithm can be devised from a depth first one. </p>
<p>First I'd create a <a href="https://en.wikipedia.org/wiki/Graph_theory" rel="nofollow">graph</a>, where each node in your coordinate graph above links to the node up, down, left, a... | 1 | 2016-09-02T21:07:54Z | [
"python",
"depth-first-search",
"maze"
] |
Python Webdriver not loading page on Windows | 39,300,553 | <p>I am using Python 3.5 on a Windows computer. When I run this code on my Mac it works perfect, no issues what so ever. But when I bring the code to my Windows computer it doesn't work.</p>
<p>Basically the web browser will open but I will just get a blank page. Nothing will load, not even the home page. I don't ... | 1 | 2016-09-02T20:52:08Z | 39,301,141 | <p>It looks like your client doesn't have the fix for the new switch to launch the gecko driver:</p>
<p><a href="https://github.com/SeleniumHQ/selenium/commit/c76917839c868603c9ab494d8aa0e9d600515371" rel="nofollow">https://github.com/SeleniumHQ/selenium/commit/c76917839c868603c9ab494d8aa0e9d600515371</a></p>
<p>Make... | 1 | 2016-09-02T21:48:44Z | [
"python",
"selenium",
"firefox",
"webdriver"
] |
python need faster response with getch | 39,300,669 | <p>I'm trying to create a setup to blink a led and be able to control the frequency.
Right now I'm just printing 10s as placeholders for testing.
Everything runs and does what should, but getch is throwing me off.</p>
<pre><code>freq = 1
while freq > 0:
time.sleep(.5/freq) #half dutycycle / Hz
print("1")
... | 0 | 2016-09-02T21:02:59Z | 39,300,707 | <p>There should be only one <code>kbfunc()</code> call. Store the result in a variable.</p>
<p>E.g.: In your code if the key isn't <code>Esc</code>, you'll read the keyboard again.</p>
| 2 | 2016-09-02T21:07:48Z | [
"python",
"msvcrt",
"getch"
] |
python need faster response with getch | 39,300,669 | <p>I'm trying to create a setup to blink a led and be able to control the frequency.
Right now I'm just printing 10s as placeholders for testing.
Everything runs and does what should, but getch is throwing me off.</p>
<pre><code>freq = 1
while freq > 0:
time.sleep(.5/freq) #half dutycycle / Hz
print("1")
... | 0 | 2016-09-02T21:02:59Z | 39,301,126 | <pre><code>from msvcrt import getch,kbhit
import time
def read_kb():
return ord(getch()) if kbhit() else 0
def next_state(state):
return (state + 1)%2 # 1 -> 0, 0 -> 1
freq = 1.0 # in blinks per second
state = 0
while freq > 0:
print(state)
state = next_state(state)
key = read_kb()
... | 0 | 2016-09-02T21:47:04Z | [
"python",
"msvcrt",
"getch"
] |
for loop to extract header for a dataframe in pandas | 39,300,691 | <p>I am a newbie in python. I have a data frame that looks like this:</p>
<pre><code> A B C D E
0 1 0 1 0 1
1 0 1 0 0 1
2 0 1 1 1 0
3 1 0 0 1 0
4 1 0 0 1 1
</code></pre>
<p>How can I write a for loop to gather the column names for each row. I expect my resu... | 4 | 2016-09-02T21:05:30Z | 39,300,749 | <p>The <code>dot</code> function is done for that purpose as you want the matrix dot product between your matrix and the vector of column names:</p>
<pre><code>df.dot(df.columns)
Out[5]:
0 ACE
1 BE
2 BCD
3 AD
4 ADE
</code></pre>
<p>If your dataframe is numeric, then obtain the boolean matrix first b... | 9 | 2016-09-02T21:11:10Z | [
"python",
"pandas",
"for-loop"
] |
having Key Error while printing json data | 39,300,705 | <p><strong>python 3.5.1</strong></p>
<p>hi i have following json and python code and i want to print json data but it has an error that says:</p>
<blockquote>
<blockquote>
<p>Key Error : 'A'</p>
</blockquote>
</blockquote>
<p><strong>python</strong></p>
<pre><code>data = json.load(...)
for item in data['x']... | 0 | 2016-09-02T21:07:42Z | 39,300,800 | <p>As @elethan pointed the second item would not have key <code>'A'</code></p>
<p>You can do the following</p>
<pre><code>data = json.load(...)
for item in data['x']:
print(item.get('A'))
</code></pre>
<p>That would not get any error for your specific json input, and print <code>None</code> if it won't find <cod... | 0 | 2016-09-02T21:15:46Z | [
"python",
"json"
] |
having Key Error while printing json data | 39,300,705 | <p><strong>python 3.5.1</strong></p>
<p>hi i have following json and python code and i want to print json data but it has an error that says:</p>
<blockquote>
<blockquote>
<p>Key Error : 'A'</p>
</blockquote>
</blockquote>
<p><strong>python</strong></p>
<pre><code>data = json.load(...)
for item in data['x']... | 0 | 2016-09-02T21:07:42Z | 39,300,833 | <p>To print the values in each dictionary (with <em>unmatching</em> keys), use the <code>values</code> method of the dictionary:</p>
<pre><code>data = json.load(...)
for item in data['x']:
print(item.values())
</code></pre>
| 1 | 2016-09-02T21:17:55Z | [
"python",
"json"
] |
having Key Error while printing json data | 39,300,705 | <p><strong>python 3.5.1</strong></p>
<p>hi i have following json and python code and i want to print json data but it has an error that says:</p>
<blockquote>
<blockquote>
<p>Key Error : 'A'</p>
</blockquote>
</blockquote>
<p><strong>python</strong></p>
<pre><code>data = json.load(...)
for item in data['x']... | 0 | 2016-09-02T21:07:42Z | 39,300,928 | <p>The problem is that your code assumes that every item in <code>data['x']</code> will have a key <code>'A'</code>, but as soon as you iterate to a <code>dict</code> that does not have such a key you will get a <code>KeyError</code>.</p>
<p>Try using <code>item.get('A')</code> which will return <code>None</code> (or ... | 0 | 2016-09-02T21:27:26Z | [
"python",
"json"
] |
Numpy Int Array to HEX and then to String Conversion PYTHON | 39,300,846 | <p>I have couple of questions </p>
<p>Say I have a numpy array </p>
<pre><code>a = np.array([0,1,2,3,4,31])
a0 = a[0]
a1 = a[1]
a2 = a[2]
a3 = a[3]
a4 = a[4]
a5 = a[5]
print hex(a4), hex(a5)
</code></pre>
<p>gives me </p>
<pre><code> 0x4L 0x1F
</code></pre>
<p>same for a0, a1, a2, a3,a5. I know the L is becau... | 0 | 2016-09-02T21:19:19Z | 39,300,989 | <p>What you really want to do is to store your array in a single number by shifting each element of the array by a certain (8) amount of bits:</p>
<pre><code>>>> a = np.array([0,1,2,3,4,31])
>>> hex(sum([ai*256**i for i,ai in enumerate(a)]))
'0x1f0403020100'
</code></pre>
<p>But for this to work, yo... | 2 | 2016-09-02T21:34:01Z | [
"python",
"arrays",
"string",
"numpy"
] |
Numpy Int Array to HEX and then to String Conversion PYTHON | 39,300,846 | <p>I have couple of questions </p>
<p>Say I have a numpy array </p>
<pre><code>a = np.array([0,1,2,3,4,31])
a0 = a[0]
a1 = a[1]
a2 = a[2]
a3 = a[3]
a4 = a[4]
a5 = a[5]
print hex(a4), hex(a5)
</code></pre>
<p>gives me </p>
<pre><code> 0x4L 0x1F
</code></pre>
<p>same for a0, a1, a2, a3,a5. I know the L is becau... | 0 | 2016-09-02T21:19:19Z | 39,301,070 | <p>You can try this workaround. An element wise <code>hex</code> conversion and a later <code>join</code>. <code>'0x'</code> is added to the start of the string:</p>
<pre><code>>>> a = np.array([0,1,2,3,4,31])
>>> '0x' + ''.join('{:02X}'.format(i) for i in reversed(a))
'0x1F0403020100'
</code></pre... | 2 | 2016-09-02T21:41:38Z | [
"python",
"arrays",
"string",
"numpy"
] |
Numpy Int Array to HEX and then to String Conversion PYTHON | 39,300,846 | <p>I have couple of questions </p>
<p>Say I have a numpy array </p>
<pre><code>a = np.array([0,1,2,3,4,31])
a0 = a[0]
a1 = a[1]
a2 = a[2]
a3 = a[3]
a4 = a[4]
a5 = a[5]
print hex(a4), hex(a5)
</code></pre>
<p>gives me </p>
<pre><code> 0x4L 0x1F
</code></pre>
<p>same for a0, a1, a2, a3,a5. I know the L is becau... | 0 | 2016-09-02T21:19:19Z | 39,301,254 | <p><strong>tl;dr</strong></p>
<pre><code>("0x" + ("{:0>2x}" * len(a))).format(*tuple(a[::-1]))
</code></pre>
<p><hr>
<strong>Explanation:</strong></p>
<ul>
<li><p>Multiply string <code>"{:0>2x}"</code> a number of times equal to <code>len(a)</code>, i.e. do <code>"{:0>2x}" * len(a)</code>. This will create ... | 2 | 2016-09-02T22:03:04Z | [
"python",
"arrays",
"string",
"numpy"
] |
Python OpenCV Sliding Window Object Detection | 39,300,872 | <p>I'm implementing a sliding window in python 2.7, openCV version 3, using sklearn, skimage to apply a HOG detector to localise an object.</p>
<p>The HOG set-up works fine. If I do not apply a sliding window everything works okay.</p>
<p>The problem is the sliding window has a size of 128x128, giving a feature vecto... | 0 | 2016-09-02T21:21:08Z | 39,310,061 | <p>I think I have the answer to this:</p>
<p>Simply train images of the same dimensions as the window size. Might seem like you are losing data, but then test on a larger image. In order for this to work well said target object should fit in the window size.</p>
<p>So I'm training on 270x200, then scan a 270x200 wind... | 0 | 2016-09-03T18:20:30Z | [
"python",
"opencv",
"histogram",
"object-detection",
"sliding-window"
] |
How to find wrong prediction cases in test set (CNNs using Keras) | 39,300,880 | <p>I'm using MNIST example with 60000 training image and 10000 testing image. How do I find which of the 10000 testing image that has an incorrect classification/prediction?</p>
| 0 | 2016-09-02T21:22:13Z | 39,303,937 | <p>Simply use <code>model.predict_classes()</code> and compare the output with true labes. i.e:</p>
<pre><code>incorrects = np.nonzero(model.predict_class(X_test) != y_test)
</code></pre>
<p>to get indices of incorrect predictions</p>
| 1 | 2016-09-03T06:29:18Z | [
"python",
"machine-learning",
"theano",
"convolution",
"keras"
] |
Is there any reason for giving self a default value? | 39,300,924 | <p>I was browsing through some code, and I noticed a line that caught my attention. The code is similar to the example below</p>
<pre><code>class MyClass:
def __init__(self):
pass
def call_me(self=''):
print(self)
</code></pre>
<p>This looks like any other class that I have seen, however a <c... | 31 | 2016-09-02T21:27:11Z | 39,300,946 | <p>The short answer is yes. That way, you can call the function as: </p>
<pre><code>MyClass.call_me()
</code></pre>
<p>without instantiating <code>MyClass</code>, that will print an empty string.</p>
<p>To give a longer answer, we need to look at what is going on behind the scenes.</p>
<p>When you create an instanc... | 13 | 2016-09-02T21:29:36Z | [
"python",
"class",
"python-3.x"
] |
Is there any reason for giving self a default value? | 39,300,924 | <p>I was browsing through some code, and I noticed a line that caught my attention. The code is similar to the example below</p>
<pre><code>class MyClass:
def __init__(self):
pass
def call_me(self=''):
print(self)
</code></pre>
<p>This looks like any other class that I have seen, however a <c... | 31 | 2016-09-02T21:27:11Z | 39,300,948 | <p><em>Not really</em>, it's just an <em>odd</em> way of making it not raise an error when called via the class:</p>
<pre><code>MyClass.call_me()
</code></pre>
<p>works fine since, even though nothing is implicitly passed as with instances, the default value for that argument is provided. If no default was provided, ... | 28 | 2016-09-02T21:29:41Z | [
"python",
"class",
"python-3.x"
] |
Checking decimal point python | 39,300,980 | <p>I'm trying to create a script that counts to 3 (step size 0.1) using while, and I'm trying to make it not display .0 for numbers without decimal number (1.0 should be displayed as 1, 2.0 should be 2...)
What I tried to do is convert the float to int and then check if they equal. the problem is that it works only wit... | 1 | 2016-09-02T21:33:11Z | 39,301,036 | <p>Due to lack of precision in floating point numbers, they will not have an exact integral representation. Therefore, you want to make sure the difference is smaller than some small <code>epsilon</code>.</p>
<pre><code>epsilon = 1e-10
i = 0
while i < 3.1:
if abs(round(i) - i) < epsilon:
print round(... | 3 | 2016-09-02T21:38:13Z | [
"python"
] |
Checking decimal point python | 39,300,980 | <p>I'm trying to create a script that counts to 3 (step size 0.1) using while, and I'm trying to make it not display .0 for numbers without decimal number (1.0 should be displayed as 1, 2.0 should be 2...)
What I tried to do is convert the float to int and then check if they equal. the problem is that it works only wit... | 1 | 2016-09-02T21:33:11Z | 39,301,090 | <p>You can remove trailing zeros with '{0:g}'.format(1.00).</p>
<pre><code>i = 0
while i < 3.1:
if int(i) == i:
print int(i)
else:
print '{0:g}'.format(i)
i = i + 0.1
</code></pre>
<p>See: <a href="https://docs.python.org/3/library/string.html#format-specification-mini-language" rel="no... | 2 | 2016-09-02T21:43:39Z | [
"python"
] |
Checking decimal point python | 39,300,980 | <p>I'm trying to create a script that counts to 3 (step size 0.1) using while, and I'm trying to make it not display .0 for numbers without decimal number (1.0 should be displayed as 1, 2.0 should be 2...)
What I tried to do is convert the float to int and then check if they equal. the problem is that it works only wit... | 1 | 2016-09-02T21:33:11Z | 39,301,140 | <pre><code>i = 0
while i < 3.1:
if int(i*10) % 10 == 0:
print int(i)
else:
print i
i = i + 0.1
</code></pre>
| 1 | 2016-09-02T21:48:30Z | [
"python"
] |
PyQt QLineEdit get value from separate .py file | 39,301,017 | <p>I have the following code in one python file (sales.py) and want to display the results of the script's calculation in a QLineEdit of a separate file (control.py).</p>
<p>All line_edit.setText(def), line_edit.dispayText(def), line_edit.setText(subtotal) are not working. Any ideas of how I could go about doing this?... | -1 | 2016-09-02T21:36:26Z | 39,431,477 | <p>At the beginning I had my doubts that what I had in mind - get a script result from one py file and display it in a QLineEdit of another py file - would ever work. With the help of more experienced developers the solution turned out to be actually quite easy. </p>
<p>In fact, my inquiries are part of a personal le... | 0 | 2016-09-10T23:25:44Z | [
"python",
"pyqt4",
"qlineedit"
] |
How to perform a loop action at least once and also when a condition is true | 39,301,041 | <p>I am looking for a Python logical equivalent of a <code>do while</code> loop in other languages. I have page results I am iterating through. The results structure:</p>
<pre><code>1, 2, 3, 4 , ... NEXT
</code></pre>
<p>Each element there is a link. only the last page has no <code>NEXT</code> element so I have iden... | 1 | 2016-09-02T21:38:45Z | 39,301,085 | <p>Check for the next link <strong>after</strong> calling your function. Then use <code>break</code> to break out of the loop instead of using <code>next_link</code> as the <code>while</code> condition.</p>
<pre><code>while True:
my_function()
next_link = driver.find_element_by_id('anch_25')
if not next_li... | 1 | 2016-09-02T21:42:57Z | [
"python",
"for-loop",
"while-loop",
"pagination",
"do-while"
] |
How to perform a loop action at least once and also when a condition is true | 39,301,041 | <p>I am looking for a Python logical equivalent of a <code>do while</code> loop in other languages. I have page results I am iterating through. The results structure:</p>
<pre><code>1, 2, 3, 4 , ... NEXT
</code></pre>
<p>Each element there is a link. only the last page has no <code>NEXT</code> element so I have iden... | 1 | 2016-09-02T21:38:45Z | 39,301,096 | <p>You may use <code>while</code> loop with the variable that is set to <code>True</code> by default and based on your condition, you may change it to <code>True/False</code>. For example:</p>
<pre><code>is_continue = True
while is_continue:
... # Your Logic
if my_condition:
is_continue = True
el... | 1 | 2016-09-02T21:44:06Z | [
"python",
"for-loop",
"while-loop",
"pagination",
"do-while"
] |
Strange nested loop behavior while handling an exception | 39,301,069 | <p>Goal: if count is larger than actual line count, in <code>except</code> block: tell user and have them press enter. set <code>count</code> equal to total number of lines in file and retry the loop. </p>
<pre><code>count = 10000
with open('mobydick_ch1.txt') as f:
while 1:
lines = []
... | 2 | 2016-09-02T21:41:36Z | 39,301,095 | <p>You already exhausted the file, you can't then read from the file <em>again</em> without seeking back to 0. As a result your <code>for i, k in enumerate(f, 1):</code> loop exits immediately. The same then applies to every future iteration of your <code>while 1:</code> loop; the file is still at the end and all acces... | 2 | 2016-09-02T21:44:00Z | [
"python",
"file"
] |
ASCII text executable, with CRLF line terminators | 39,301,086 | <p>Good evening,</p>
<p>I'm currently enrolled in an introduction-course to python and have come across an issue that I haven't been able to solve. I'm sure it's a simple error somewhere in my code, but I haven't been able to find any questions on SO that solved my issue.</p>
<p><em>Strangely enough it compiles and r... | 1 | 2016-09-02T21:43:03Z | 39,301,195 | <p>You need to convert CRLF to LF, to do so you can run this command:</p>
<pre><code>dos2unix your_file
</code></pre>
<p>If you need to apply that to a specific folder content, use the below command inside your folder:</p>
<pre><code>find . -type f -exec dos2unix {} \;
</code></pre>
<p>You need to install <strong>d... | 1 | 2016-09-02T21:54:38Z | [
"python",
"python-3.x"
] |
How do I speed up a piece of python code which has a numpy function embedded in it? | 39,301,122 | <p>Here is the rate limiting function in my code </p>
<pre><code>def timepropagate(wv1, ham11,
ham12, ham22, scalararray, nt):
wv2 = np.zeros((nx, ny), 'c16')
fw1 = np.zeros((nx, ny), 'c16')
fw2 = np.zeros((nx, ny), 'c16')
for t in range(0, nt, 1):
wv1, wv2 = scalararray*wv1... | 0 | 2016-09-02T21:46:23Z | 39,316,416 | <p>If most of the time is spent in the hamiltonian multiplication, you may want to apply numba on that part. The most benefit coming from removing all the temporal arrays that would be needed if evaluating expressions from within NumPy.</p>
<p>Bear also in mind that the arrays (4096, 4096, c16) are big enough to not f... | 0 | 2016-09-04T11:27:37Z | [
"python",
"performance",
"numpy",
"cython",
"numba"
] |
Wait until all threads are started before run them | 39,301,149 | <p>i'd like to do the same thing of this part of script, but possibly in a different way. Is it possible? This script waits that all threads are ready and started and then run the while True of urllib.request... Since I don't want to copy-paste this method, is there a different way to do it?</p>
<pre><code>import thre... | 0 | 2016-09-02T21:49:32Z | 39,301,531 | <p>A better way is to use a <a href="https://docs.python.org/2/library/threading.html#event-objects" rel="nofollow">threading.Event</a> object.</p>
<pre><code>import threading, urllib.request
go = threading.Event()
class request(threading.Thread):
def run(self):
go.wait()
while True:
... | 1 | 2016-09-02T22:40:23Z | [
"python",
"multithreading",
"python-3.x"
] |
Excessive memory usage for very large Python lists loaded from 90GB of JSON for word2vec | 39,301,199 | <p>I'm working using a cluster to generate word2vec models using gensim from sentences from medical journals that are stored in JSON files and I'm having trouble with memory usage being too large.</p>
<p>The task is to keep a cumulative list of all sentences up to a particular year, and then generate a word2vec model ... | 2 | 2016-09-02T21:54:52Z | 39,375,500 | <p>I think you should be able to reduce the memory footprint of the corpus significantly by only explicitly storing the first occurrence of every word. All occurrences after that only need to store a reference to the first. This way you don't spend memory on duplicate strings, at the cost of some overhead. In code it c... | 0 | 2016-09-07T16:53:46Z | [
"python",
"numpy",
"word2vec"
] |
Inserting an array of arrays as the last column | 39,301,247 | <p>I have an array A:</p>
<pre><code>array([[1, 2, 3],
[1, 1, 1],
[2, 2, 2]])
</code></pre>
<p>and an array B:</p>
<pre><code>array([[1, 0],
[1, 0],
[0, 1]])
</code></pre>
<p>I want to make array B as the last column of array A, so I want the result array (let's call it C) to look like t... | -1 | 2016-09-02T22:02:36Z | 39,301,311 | <p>Maybe that's what you're looking for:</p>
<pre><code>import numpy as np
a = np.array([[1, 2, 3],
[1, 1, 1],
[2, 2, 2]])
b = np.array([[1, 0],
[1, 0],
[0, 1]])
np.hstack([a,b])
</code></pre>
<p>Which results in: </p>
<pre><code>array([[1, 2, 3, 1, 0],
... | 1 | 2016-09-02T22:10:42Z | [
"python",
"numpy"
] |
Inserting an array of arrays as the last column | 39,301,247 | <p>I have an array A:</p>
<pre><code>array([[1, 2, 3],
[1, 1, 1],
[2, 2, 2]])
</code></pre>
<p>and an array B:</p>
<pre><code>array([[1, 0],
[1, 0],
[0, 1]])
</code></pre>
<p>I want to make array B as the last column of array A, so I want the result array (let's call it C) to look like t... | -1 | 2016-09-02T22:02:36Z | 39,301,340 | <pre><code>print zip(*zip(*a)+[b.tolist(),])
</code></pre>
<p>although it wont be a numpy array afterwards </p>
<pre><code>>>> a
array([[1, 2, 3],
[1, 1, 1],
[2, 2, 2]])
>>> b
array([[1, 0],
[1, 0],
[0, 1]])
>>> zip(*zip(*a)+[b.tolist(),])
[(1, 2, 3, [1, 0]), (1,... | 1 | 2016-09-02T22:14:16Z | [
"python",
"numpy"
] |
The formula for "Two-for" price is 20% off the total price of two items. Prompt the user for each of the values and calculate the result | 39,301,263 | <p>The following is what the output should look like:</p>
<p>Enter price 1: 10.0</p>
<p>Enter price 2: 20.0</p>
<p>The 'two-for' price is $24.0</p>
<p>The code I entered is:</p>
<pre><code>price_one = float(input('Enter price 1: '))
print(price_one)
price_two = float(input('Enter price 2: '))
print(price_two)
... | 2 | 2016-09-02T22:04:37Z | 39,301,294 | <p>If i'm reading this correctly you just need to remove a space from your output.</p>
<p>Change your last line to this:</p>
<p><code>print("The 'two-for' price is ${0}".format(two_for_price))</code></p>
| 3 | 2016-09-02T22:08:32Z | [
"python"
] |
The formula for "Two-for" price is 20% off the total price of two items. Prompt the user for each of the values and calculate the result | 39,301,263 | <p>The following is what the output should look like:</p>
<p>Enter price 1: 10.0</p>
<p>Enter price 2: 20.0</p>
<p>The 'two-for' price is $24.0</p>
<p>The code I entered is:</p>
<pre><code>price_one = float(input('Enter price 1: '))
print(price_one)
price_two = float(input('Enter price 2: '))
print(price_two)
... | 2 | 2016-09-02T22:04:37Z | 39,301,530 | <p>Your underlying problem is that the <code>print</code> function behavior, given a list of items, is to print each item, separated by a space. This is often convenient for quick-and-dirty print-outs, but you want something more refined.</p>
<p>What you need to do is create a string with the proper spacing and then ... | 1 | 2016-09-02T22:39:55Z | [
"python"
] |
Parsing with regex | 39,301,366 | <p>I'm trying to count the number of lines contained by a file that looks like this:</p>
<pre><code>-StartACheck
---Lines--
-EndACheck
-StartBCheck
---Lines--
-EndBCheck
</code></pre>
<p>with this:</p>
<pre><code>count=0
z={}
for line in file:
s=re.search(r'\-+Start([A-Za-z0-9]+)Check',line)
if s:
... | -2 | 2016-09-02T22:18:05Z | 39,301,539 | <p>You could consider using something like:</p>
<pre><code>import re
from collections import defaultdict
counts = defaultdict(int) # zero if key doesn't exists
for line in file:
start = re.fullmatch('^Start([AB])Check\n$', line).groups()[0]
end = re.fullmatch('^End([AB])Check\n$', line).groups()[0]
if s... | 0 | 2016-09-02T22:42:19Z | [
"python",
"regex"
] |
Parsing with regex | 39,301,366 | <p>I'm trying to count the number of lines contained by a file that looks like this:</p>
<pre><code>-StartACheck
---Lines--
-EndACheck
-StartBCheck
---Lines--
-EndBCheck
</code></pre>
<p>with this:</p>
<pre><code>count=0
z={}
for line in file:
s=re.search(r'\-+Start([A-Za-z0-9]+)Check',line)
if s:
... | -2 | 2016-09-02T22:18:05Z | 39,301,580 | <p>If the file isn't too big (say, smaller than 1GB or so), I'd just read the whole thing and call <code>re.findall()</code>:</p>
<pre><code>import re
result = {
name: lines.count('\n')
for name, lines in
re.findall(r'^-Start([A-Za-z0-9]+)Check$(.*)^-End\1Check$',
open('x.in').read(),
... | 0 | 2016-09-02T22:47:53Z | [
"python",
"regex"
] |
Parsing with regex | 39,301,366 | <p>I'm trying to count the number of lines contained by a file that looks like this:</p>
<pre><code>-StartACheck
---Lines--
-EndACheck
-StartBCheck
---Lines--
-EndBCheck
</code></pre>
<p>with this:</p>
<pre><code>count=0
z={}
for line in file:
s=re.search(r'\-+Start([A-Za-z0-9]+)Check',line)
if s:
... | -2 | 2016-09-02T22:18:05Z | 39,302,099 | <p>Given the pattern of </p>
<pre><code>-StartACheck
--- Line 1
-EndACheck
-StartBCheck
---Line 1
-EndBCheck
-StartACheck
---Line 1
---Line 2
---Line 3
-EndACheck
</code></pre>
<p>You can use a multi-line regex to capture the blocks that start with <code>-Start[pattern]Check</code> and end with <code>-End[pattern]Che... | 0 | 2016-09-03T00:12:44Z | [
"python",
"regex"
] |
Counting the number of set bits in a number | 39,301,375 | <p>The problem statement is: </p>
<p>Write an efficient program to count number of 1s in binary representation of an integer.</p>
<p>I found a post on this problem <a href="http://www.geeksforgeeks.org/count-set-bits-in-an-integer/" rel="nofollow">here</a> which outlines multiple solutions which run in log(n) time in... | -1 | 2016-09-02T22:18:55Z | 39,301,404 | <p>You are converting the integer to a string, which means it'll have to produce N <code>'0'</code> and <code>'1'</code> characters. You then use <code>str.count()</code> which must visit <em>every character</em> in the string to count the <code>'1'</code> characters.</p>
<p>All in all you have a O(N) algorithm, with ... | 5 | 2016-09-02T22:22:45Z | [
"python",
"algorithm",
"bit-manipulation"
] |
Counting the number of set bits in a number | 39,301,375 | <p>The problem statement is: </p>
<p>Write an efficient program to count number of 1s in binary representation of an integer.</p>
<p>I found a post on this problem <a href="http://www.geeksforgeeks.org/count-set-bits-in-an-integer/" rel="nofollow">here</a> which outlines multiple solutions which run in log(n) time in... | -1 | 2016-09-02T22:18:55Z | 39,301,432 | <p>Let's say you are trying to count the number of set bits of <code>n</code>. On <em>Python</em> typical implementations, <code>bin</code> will compute the binary representation in <code>O(log n)</code> time and <code>count</code> will go through the string, therefore resulting in an overall <code>O(log n)</code> comp... | 4 | 2016-09-02T22:25:45Z | [
"python",
"algorithm",
"bit-manipulation"
] |
Append a new column based on existing columns | 39,301,422 | <p>Pandas newbie here. </p>
<p>I'm trying to create a new column in my data frame that will serve as a training label when I feed this into a classifier.</p>
<p>The value of the label column is 1.0 if a given Id has (Value1 > 0) or (Value2 > 0) for Apples or Pears, and 0.0 otherwise.</p>
<p>My dataframe is row inde... | 0 | 2016-09-02T22:24:30Z | 39,301,486 | <p>Define your function: </p>
<pre><code>def new_column (x):
if x['Value1'] > 0 :
return '1.0'
if x['Value2'] > 0 :
return '1.0'
return '0.0'
</code></pre>
<p>Apply it on your data:</p>
<pre><code>df.apply (lambda x: new_column (x),axis=1)
</code></pre>
| 2 | 2016-09-02T22:32:02Z | [
"python",
"pandas",
"numpy",
"sklearn-pandas"
] |
Append a new column based on existing columns | 39,301,422 | <p>Pandas newbie here. </p>
<p>I'm trying to create a new column in my data frame that will serve as a training label when I feed this into a classifier.</p>
<p>The value of the label column is 1.0 if a given Id has (Value1 > 0) or (Value2 > 0) for Apples or Pears, and 0.0 otherwise.</p>
<p>My dataframe is row inde... | 0 | 2016-09-02T22:24:30Z | 39,305,094 | <p>The answer provided by @vlad.rad works, but it is not very efficient since pandas has to manually loop in Python over all rows, not being able to take advantage of numpy vectorized functions speedup. The following vectorized solution should be more efficient:</p>
<pre><code>condition = (df['Value1'] > 0) | (df['... | 1 | 2016-09-03T08:54:00Z | [
"python",
"pandas",
"numpy",
"sklearn-pandas"
] |
Appending one data frame into another | 39,301,465 | <p>I want to bring three data frames into a single one .All data frames have a single column .</p>
<pre><code>org_city_id=p.DataFrame(training_data['origcity_id'])
pol_city_id=p.DataFrame(training_data['pol_city_id'])
pod_city_id=p.DataFrame(training_data['pod_city_id'])
</code></pre>
<p>All have 100 records in it so... | 2 | 2016-09-02T22:29:30Z | 39,301,490 | <p>Get a single column name for all your dataframes:</p>
<pre><code>org_city_id.columns = pol_city_id.columns = pod_city_id.columns = 'Final Name'
</code></pre>
<p>Then concat them:</p>
<pre><code>pd.concat([org_city_id,pol_city_id,pod_city_id])
</code></pre>
| 1 | 2016-09-02T22:32:17Z | [
"python",
"pandas",
"dataframe"
] |
Appending one data frame into another | 39,301,465 | <p>I want to bring three data frames into a single one .All data frames have a single column .</p>
<pre><code>org_city_id=p.DataFrame(training_data['origcity_id'])
pol_city_id=p.DataFrame(training_data['pol_city_id'])
pod_city_id=p.DataFrame(training_data['pod_city_id'])
</code></pre>
<p>All have 100 records in it so... | 2 | 2016-09-02T22:29:30Z | 39,301,496 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow">concat</a> from Pandas documentation.</p>
<p>Here is what you'll do:</p>
<p><code>pd.concat([org_city_id, pol_city_id, pod_city_id])</code></p>
| 0 | 2016-09-02T22:33:08Z | [
"python",
"pandas",
"dataframe"
] |
Appending one data frame into another | 39,301,465 | <p>I want to bring three data frames into a single one .All data frames have a single column .</p>
<pre><code>org_city_id=p.DataFrame(training_data['origcity_id'])
pol_city_id=p.DataFrame(training_data['pol_city_id'])
pod_city_id=p.DataFrame(training_data['pod_city_id'])
</code></pre>
<p>All have 100 records in it so... | 2 | 2016-09-02T22:29:30Z | 39,302,322 | <pre><code>dfs = [org_city_id, pol_city_id, pod_city_id]
pd.concat([df.squeeze() for df in dfs], ignore_index=True)
</code></pre>
| 3 | 2016-09-03T00:55:55Z | [
"python",
"pandas",
"dataframe"
] |
Dynamically call a var inside string in function | 39,301,564 | <p>I'm new to python, I have var (string) which is an <em>Xpath</em> query. I want to pass the variable <em><code>i</code></em> into the <em>Xpath</em> query. A simple example below:</p>
<pre><code>i = 0
self.var = 'li['+i+']'
def test(self):
while(i<10):
print self.var # 'li[0]', 'li[1]' ...
i += 1
</co... | -2 | 2016-09-02T22:45:59Z | 39,301,596 | <p>You would need to call <em><code>str</code></em> on the variable <em><code>i</code></em>, you cannot concatenate an int and a str:</p>
<pre><code> 'li['+str(i)+']'
</code></pre>
<p>Or just use <em>str.format</em>, you can also pass use range and xpath indexing is also 1-based so you would start at 1:</p>
<pre><co... | 1 | 2016-09-02T22:49:48Z | [
"python"
] |
Dynamically call a var inside string in function | 39,301,564 | <p>I'm new to python, I have var (string) which is an <em>Xpath</em> query. I want to pass the variable <em><code>i</code></em> into the <em>Xpath</em> query. A simple example below:</p>
<pre><code>i = 0
self.var = 'li['+i+']'
def test(self):
while(i<10):
print self.var # 'li[0]', 'li[1]' ...
i += 1
</co... | -2 | 2016-09-02T22:45:59Z | 39,301,647 | <p>You can create a list with the first string, the integer, and the second string. </p>
<pre><code>i = 0
var = ['li[',i,']']
def test(var):
while(var[1]<10):
print var[0]+str(var[1])+var[2]
var[1] += 1
test(var)
</code></pre>
| 0 | 2016-09-02T22:56:59Z | [
"python"
] |
How to log to different files based on from which python process logging is called? | 39,301,593 | <p>I am working on a test framework. Each test is launched as a new python multiprocessing process.
There is one master log file and individual log files corresponding to each test.
There is a master logger created at the launch of framework code and a new logger created in each test process. Test loggers log to both... | 0 | 2016-09-02T22:49:42Z | 39,301,704 | <p>The <a href="https://docs.python.org/3/library/threading.html" rel="nofollow">threading</a> module has a <code>get_ident</code> member which could be used to index some logger dictionary, something like;</p>
<pre><code>from threading import get_ident
loggers[get_ident()].logError('blah blah blah')
</code></pre>
<... | 0 | 2016-09-02T23:05:42Z | [
"python",
"logging",
"python-multiprocessing"
] |
Quickly convert numpy arrays with index to dict of numpy arrays keyed on that index | 39,301,666 | <p>I have a set of numpy arrays. One of these is a list of "keys", and I'd like to rearrange the arrays into a dict of arrays keyed on that key. My current code is:</p>
<pre><code>for key, val1, val2 in itertools.izip(keys, vals1, vals2):
dict1[key].append(val1)
dict2[key].append(val2)
</code></pre>
<p>This i... | 2 | 2016-09-02T22:59:49Z | 39,301,716 | <p>Let's import numpy and create some sample data:</p>
<pre><code>>>> import numpy as np
>>> keys = np.array(('key1', 'key2', 'key3', 'key1', 'key2', 'key1'))
>>> vals1 = np.arange(6)
>>> vals2 = np.arange(10, 16)
</code></pre>
<p>Now, let's create the dictionary:</p>
<pre><code>&... | 2 | 2016-09-02T23:07:14Z | [
"python",
"numpy",
"vectorization"
] |
Quickly convert numpy arrays with index to dict of numpy arrays keyed on that index | 39,301,666 | <p>I have a set of numpy arrays. One of these is a list of "keys", and I'd like to rearrange the arrays into a dict of arrays keyed on that key. My current code is:</p>
<pre><code>for key, val1, val2 in itertools.izip(keys, vals1, vals2):
dict1[key].append(val1)
dict2[key].append(val2)
</code></pre>
<p>This i... | 2 | 2016-09-02T22:59:49Z | 39,301,900 | <p>The vectorized way to do this is probably going to require you to sort your keys. The basic idea is that you sort the keys and vals to match. Then you can split the val array every time there is a new key in the sorted keys array. The vectorized code looks something like this:</p>
<pre><code>import numpy as np
key... | 2 | 2016-09-02T23:37:21Z | [
"python",
"numpy",
"vectorization"
] |
Quickly convert numpy arrays with index to dict of numpy arrays keyed on that index | 39,301,666 | <p>I have a set of numpy arrays. One of these is a list of "keys", and I'd like to rearrange the arrays into a dict of arrays keyed on that key. My current code is:</p>
<pre><code>for key, val1, val2 in itertools.izip(keys, vals1, vals2):
dict1[key].append(val1)
dict2[key].append(val2)
</code></pre>
<p>This i... | 2 | 2016-09-02T22:59:49Z | 39,302,125 | <p><code>defaultdict</code> is intended for building dictionaries like this. In particular is streamlines the step of creating a new dictionary entry for a new key.</p>
<pre><code>In [19]: keys = np.random.choice(np.arange(10),100)
In [20]: vals=np.arange(100)
In [21]: from collections import defaultdict
In [22]: dd ... | 0 | 2016-09-03T00:16:59Z | [
"python",
"numpy",
"vectorization"
] |
Quickly convert numpy arrays with index to dict of numpy arrays keyed on that index | 39,301,666 | <p>I have a set of numpy arrays. One of these is a list of "keys", and I'd like to rearrange the arrays into a dict of arrays keyed on that key. My current code is:</p>
<pre><code>for key, val1, val2 in itertools.izip(keys, vals1, vals2):
dict1[key].append(val1)
dict2[key].append(val2)
</code></pre>
<p>This i... | 2 | 2016-09-02T22:59:49Z | 39,302,214 | <p>Some timings:</p>
<pre><code>import numpy as np
import itertools
def john1024(keys, v1, v2):
d1 = {}; d2 = {};
for k in set(keys):
d1[k] = v1[k==keys]
d2[k] = v2[k==keys]
return d1,d2
def birico(keys, v1, v2):
order = keys.argsort()
keys_sorted = keys[order]
diff = np.ones(keys_sorted.shape, d... | 2 | 2016-09-03T00:34:03Z | [
"python",
"numpy",
"vectorization"
] |
Identifying Consecutive Sequences of Data and Counting their Lengths | 39,301,691 | <p>I am working with a DataFrame where each row observation has an ordinal datetime object attached to it. I've written a function that I believe looks through my DataFrame and identifies consecutively occurring days and the length of run of these consecutively occurring days with the following code: </p>
<pre><code> ... | 1 | 2016-09-02T23:03:27Z | 39,301,862 | <p>IIUC, you can you can use the shift-compare-cumsum pattern after applying your groupby, and then do a transform.</p>
<p>Assuming that your data looks something like this (simplifying a bit)</p>
<pre><code>df = pd.DataFrame({"GEOID_YEAR": [2000]*10 + [2001]*4, "TEMPBIN": [1]*14,
"DATE_INT": [1,2,... | 1 | 2016-09-02T23:30:12Z | [
"python",
"function",
"datetime",
"pandas",
"dataframe"
] |
Python: delete all variables except one for loops without contaminations | 39,301,752 | <pre><code>%reset
%reset -f
</code></pre>
<p>and </p>
<pre><code>%reset_selective a
%reset_selective -f a
</code></pre>
<p>are usefull Python alternative to the Matlab command "clear all", in which "-f" means "force without asking for confirmation" and "_selective" could be used in conjunction with </p>
<pre><code>... | -1 | 2016-09-02T23:12:35Z | 39,302,526 | <p>The normal approach to limiting the scope of variables is to use them in a function. When the function is done, its <code>locals</code> disappear.</p>
<pre><code>In [71]: def foo():
...: a=1
...: b=2
...: c=[1,2,3]
...: d=np.arange(12)
...: print(locals())
...: del(a... | 2 | 2016-09-03T01:48:09Z | [
"python",
"ipython"
] |
Tensor too big for graph distribution - "InternalError: Message length was negative" | 39,301,773 | <p><strong>I tried to run the following graph:</strong>
<a href="http://i.stack.imgur.com/y5d5x.png" rel="nofollow"><img src="http://i.stack.imgur.com/y5d5x.png" alt="Graph that causes the error."></a></p>
<p><strong>Unfortunately, I receive the following error message:</strong></p>
<pre><code>tensorflow.python.frame... | 1 | 2016-09-02T23:15:16Z | 39,301,914 | <p>Yes, currently there is a <strong>2GB limit</strong> on an individual tensor when sending it between processes. This limit is imposed by the protocol buffer representation (more precisely, by the auto-generated C++ wrappers produced by the <code>protoc</code> compiler) that is used in TensorFlow's communication laye... | 2 | 2016-09-02T23:39:33Z | [
"python",
"tensorflow",
"distribution"
] |
Django 1.10: extend/override admin css | 39,301,791 | <p>I want to override the css definition of a select-multiple widget by decreasing the min-height attribute from <code>contrib/admin/static/admin/css/base.css</code>. However, my css is not loaded I think. I use a custom admin form and have defined the Media subclass within this form as well as within the corresponding... | 0 | 2016-09-02T23:18:06Z | 39,355,192 | <p>I've found the solution myself. It is indeed only one character, but not the whitespace in the filename that Jonas pointed me to (I'm on a Windows filesystem, maybe that's different on linux). Instead, it's the leading slash of the URL in the Media class. Instead of:</p>
<pre><code> class Media:
css = {
... | 0 | 2016-09-06T18:01:57Z | [
"python",
"css",
"django",
"admin"
] |
How to determine whether a Python string contains an emoji? | 39,301,796 | <p>I've seen previous responses to this question, but none of them are recent and none of them are working for me in Python 3. I have a list of strings, and I simply want to identify which ones contain emoji. What's the fastest way to do this?</p>
<p>To be more specific, I have a lengthy list of email subject lines fr... | 0 | 2016-09-02T23:18:46Z | 39,303,198 | <p>You could do something like this</p>
<pre><code>text = input('What is your text? ')
if text != 'a' # or b c d -z then all other characters + - etc
</code></pre>
<p>However this would be a long way of doing it.</p>
| 0 | 2016-09-03T04:20:48Z | [
"python",
"emoji"
] |
How to determine whether a Python string contains an emoji? | 39,301,796 | <p>I've seen previous responses to this question, but none of them are recent and none of them are working for me in Python 3. I have a list of strings, and I simply want to identify which ones contain emoji. What's the fastest way to do this?</p>
<p>To be more specific, I have a lengthy list of email subject lines fr... | 0 | 2016-09-02T23:18:46Z | 39,303,814 | <p><a href="http://stackoverflow.com/questions/28290240/python-2-7-detect-emoji-from-text/28327594#28327594">this link</a> and <a href="http://stackoverflow.com/questions/38730560/is-there-a-specific-range-of-unicode-code-points-which-can-be-checked-for-emojis">this link</a> both count © and other common characters as... | 1 | 2016-09-03T06:11:43Z | [
"python",
"emoji"
] |
Divide date as day,month and year | 39,301,871 | <p>l have 41 year-dataset and l would like to do some calculations by using these dataset but for this, l need to divide the date into day, month and year respectively.</p>
<p>example dataset(csv file data)</p>
<pre><code> date stations pcp
1.01.1979 6 1.071
2.01.1979 6 5.909
3.01.1979 6 9.134
1.... | 0 | 2016-09-02T23:31:49Z | 39,301,965 | <p>There are a few problems:</p>
<ol>
<li>Your delimiter should be a comma instead of a semicolon if it's a CSV.</li>
<li>You are splitting on a date string instead of a delimiter when you call <code>a.split(x[i])</code>. You probably want to split on a <code>.</code>, since that's what's separating the date fields.</... | 3 | 2016-09-02T23:49:49Z | [
"python",
"date",
"csv"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.