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 |
|---|---|---|---|---|---|---|---|---|---|
is there a function to get axis interval | 38,605,027 | <p>I have a axes variable <code>ax</code>.</p>
<pre><code>ax.get_yticks()
Out[37]: array([ 0. , 0.2, 0.4, 0.6, 0.8, 1. ])
</code></pre>
<p>I want to get the ticks intervalï¼0.2-0). Is there a function to return the result (0.2)?</p>
| 1 | 2016-07-27T06:11:40Z | 38,605,135 | <p>Use this:</p>
<pre><code>intervalSize = ax.get_yticks[1] - ax.get_yticks[0]
</code></pre>
| 0 | 2016-07-27T06:19:25Z | [
"python",
"matplotlib"
] |
python pandas from 0/1 dataframe to an itemset list | 38,605,111 | <p>What is the most efficient way to go from a 0/1 pandas/numpy dataframe of this form::</p>
<pre><code>>>> dd
{'a': {0: 1, 1: 0, 2: 1, 3: 0, 4: 1, 5: 1},
'b': {0: 1, 1: 1, 2: 0, 3: 0, 4: 1, 5: 1},
'c': {0: 0, 1: 1, 2: 1, 3: 0, 4: 1, 5: 1},
'd': {0: 0, 1: 1, 2: 1, 3: 1, 4: 0, 5: 1},
'e': {0: 0, 1: 0, 2: 1... | 2 | 2016-07-27T06:18:01Z | 38,605,258 | <p>You can first multiple by columns names by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mul.html" rel="nofollow"><code>mul</code></a> and convert <code>DataFrame</code> to <code>numpy array</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.va... | 2 | 2016-07-27T06:26:02Z | [
"python",
"numpy",
"pandas"
] |
python pandas from 0/1 dataframe to an itemset list | 38,605,111 | <p>What is the most efficient way to go from a 0/1 pandas/numpy dataframe of this form::</p>
<pre><code>>>> dd
{'a': {0: 1, 1: 0, 2: 1, 3: 0, 4: 1, 5: 1},
'b': {0: 1, 1: 1, 2: 0, 3: 0, 4: 1, 5: 1},
'c': {0: 0, 1: 1, 2: 1, 3: 0, 4: 1, 5: 1},
'd': {0: 0, 1: 1, 2: 1, 3: 1, 4: 0, 5: 1},
'e': {0: 0, 1: 0, 2: 1... | 2 | 2016-07-27T06:18:01Z | 38,605,434 | <p>Simple list comprehesion:</p>
<pre><code>itemset = [[df.columns.values[j] # the output based on the following logic:
for j in range(0, len(df.iloc[i]))
if df.iloc[i][j] == 1]
for i in range(0, len(df.index))]
print (itemset)
</code></pre>
<p>Gives the result:</p>
<pre><code>$ python test.py
[['a... | 0 | 2016-07-27T06:37:02Z | [
"python",
"numpy",
"pandas"
] |
python pandas from 0/1 dataframe to an itemset list | 38,605,111 | <p>What is the most efficient way to go from a 0/1 pandas/numpy dataframe of this form::</p>
<pre><code>>>> dd
{'a': {0: 1, 1: 0, 2: 1, 3: 0, 4: 1, 5: 1},
'b': {0: 1, 1: 1, 2: 0, 3: 0, 4: 1, 5: 1},
'c': {0: 0, 1: 1, 2: 1, 3: 0, 4: 1, 5: 1},
'd': {0: 0, 1: 1, 2: 1, 3: 1, 4: 0, 5: 1},
'e': {0: 0, 1: 0, 2: 1... | 2 | 2016-07-27T06:18:01Z | 38,607,200 | <p>Here's a NumPy based vectorized approach to get a list of arrays as output -</p>
<pre><code>In [47]: df
Out[47]:
a b c d e
0 1 1 0 0 0
1 0 1 1 1 0
2 1 0 1 1 1
3 0 0 0 1 0
4 1 1 1 0 0
5 1 1 1 1 0
In [48]: cols = df.columns.values.astype(str)
In [49]: R,C = np.where(df.values==... | 1 | 2016-07-27T08:03:10Z | [
"python",
"numpy",
"pandas"
] |
Why Python Pandas append to DataFrame like this? | 38,605,182 | <p>I want to add l in column 'A' but it creates a new column and adds l to the last one. Why is it happening? And how can I make what I want?</p>
<pre><code>import pandas as pd
l=[1,2,3]
df = pd.DataFrame(columns =['A'])
df = df.append(l, ignore_index=True)
df = df.append(l, ignore_index=True)
print(df)
A 0
0... | 0 | 2016-07-27T06:22:22Z | 38,605,221 | <p><strong>Edited</strong>
Is this what you want to do:</p>
<pre><code>In[6]:df=df.A.append(pd.Series(l)).reset_index().drop('index',1).rename(columns={0:'A'})
In[7]:df
Out[7]:
A
0 1
1 2
2 3
</code></pre>
<p>Then you can add any list of different length.
Suppose:</p>
<pre><code>a=[9,8,7,6,5]
In[11]:df=df.A.... | 2 | 2016-07-27T06:24:29Z | [
"python",
"pandas"
] |
Why Python Pandas append to DataFrame like this? | 38,605,182 | <p>I want to add l in column 'A' but it creates a new column and adds l to the last one. Why is it happening? And how can I make what I want?</p>
<pre><code>import pandas as pd
l=[1,2,3]
df = pd.DataFrame(columns =['A'])
df = df.append(l, ignore_index=True)
df = df.append(l, ignore_index=True)
print(df)
A 0
0... | 0 | 2016-07-27T06:22:22Z | 38,605,283 | <p>You can just pass a dictionary in the dataframe constructor, that if I understand your question correctly.</p>
<pre><code>l = [1,2,3]
df = pd.DataFrame({'A': l})
df
A
0 1
1 2
2 3
</code></pre>
| 2 | 2016-07-27T06:28:06Z | [
"python",
"pandas"
] |
Cyclic import error | 38,605,374 | <p>Whatever I try to import from my <code>pupils</code> app, I get an import error. For example:</p>
<p><strong>offices/models.py</strong></p>
<pre><code>from pupils.models import Pupils # => ImportError: cannot import name Pupils
</code></pre>
<p>I bet the path is right, PyCharm reads it. Everything imports fin... | 0 | 2016-07-27T06:33:52Z | 38,605,476 | <p>I guess you meet the <code>cyclic imports</code> problem.</p>
<p>An easy way to fix it is import <code>Pupils</code> later:</p>
<pre><code>def where_you_need_pupils():
from pupils.models import Pupils
# do something
</code></pre>
| 1 | 2016-07-27T06:39:48Z | [
"python",
"django",
"import",
"python-import"
] |
calculate the length of a sequence after adding the length of previous sequences | 38,605,751 | <p>I want to determine length of individual sequences in a multifasta file. I got this biopython code from the bio manual as: </p>
<pre><code>from Bio import SeqIO
import sys
cmdargs = str(sys.argv)
for seq_record in SeqIO.parse(str(sys.argv[1]), "fasta"):
output_line = '%s\t%i' % \
(seq_record.id, len(seq_record))
... | 0 | 2016-07-27T06:54:34Z | 38,606,984 | <p>It is easy just to get the total length:</p>
<pre><code>from Bio import SeqIO
import sys
cmdargs = str(sys.argv)
total_len = 0
for seq_record in SeqIO.parse(str(sys.argv[1]), "fasta"):
total_len += len(seq_record)
output_line = '%s\t%i' % (seq_record.id, total_len))
print(output_line)
</code></pre>
<p>... | 0 | 2016-07-27T07:52:09Z | [
"python",
"biopython",
"fasta"
] |
Read a file multi-threaded in python in chunks of 2KB. | 38,605,752 | <p>I have to read a file in chunks of 2KB and do some operation on those chunks. Now where I'm actually stuck is, when the data needs to be thread-safe. From what I've seen in online tutorials and StackOverflow answers, we define a worker thread, and override its run method. The run method uses data from a queue which ... | 0 | 2016-07-27T06:54:37Z | 38,606,759 | <p>Reading the file serially is your best option since (hardware wise) it gives you the best read throughout.</p>
<p><em>Usually</em> the slow part is not in the data reading but in its processing...</p>
| 1 | 2016-07-27T07:41:19Z | [
"python",
"multithreading",
"thread-safety",
"python-multithreading"
] |
Use QProcessAnimation on main window | 38,605,771 | <p>I'm having an issue trying to animate a QMainWindow. I'm trying to make a "slide" animation for a side panel. It works fine if I call it before the "app.exec" however calling the "animate_out" function it seems not to do anything. Any ideas?</p>
<p>PS: You can un-comment the code towards the bottom to see an exampl... | 1 | 2016-07-27T06:55:31Z | 38,692,042 | <p>The problem is that the <code>animation</code> Object will not outlive the scope of the <code>animate_out</code> out function.
To solve this you have to add the <code>animation</code> Object as a member to the <code>HUB</code> class.</p>
<p>In my Example code I also split the creation and playing of the animation i... | 0 | 2016-08-01T06:14:07Z | [
"python",
"qt",
"pyqt",
"pyside"
] |
python script for convert video to image sequence using FFmpeg | 38,605,822 | <p>I have 100 uncompressed mov (Video files) and i want to convert all mov to sgi image sequences.</p>
<p>i have a list of all mov file path.</p>
<p>how to convert .mov (video) to .sgi (image sequence) using <a href="https://www.python.org/" rel="nofollow">python</a> and <a href="https://ffmpeg.org/" rel="nofollow">F... | 0 | 2016-07-27T06:57:40Z | 38,607,558 | <p>you can use ffmpeg to convert the video to sgi images using this ffmpeg command</p>
<pre><code>ffmpeg -i inputVideo outputFrames_%04d.sgi
</code></pre>
<p>-replace inputVideo your input file path and name</p>
<p>-replace outputFrames with output file path and name</p>
<p>-replace '4' in _%04d with the number of ... | 1 | 2016-07-27T08:21:30Z | [
"python",
"ffmpeg"
] |
No. of occurrences of maximum item in a list | 38,605,838 | <p>Suppose I have a <code>list</code></p>
<pre><code>L= [3 2 1 3 5 4 5 3 5 3]
</code></pre>
<p>Output should be <code>3</code> as <code>5</code> is maximum in the list as its no. of occurrences is <code>3</code></p>
<p>I am able to try this till now</p>
<pre><code>from collections import defaultdict
d = defaultdic... | -1 | 2016-07-27T06:58:22Z | 38,606,043 | <p>Check this Code:-</p>
<pre><code>L= [3, 2, 1, 3, 5, 4, 5, 3, 5, 3]
newDict = {}
for i in L:
newDict.setdefault(i,0)
newDict[i]+=1
filter( lambda x : (newDict[x] == max(newDict.values())) ,newDict)[0]
</code></pre>
| 1 | 2016-07-27T07:08:14Z | [
"python"
] |
No. of occurrences of maximum item in a list | 38,605,838 | <p>Suppose I have a <code>list</code></p>
<pre><code>L= [3 2 1 3 5 4 5 3 5 3]
</code></pre>
<p>Output should be <code>3</code> as <code>5</code> is maximum in the list as its no. of occurrences is <code>3</code></p>
<p>I am able to try this till now</p>
<pre><code>from collections import defaultdict
d = defaultdic... | -1 | 2016-07-27T06:58:22Z | 38,606,210 | <p>You were picking the maximum <em>count</em>, rather than the maximum <em>item</em>. You could have solved this by dropping the <code>key</code> argument to <code>max()</code>, and then just print the result (not the length of it, that'll <em>always</em> be 2!):</p>
<pre><code>result = max(d.iteritems())
print resul... | 2 | 2016-07-27T07:15:13Z | [
"python"
] |
No. of occurrences of maximum item in a list | 38,605,838 | <p>Suppose I have a <code>list</code></p>
<pre><code>L= [3 2 1 3 5 4 5 3 5 3]
</code></pre>
<p>Output should be <code>3</code> as <code>5</code> is maximum in the list as its no. of occurrences is <code>3</code></p>
<p>I am able to try this till now</p>
<pre><code>from collections import defaultdict
d = defaultdic... | -1 | 2016-07-27T06:58:22Z | 38,606,237 | <p>Use <code>max</code> and <code>list.count</code>:</p>
<pre><code>max_element= max(L)
count= L.count(max_element)
print(count)
</code></pre>
| 3 | 2016-07-27T07:16:33Z | [
"python"
] |
Using python pandas timestamps in sklearn.cross_validation.cross_val_score | 38,605,916 | <p>One of my dataframe columns is dates. In order to use it in my analysis I convert it to datetime as follows:</p>
<pre><code>datetime_columns = ['my_dates']
for c in datetime_columns:
df[c] = pd.to_datetime(df[c], infer_datetime_format=False)
</code></pre>
<p>Conversion does the job:</p>
<pre><code>print df['m... | 2 | 2016-07-27T07:02:30Z | 38,607,335 | <p>Try to convert your <code>my_dates</code> column into <code>np.int64</code> dtype in order to make <code>cross_val_score()</code> happy</p>
<p>Demo:</p>
<pre><code>In [330]: df = pd.DataFrame({'my_dates':pd.date_range('2001-01-01', periods=10, freq='55555T')})
In [331]: df
Out[331]:
my_dates
0 2001-0... | 0 | 2016-07-27T08:10:07Z | [
"python",
"pandas",
"timestamp",
"scikit-learn"
] |
Accesing <td> elements in a table that do not have ID or class when using python and BeautifulSoup on html/css pages | 38,605,967 | <p>I am scraping a page using Selenium, Python and Beautiful Soup, and I want to output the rows of a table as comma delimited values. Unfortunately the HTML of the page is all over the place. So far I have managed to extract two columns by using the IDs of their elements. The rest of the values are just contained in ... | 0 | 2016-07-27T07:04:39Z | 38,612,036 | <p>If all you want is to just dump out the content, something like this should do:</p>
<pre><code>myTable = bsObj.find_element_by_tag_name("table")
for table_ in myTable:
rows = table_.find_elements_by_tag_name("tr")
for row_ in rows:
columns = row_.find_elements_by_tag_name("td")
for column_ i... | 0 | 2016-07-27T11:45:08Z | [
"python",
"html",
"css",
"selenium",
"beautifulsoup"
] |
How to get output of Python Selenium code in Excel format? | 38,606,024 | <pre><code>import urllib2
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
url = ("http://www.justdial.com/Mumbai/CA")
driver = webdriver.Firefox()
driver.get(url)
driver
elements = driver.find_elements_by_xpath('//div[@cla... | 0 | 2016-07-27T07:07:19Z | 38,610,461 | <p>The following should get you started. The important thing is to ensure your xpath entries select exactly what you need. Python's <a href="https://docs.python.org/2/library/csv.html#module-csv" rel="nofollow"><code>csv module</code></a> can be used to convert the lists obtained automatically into comma separated entr... | 0 | 2016-07-27T10:31:34Z | [
"python"
] |
REST Framework: how to serialize objects? | 38,606,028 | <p>I want to create a ListView with a array of nested objects. Here what I've tried so far:</p>
<p><strong>rest.py</strong></p>
<pre><code>class GroupDetailSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = (
'id',
'num',
'students',
... | 0 | 2016-07-27T07:07:35Z | 38,606,368 | <p>Error is because your model is not json serializable.</p>
<p>you can see @yuwang comment to follow nested serializer <a href="http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects" rel="nofollow">http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-object... | 1 | 2016-07-27T07:21:39Z | [
"python",
"json",
"django",
"django-rest-framework"
] |
Error occured while building recommendation Engine using pio build --verbose in predictionio | 38,606,214 | <p>I am trying to Integrate Predicitionio with my App. I followed the steps in <a href="http://docs.prediction.io/templates/recommendation/quickstart/" rel="nofollow">Quick start</a>
I am stuck in step 5, Deploying Engine as a Service. I couldn't build the Recommendation using <code>pio build --verbose</code>. Followin... | 2 | 2016-07-27T07:15:26Z | 38,634,140 | <p>Reason was 'pio' is not set as an environment variable. So I execute building engine as follows. </p>
<pre><code>/home/PredictionIO/PredictionIO-0.9.6/bin/pio build --verbose
</code></pre>
<p>Then it works for me</p>
| 0 | 2016-07-28T10:47:39Z | [
"python",
"statistics",
"prediction",
"predictionio"
] |
Python, Correct way to formulate Binary Data ready to be sent over serial | 38,606,244 | <p>I am in need of creating a device which talks to a different device over serial. Pretty basic stuff.</p>
<p>However, All I need to do is pass down specific binary data and the device will handle the rest.</p>
<p>The data has to be in binary format and I have seen various way to do it across the internet but really... | 0 | 2016-07-27T07:16:49Z | 38,606,664 | <p>Binary literals in python look like this:</p>
<pre><code>>>> 0b11
3
>>> 0b10
2
>>> 0b100
4
</code></pre>
<p>you can manipulate bits using bitwise operators:</p>
<pre><code>>>> 0b1000
8
>>> 0b1000 | 0b1
9
</code></pre>
<p><code>|</code> is just the <code>or</code> oper... | 1 | 2016-07-27T07:36:08Z | [
"python",
"serial-port",
"byte",
"bit"
] |
How to get pseudo-private attribute through inner class in Python? | 38,606,265 | <pre><code>class Test:
__x = 1
class C:
def test(self):
print(Test.__x)
c = C()
a = Test()
a.c.test()
</code></pre>
<p>I get Error Information like this</p>
<blockquote>
<p>AttributeError: type object 'Test' has no attribute '_C__x'</p>
</blockquote>
<p>So, is it inner class cannot... | 3 | 2016-07-27T07:17:43Z | 38,606,477 | <p>Adding to underscores is the proper way to declare private attributes in Python. Your code would work fine if you changed the name of <code>__x</code> to <code>_Test__x</code> when you call it from the other class.</p>
<pre><code>class Test:
__x = 1
class C:
def test(self):
print(Test._T... | 1 | 2016-07-27T07:26:34Z | [
"python",
"python-3.x"
] |
How to get pseudo-private attribute through inner class in Python? | 38,606,265 | <pre><code>class Test:
__x = 1
class C:
def test(self):
print(Test.__x)
c = C()
a = Test()
a.c.test()
</code></pre>
<p>I get Error Information like this</p>
<blockquote>
<p>AttributeError: type object 'Test' has no attribute '_C__x'</p>
</blockquote>
<p>So, is it inner class cannot... | 3 | 2016-07-27T07:17:43Z | 38,606,797 | <p>From <a href="https://docs.python.org/3/tutorial/classes.html#private-variables" rel="nofollow">Private Variables</a></p>
<blockquote>
<p>Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the curren... | 2 | 2016-07-27T07:43:10Z | [
"python",
"python-3.x"
] |
Looping through HTML tags using BeautifulSoup | 38,606,290 | <p>As mentioned in the previous questions, I am using Beautiful soup with python to retrieve weather data from a website.</p>
<p>Here's how the website looks like:</p>
<pre><code><channel>
<title>2 Hour Forecast</title>
<source>Meteorological Services Singapore</source>
<description&g... | 0 | 2016-07-27T07:18:30Z | 38,606,655 | <p>The problem is in the line: <code>writer.writerow( (time, element['date'], element['time'], area, name))</code>, the <code>name</code> never change.</p>
<p>A way to fix it:</p>
<pre><code>try:
for index, area in enumerate(area_attrs_li):
# print str(area) + "\n"
writer = csv.writer(f)
w... | 1 | 2016-07-27T07:35:44Z | [
"python",
"beautifulsoup"
] |
Looping through HTML tags using BeautifulSoup | 38,606,290 | <p>As mentioned in the previous questions, I am using Beautiful soup with python to retrieve weather data from a website.</p>
<p>Here's how the website looks like:</p>
<pre><code><channel>
<title>2 Hour Forecast</title>
<source>Meteorological Services Singapore</source>
<description&g... | 0 | 2016-07-27T07:18:30Z | 38,606,680 | <p>This is because when you are writing, you are referring last instance of loop, try this :</p>
<pre><code>writer.writerow( (time, element['date'], element['time'], area, area['name']))
</code></pre>
| 1 | 2016-07-27T07:36:51Z | [
"python",
"beautifulsoup"
] |
Looping through HTML tags using BeautifulSoup | 38,606,290 | <p>As mentioned in the previous questions, I am using Beautiful soup with python to retrieve weather data from a website.</p>
<p>Here's how the website looks like:</p>
<pre><code><channel>
<title>2 Hour Forecast</title>
<source>Meteorological Services Singapore</source>
<description&g... | 0 | 2016-07-27T07:18:30Z | 38,606,750 | <p>After the loop you are getting only one value in the name variable. You need to have a list. try this </p>
<pre><code>areas = soup.select('area')
name=[]
for data in areas:
name.append(data.get('name'))
print name
l=len(name)
</code></pre>
<p>and in try finally</p>
<pre><code>i=0
try:
for area in are... | 1 | 2016-07-27T07:40:44Z | [
"python",
"beautifulsoup"
] |
How do I select a random index in a print statement python | 38,606,291 | <p>I have this print statement and I want to select a random index from the list provided</p>
<pre><code>print("{randint(1, 10)}".format(player_r1, player_r2, player_r3, player_r4, player_r5, player_r6, player_r7, player_r8, player_r9, player_r10))
</code></pre>
| 0 | 2016-07-27T07:18:32Z | 38,606,394 | <p>Code expressions inside strings are not evaluated, it's just text. </p>
<pre><code>import random
print("{}".format(random.choice([player_r1, player_r2, player_r3, player_r4, player_r5, player_r6, player_r7, player_r8, player_r9, player_r10])))
</code></pre>
<p>Or something more readable:</p>
<pre><code>players =... | 1 | 2016-07-27T07:22:44Z | [
"python",
"indexing"
] |
Python:Syntax Error while using Lambda Function inside List | 38,606,293 | <p>I am relatively new to python. I am trying to filter data in List using a Lambda, but the compiler gives me a syntax error for the commented code.</p>
<pre><code># documents = [(list(filter(lambda w:w if not w in stop_words,movie_reviews.words(fileid))),category)
# for category in movie_reviews.categories(... | 0 | 2016-07-27T07:18:34Z | 38,606,397 | <p><code>x if y</code> expressions require an <code>else</code>. It's an expression which must return a value, and without <code>else</code> it's undefined what's supposed to happen in the event that the <code>if</code> condition does not apply.</p>
<p>At the very least you need:</p>
<pre><code>w if w not in stop_wor... | 1 | 2016-07-27T07:22:58Z | [
"python",
"list",
"lambda"
] |
Python:Syntax Error while using Lambda Function inside List | 38,606,293 | <p>I am relatively new to python. I am trying to filter data in List using a Lambda, but the compiler gives me a syntax error for the commented code.</p>
<pre><code># documents = [(list(filter(lambda w:w if not w in stop_words,movie_reviews.words(fileid))),category)
# for category in movie_reviews.categories(... | 0 | 2016-07-27T07:18:34Z | 38,606,411 | <p>The problem is here:</p>
<pre><code>w if not w in stop_words
</code></pre>
<p>This is the first half of a <a href="http://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator">ternary condition operator</a>, but it's missing the <code>else</code> block.</p>
<p>You actually don't need... | 2 | 2016-07-27T07:23:28Z | [
"python",
"list",
"lambda"
] |
Skimage: how to show image | 38,606,372 | <p>I am novice at skimage and I try to show the image in my ipython notebook:\</p>
<pre><code>from skimage import data, io
coins = data.coins()
io.imshow(coins)
</code></pre>
<p>But I see only the following string:</p>
<pre><code><matplotlib.image.AxesImage at 0x7f8c9c0cc6d8>
</code></pre>
<p>Can anyboby expl... | 2 | 2016-07-27T07:21:42Z | 38,606,757 | <p>Just add <code>matplotlib.pyplot.show()</code> after the <code>io.imshow(coins)</code> line. </p>
<pre><code>from skimage import data, io
from matplotlib import pyplot as plt
coins = data.coins()
io.imshow(coins)
plt.show()
</code></pre>
| 2 | 2016-07-27T07:41:10Z | [
"python",
"skimage"
] |
Pandas pivot table arrangement no aggregation | 38,606,393 | <p>I want to pivot a pandas dataframe without aggregation, and instead of presenting the pivot index column vertically I want to present it horizontally. I tried with <code>pd.pivot_table</code> but I'm not getting exactly what I wanted.</p>
<pre><code>data = {'year': [2011, 2011, 2012, 2013, 2013],
'A': [10, ... | 4 | 2016-07-27T07:22:41Z | 38,606,514 | <p>You can first create column for new index by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow"><code>cumcount</code></a>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack<... | 2 | 2016-07-27T07:28:11Z | [
"python",
"pandas",
"dataframe",
"pivot"
] |
Pandas pivot table arrangement no aggregation | 38,606,393 | <p>I want to pivot a pandas dataframe without aggregation, and instead of presenting the pivot index column vertically I want to present it horizontally. I tried with <code>pd.pivot_table</code> but I'm not getting exactly what I wanted.</p>
<pre><code>data = {'year': [2011, 2011, 2012, 2013, 2013],
'A': [10, ... | 4 | 2016-07-27T07:22:41Z | 38,606,794 | <p><code>groupby('year')</code> so I can <code>reset_index</code> to get index values of <code>0</code> and <code>1</code>. Then do a bunch of clean up.</p>
<pre><code>df.groupby('year')['A', 'B'] \
.apply(lambda df: df.reset_index(drop=True)) \
.unstack(0).swaplevel(0, 1, 1).sort_index(1)
</code></pre>
<p><... | 1 | 2016-07-27T07:42:50Z | [
"python",
"pandas",
"dataframe",
"pivot"
] |
How does python decorator work on this code? | 38,606,403 | <p>I'm trying to understand python decorator. I thought somehow I understood decorator until I wrote this code.</p>
<pre><code>def func():
def wrapper(x):
return x()
return wrapper
@func()
def b():
return sum
a = b([1,2,5])
print a # Result: 8 How?
e = b # pass b function to variable e
f = e(... | 1 | 2016-07-27T07:23:12Z | 38,606,644 | <p>You used <code>func</code> as a decorator <em>factory</em>, which produces a decorator that <em>called</em> the original <code>b()</code> to produce the decoration result. Here's what happens:</p>
<ul>
<li><code>@func()</code> executes <code>func()</code> <em>first</em>, then uses the return value as the decorator.... | 2 | 2016-07-27T07:35:15Z | [
"python",
"python-2.7",
"decorator",
"python-decorators"
] |
Fitting empirical distribution against a hyperbolic distribution using scipy.stats | 38,606,505 | <p>At the moment, I am fitting empirical distributions against theoretical ones as explained in <a href="http://stackoverflow.com/questions/6620471/fitting-empirical-distribution-to-theoretical-ones-with-scipy-python">Fitting empirical distribution to theoretical ones with Scipy (Python)?</a></p>
<p>Using the <a href... | 1 | 2016-07-27T07:27:40Z | 38,624,040 | <p>As your distribution is not in <code>scipy.stats</code> you can either add it to the package or try doing things "by hand".</p>
<p>For the former have a look at the <a href="https://github.com/scipy/scipy/tree/master/scipy/stats" rel="nofollow">source code</a> of the <code>scipy.stats</code> package - it might not ... | 2 | 2016-07-27T22:10:54Z | [
"python",
"scipy",
"statistics",
"statsmodels",
"scientific-computing"
] |
Measure current time in seconds? | 38,606,572 | <p>How can I take the current time in seconds in Python? I was using <code>calendar.timegm(time.gmtime())</code> but I'm not sure if this given value is in seconds?</p>
| 0 | 2016-07-27T07:31:41Z | 38,606,630 | <p>Try this : </p>
<pre><code>import time
print(round(time.time()))
</code></pre>
| 2 | 2016-07-27T07:34:29Z | [
"python",
"python-2.7",
"time",
"calendar"
] |
Measure current time in seconds? | 38,606,572 | <p>How can I take the current time in seconds in Python? I was using <code>calendar.timegm(time.gmtime())</code> but I'm not sure if this given value is in seconds?</p>
| 0 | 2016-07-27T07:31:41Z | 38,606,719 | <p>Use:</p>
<pre><code>from datetime import datetime
sec = int(datetime.utcnow().total_seconds()) % 86400
</code></pre>
| 0 | 2016-07-27T07:39:14Z | [
"python",
"python-2.7",
"time",
"calendar"
] |
Error in Calling python module from Java | 38,606,613 | <p>Java Code to call Python:</p>
<pre><code>//arguments to be passed to the script
String[] patchArguments = { patchFileDirectory,centralPatchStagePath,patchId,patchFileName, action };
//initialize the interpreter with properties and arguments
PythonInterpreter.initialize(System.getProperties(), System.getProperties()... | 0 | 2016-07-27T07:33:48Z | 38,610,674 | <p>In short: No. Or Maybe. Or Yes. <strong>But most relevant for you, in Jython, No.</strong></p>
<p>TLDR: Jython has its own implementation of subprocess</p>
<p>The details are a little sketchy on the python documentation, However the PEP has more details ( <a href="https://www.python.org/dev/peps/pep-0324/" rel="no... | 1 | 2016-07-27T10:41:40Z | [
"java",
"python",
"jython-2.7"
] |
Private Variables and Class-local References | 38,606,804 | <p>I'm not English mother language, and i learn python at <a href="https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references" rel="nofollow">https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references</a></p>
<p>At section 9.6 Private Variables and Cl... | 1 | 2016-07-27T07:43:27Z | 38,607,063 | <p>Imagine you have a class with a private member:</p>
<pre><code>class Foo:
__attr= 5
</code></pre>
<p>Inside the class, this attribute can be referenced as <code>__attr</code>:</p>
<pre><code>class Foo:
__attr= 5
print(__attr) # prints 5
</code></pre>
<p>But not outside of the class:</p>
<pre><code>p... | 2 | 2016-07-27T07:56:47Z | [
"python",
"class",
"reference",
"local",
"private"
] |
AttributeError: 'NoneType' object has no attribute 'browse' | 38,606,863 | <p>I am having trouble in getting data from res.company
Can someone tell me why this code gives me an error ?</p>
<pre><code> def refresh_calculation(self,cr,uid,ids, context=None):
company_pool = self.pool.get('res.company')
company_id = self.pool.get('res.company')._company_default_get(cr, uid, '... | 0 | 2016-07-27T07:46:30Z | 38,606,920 | <p><code>self.pool.get</code> is returning None for "res.company". If that's a dict, it doesn't have that key.</p>
| 3 | 2016-07-27T07:49:09Z | [
"python",
"openerp",
"openerp-7"
] |
AttributeError: 'NoneType' object has no attribute 'browse' | 38,606,863 | <p>I am having trouble in getting data from res.company
Can someone tell me why this code gives me an error ?</p>
<pre><code> def refresh_calculation(self,cr,uid,ids, context=None):
company_pool = self.pool.get('res.company')
company_id = self.pool.get('res.company')._company_default_get(cr, uid, '... | 0 | 2016-07-27T07:46:30Z | 38,606,957 | <p>Your <code>company_pool</code> parameter has <code>None</code> stored in it for some reason. To prevent this error, a simple if statement would suffice.</p>
<pre><code>if company_pool is not None:
# doSomething
else
print "You did not enter the parameter res.company"
</code></pre>
| 1 | 2016-07-27T07:50:50Z | [
"python",
"openerp",
"openerp-7"
] |
AttributeError: 'NoneType' object has no attribute 'browse' | 38,606,863 | <p>I am having trouble in getting data from res.company
Can someone tell me why this code gives me an error ?</p>
<pre><code> def refresh_calculation(self,cr,uid,ids, context=None):
company_pool = self.pool.get('res.company')
company_id = self.pool.get('res.company')._company_default_get(cr, uid, '... | 0 | 2016-07-27T07:46:30Z | 38,606,999 | <p><code>company_pool</code> returns the value <code>None</code>. Because <code>self.pool</code> does not have the key value 'res.company'. When <code>company_pool.browse(...)</code> is used -> <code>None.browse(...)</code> is called and this throws an error because <code>NoneType</code> does not have a browse attribut... | 2 | 2016-07-27T07:52:59Z | [
"python",
"openerp",
"openerp-7"
] |
Pandas histogram (counts) on grouped (by) values | 38,606,912 | <p>I have a <code>DataFrame</code> which looks like this:</p>
<pre><code>>>> df
type value
0 1 0.698791
1 3 0.228529
2 3 0.560907
3 1 0.982690
4 1 0.997881
5 1 0.301664
6 1 0.877495
7 2 0.561545
8 1 0.167920
9 1 0.928918
10 2 0.212339
11... | 2 | 2016-07-27T07:48:43Z | 38,607,474 | <p>is that what you want?</p>
<pre><code>In [98]: %paste
bins = np.linspace(0, 1.0, 11)
labels = list(range(1,11))
(df.assign(q=pd.cut(df.value, bins=bins, labels=labels, right=False))
.pivot_table(index='type', columns='q', aggfunc='size', fill_value=0)
)
## -- End pasted text --
Out[98]:
q 1 2 3 4 5 ... | 1 | 2016-07-27T08:16:16Z | [
"python",
"pandas",
"aggregate",
"histogram"
] |
Playing, Opening and Pausing VLC command line executed from Python scripts | 38,606,973 | <p>I am trying to create an small python app that syncs up 2 computers via tcp socket and when I send a command play or pause. Both scripts will/should execute a command line to pause or play or open vlc wit file. Both computers are MacOSX latest with a VLC installed within the past 3 weeks.</p>
<p>I have been readin... | 1 | 2016-07-27T07:51:41Z | 38,668,805 | <p>I suspect the best way to do this on MacOS would be to use the <a href="https://wiki.videolan.org/documentation:modules/rc/" rel="nofollow">VLC remote control interface</a>.</p>
<p>This allows you to control the behavior of a launched VLC instance using commands which you send to the process' stdin.</p>
<p>You cou... | 2 | 2016-07-29T23:24:09Z | [
"python",
"ipc",
"vlc"
] |
How to plot image none-inline in Pandas | 38,606,975 | <p>There are lots of posts telling you how to display your chart/image inline. Yet once you used the magical <code>%pylab inline</code>, you have can no longer make it display image in a new window. </p>
<p>Is ther a magical line like <code>%pylab none-inline</code> to again make pandas display graph in new window?</p... | 1 | 2016-07-27T07:51:44Z | 38,607,006 | <p><a href="https://ipython.org/ipython-doc/3/interactive/magics.html#magic-matplotlib" rel="nofollow">This</a> is what you're looking for:</p>
<pre><code>%matplotlib [backend]
</code></pre>
<p>when you specify <code>%matplotlib inline</code> you're opting to use Ipython's backend renderer. </p>
| 1 | 2016-07-27T07:53:26Z | [
"python",
"matplotlib",
"ipython",
"jupyter-notebook"
] |
Django pickle.dumps(model.query) hitting db | 38,606,989 | <p>I try to pickle django Query object to save it in Redis. </p>
<pre><code>materials = Material.objects.prefetch_related('tags_applied').prefetch_related('materialdata_set').prefetch_related('source')
materials_ids = MaterialData.objects.filter(tag_id__in=tags).values_list('material_id', flat=True)
materials = materi... | 1 | 2016-07-27T07:52:23Z | 38,607,723 | <p>Django query's are lazy query's, but let me explain what you have written:</p>
<pre><code>materials = Material.objects.prefetch_related('tags_applied'
).prefetch_related('materialdata_set').prefetch_related('source')
materials_ids = MaterialData.objects.filter(tag_id__in=tags).values_list('material_id', flat=... | 1 | 2016-07-27T08:29:41Z | [
"python",
"django"
] |
Simplest Way To Deploy Javascript Application On Linux | 38,607,079 | <p>I have an folder say 'mywebapp' on windows machines. This folder has index.html page, js directory with java script files and css directory with css files.</p>
<p>Now when i open this index.html into browser, the browser displays contents pretty well, as if i have deployed this application on server, which is not t... | 0 | 2016-07-27T07:57:15Z | 38,607,466 | <p>Most simplest way i can suggest it to download and copy tar.gz file from location:</p>
<p><a href="https://tomcat.apache.org/download-70.cgi" rel="nofollow">https://tomcat.apache.org/download-70.cgi</a></p>
<p>1 then gunzip and untar this downloaded file.</p>
<p>2 Go to conf/Catelina/localhost folder.</p>
<p>3 c... | 0 | 2016-07-27T08:16:02Z | [
"javascript",
"python",
"linux",
"web-deployment",
"putty"
] |
Accessing data frame and printing custom error messages | 38,607,202 | <p>I have this dictionary having <code>Error_ID</code> and <code>Error_Messages</code> mapping, and these error messages have <code>{}</code> so that they can have dynamic data while printing</p>
<pre><code>dict = {'101': 'Invalid table name {}', '102': 'Invalid pair {} and {}'}
</code></pre>
<p>I have this function ... | 1 | 2016-07-27T08:03:17Z | 38,607,409 | <p>You can use python's iterable unpacking feature to pass a variable number of arguments to <code>str.format</code>:</p>
<pre><code>def print_error(error_id,error_data):
if not isinstance(error_data, tuple): # if error_data isn't a tuple
error_data= (error_data,) # make it a tuple so we can unpack it
... | 2 | 2016-07-27T08:13:44Z | [
"python",
"dictionary",
"printing"
] |
Wrap quotes around many strings in Python | 38,607,346 | <pre><code>Afghanistan
Albania
Algeria
etc
</code></pre>
<p>I have a list of countries, as above, copied from a txt file. I would like to create a list called <code>countries</code> containing all of these entries, without having to go down the list one-by-one wrapping each entry in quotes and add commas.</p>
<p>How... | -2 | 2016-07-27T08:10:27Z | 38,607,441 | <p>You dont need to add quotes and commas to every entry, just wrap everithing in triple quotes and then split it.</p>
<pre><code>text = \
'''
Afghanistan
Albania
Algeria
'''
my_list = []
for line in text.strip().split('\n'):
my_list.append(line)
print my_list
['Afghanistan', 'Albania', 'Algeria']
</code></pre>
... | 1 | 2016-07-27T08:14:50Z | [
"python"
] |
Wrap quotes around many strings in Python | 38,607,346 | <pre><code>Afghanistan
Albania
Algeria
etc
</code></pre>
<p>I have a list of countries, as above, copied from a txt file. I would like to create a list called <code>countries</code> containing all of these entries, without having to go down the list one-by-one wrapping each entry in quotes and add commas.</p>
<p>How... | -2 | 2016-07-27T08:10:27Z | 38,607,489 | <p>Supposing your entry is <code>test.txt</code> and you want to output in <code>out.txt</code>:</p>
<pre><code>if __name__ == '__main__':
with open('test.txt', 'rb') as fr:
reader = fr.readlines()
with open('out.txt', 'wb') as fw:
for line in reader:
fw.write('\''+line.... | 0 | 2016-07-27T08:17:21Z | [
"python"
] |
Wrap quotes around many strings in Python | 38,607,346 | <pre><code>Afghanistan
Albania
Algeria
etc
</code></pre>
<p>I have a list of countries, as above, copied from a txt file. I would like to create a list called <code>countries</code> containing all of these entries, without having to go down the list one-by-one wrapping each entry in quotes and add commas.</p>
<p>How... | -2 | 2016-07-27T08:10:27Z | 38,607,492 | <p>Quotes and commas are for lists and strings specified as <em>literals</em> in code. You don't need that for data you are reading programmatically.</p>
<p>Just read the lines and strip off the tailing newlines.</p>
<pre><code>with open('countries.text') as src:
countries = [row.strip('\n') for row in src]
</cod... | 2 | 2016-07-27T08:17:32Z | [
"python"
] |
Can I extract comments of any page from https://www.rt.com/ using python3? | 38,607,502 | <p>I am writing a web crawler. I extracted heading and Main Discussion of the this <a href="https://www.rt.com/usa/353493-clinton-speech-affairs-silence/" rel="nofollow">link</a> but I am unable to find any one of the comment (Ctrl+u -> Ctrl+f . Comment Text). I think the comments are written in JavaScript. Can I extra... | 0 | 2016-07-27T08:18:01Z | 38,607,642 | <p>Yes, if it can be viewed with a web browser, you can extract it.</p>
<p>If you look at the source it is really an iframe that loads a piece of javascript, that then creates a new tag in the document with the source of that script tag loading bundle.js, which really contains the commenting software. This in turns t... | 1 | 2016-07-27T08:25:34Z | [
"javascript",
"python",
"beautifulsoup",
"web-crawler"
] |
Can I extract comments of any page from https://www.rt.com/ using python3? | 38,607,502 | <p>I am writing a web crawler. I extracted heading and Main Discussion of the this <a href="https://www.rt.com/usa/353493-clinton-speech-affairs-silence/" rel="nofollow">link</a> but I am unable to find any one of the comment (Ctrl+u -> Ctrl+f . Comment Text). I think the comments are written in JavaScript. Can I extra... | 0 | 2016-07-27T08:18:01Z | 38,614,486 | <p>RT are using a service from <a href="https://www.spot.im/" rel="nofollow">spot.im</a> for comments</p>
<p>you need to do make two POST requests, first <code>https://api.spot.im/me/network-token/spotim</code> to get a token, then <code>https://api.spot.im/conversation-read/spot/sp_6phY2k0C/post/353493/get</code> to ... | 0 | 2016-07-27T13:32:54Z | [
"javascript",
"python",
"beautifulsoup",
"web-crawler"
] |
Create 3D array from a 2D array by replicating/repeating along the first axis | 38,607,546 | <p>Suppose I have a <code>n à m</code> array, i.e.:</p>
<pre><code>array([[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.]])
</code></pre>
<p>And I what to generate a 3D array <code>k à n à m</code>, where all the arrays in the new axis are equal, i.e.: the same array but now <code>3 à 3 à 3</code... | 2 | 2016-07-27T08:20:49Z | 38,607,674 | <p>Introduce a new axis at the start with <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/arrays.indexing.html#numpy.newaxis" rel="nofollow"><code>None/np.newaxis</code></a> and replicate along it with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow"><code>np.repe... | 1 | 2016-07-27T08:26:58Z | [
"python",
"arrays",
"numpy"
] |
Create 3D array from a 2D array by replicating/repeating along the first axis | 38,607,546 | <p>Suppose I have a <code>n à m</code> array, i.e.:</p>
<pre><code>array([[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.]])
</code></pre>
<p>And I what to generate a 3D array <code>k à n à m</code>, where all the arrays in the new axis are equal, i.e.: the same array but now <code>3 à 3 à 3</code... | 2 | 2016-07-27T08:20:49Z | 38,607,907 | <p>if you have:</p>
<pre><code>a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
</code></pre>
<p>You can use a list comprehension to generate the duplicate array:</p>
<pre><code>b = [a for x in range(3)]
</code></pre>
<p>Then (for numpy):</p>
<pre><code>c = array(b)
</code></pre>
| 0 | 2016-07-27T08:39:12Z | [
"python",
"arrays",
"numpy"
] |
Create 3D array from a 2D array by replicating/repeating along the first axis | 38,607,546 | <p>Suppose I have a <code>n à m</code> array, i.e.:</p>
<pre><code>array([[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.]])
</code></pre>
<p>And I what to generate a 3D array <code>k à n à m</code>, where all the arrays in the new axis are equal, i.e.: the same array but now <code>3 à 3 à 3</code... | 2 | 2016-07-27T08:20:49Z | 38,618,809 | <p>One possibility would be to use default broadcasting to replicate your array:</p>
<pre><code>a = np.arange(1, 10).reshape(3,3)
n = 3
b = np.ones((n, 3, 3)) * a
</code></pre>
<p>Which results in the array you wanted:</p>
<pre><code>array([[[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.]],
... | 0 | 2016-07-27T16:43:02Z | [
"python",
"arrays",
"numpy"
] |
Delete columns based on repeat value in one row in numpy array | 38,607,586 | <p>I'm hoping to delete columns in my arrays that have repeat entries in row 1 as shown below (row 1 has repeats of values 1 & 2.5, so one of each of those values have been been deleted, together with the column each deleted value lies within).</p>
<pre><code>initial_array =
row 0 [[ 1, 1, 1, 1, 1,... | 3 | 2016-07-27T08:22:54Z | 38,607,962 | <p>You can find the indices of wanted columns using <code>unique</code>:</p>
<pre><code>>>> indices = np.sort(np.unique(A[1], return_index=True)[1])
</code></pre>
<p>Then use a simple indexing to get the desire columns:</p>
<pre><code>>>> A[:,indices]
array([[ 1. , 1. , 1. , 1. , 1. ,... | 1 | 2016-07-27T08:41:22Z | [
"python",
"arrays",
"numpy"
] |
Delete columns based on repeat value in one row in numpy array | 38,607,586 | <p>I'm hoping to delete columns in my arrays that have repeat entries in row 1 as shown below (row 1 has repeats of values 1 & 2.5, so one of each of those values have been been deleted, together with the column each deleted value lies within).</p>
<pre><code>initial_array =
row 0 [[ 1, 1, 1, 1, 1,... | 3 | 2016-07-27T08:22:54Z | 38,608,165 | <p>You can use the optional arguments that come with <code>np.unique</code> and then use <code>np.bincount</code> to use the last row as weights to get the final averaged output, like so -</p>
<pre><code>_,unqID,tag,C = np.unique(arr[1],return_index=1,return_inverse=1,return_counts=1)
out = arr[:,unqID]
out[-1] = np.b... | 2 | 2016-07-27T08:50:52Z | [
"python",
"arrays",
"numpy"
] |
Delete columns based on repeat value in one row in numpy array | 38,607,586 | <p>I'm hoping to delete columns in my arrays that have repeat entries in row 1 as shown below (row 1 has repeats of values 1 & 2.5, so one of each of those values have been been deleted, together with the column each deleted value lies within).</p>
<pre><code>initial_array =
row 0 [[ 1, 1, 1, 1, 1,... | 3 | 2016-07-27T08:22:54Z | 38,608,790 | <p>This is a typical grouping problem, which can be solve elegantly and efficiently using the <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author):</p>
<pre><code>import numpy_indexed as npi
unique, final_array = npi.group_by(initial_... | 0 | 2016-07-27T09:19:36Z | [
"python",
"arrays",
"numpy"
] |
Part of Data get lost on adding to session and commiting flask | 38,607,812 | <p>The model is </p>
<pre><code>class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
artistname = db.Column(db.String(64))
photourl = db.Column(db.String(1000))
contactInfo = db.Column(db.String(20))
description = db.Column(db.String(500))
date = db.Column(db.Date)
def __repr_... | 0 | 2016-07-27T08:34:17Z | 38,636,970 | <p>Judging by the size of your photourl string, you want to save several image filenames inside a string separated by an asterisk *. A better alternative would be storing the filenames in a JSON array with each filename as a string.</p>
<pre><code>class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
... | 1 | 2016-07-28T12:53:04Z | [
"python",
"mysql",
"session",
"flask",
"flask-sqlalchemy"
] |
Testing stepper motor with python code with easydriver | 38,607,901 | <p>i am having some problems with my python code on my raspberry pi to move my stepper motor. </p>
<p>I am new to python language and hope if i could get help on moving my stepper motor.</p>
<p>I have attach a photo of my setup
<a href="http://i.stack.imgur.com/0hgFZ.jpg" rel="nofollow"><img src="http://i.stack.imgur... | 3 | 2016-07-27T08:39:02Z | 38,608,814 | <p>You need to define <code>set_stepper</code>, <code>set_cw</code> and <code>set_anticw</code> as functions and not variables. The way it is working now is that you initially define the two GPIO outputs to be false, and nothing happens in while loop.</p>
<pre><code>def set_stepper():
gpio.output(14, False)
def s... | 0 | 2016-07-27T09:20:45Z | [
"python",
"python-2.7",
"gpio"
] |
Testing stepper motor with python code with easydriver | 38,607,901 | <p>i am having some problems with my python code on my raspberry pi to move my stepper motor. </p>
<p>I am new to python language and hope if i could get help on moving my stepper motor.</p>
<p>I have attach a photo of my setup
<a href="http://i.stack.imgur.com/0hgFZ.jpg" rel="nofollow"><img src="http://i.stack.imgur... | 3 | 2016-07-27T08:39:02Z | 38,805,187 | <p>Silly me! I check the datasheet of my motor and did a multi meter test.
i wired the A+ and A= wrongly to the easy driver board... Now it's working, my code works fine.</p>
| 0 | 2016-08-06T14:12:35Z | [
"python",
"python-2.7",
"gpio"
] |
How to split string into repeated substrings | 38,607,916 | <p>I have strings each of which is one or more copies of some string. For example:</p>
<pre><code>L = "hellohellohello"
M = "good"
N = "wherewhere"
O = "antant"
</code></pre>
<p>I would like to split such strings into a list so that each element just has the part that was repeated. For example:</p>
<pre><code>split... | 3 | 2016-07-27T08:39:33Z | 38,608,105 | <p>The approach i would use:</p>
<pre><code>import re
L = "hellohellohello"
N = "good"
N = "wherewhere"
cnt = 0
result = ''
for i in range(1,len(L)+1):
if cnt <= len(re.findall(L[0:i],L)):
cnt = len(re.findall(L[0:i],L))
result = re.findall(L[0:i],L)[0]
print(result)
</code></pre>
<p>Gives t... | 0 | 2016-07-27T08:48:42Z | [
"python"
] |
How to split string into repeated substrings | 38,607,916 | <p>I have strings each of which is one or more copies of some string. For example:</p>
<pre><code>L = "hellohellohello"
M = "good"
N = "wherewhere"
O = "antant"
</code></pre>
<p>I would like to split such strings into a list so that each element just has the part that was repeated. For example:</p>
<pre><code>split... | 3 | 2016-07-27T08:39:33Z | 38,608,219 | <p>Try this. Instead of cutting your list, it concentrates on finding the shortest pattern, then just creates a new list by repeating this pattern an appropriate number of times.</p>
<pre><code>def splitstring(s):
# searching the number of characters to split on
proposed_pattern = s[0]
for i, c in enumerat... | 1 | 2016-07-27T08:53:24Z | [
"python"
] |
How to split string into repeated substrings | 38,607,916 | <p>I have strings each of which is one or more copies of some string. For example:</p>
<pre><code>L = "hellohellohello"
M = "good"
N = "wherewhere"
O = "antant"
</code></pre>
<p>I would like to split such strings into a list so that each element just has the part that was repeated. For example:</p>
<pre><code>split... | 3 | 2016-07-27T08:39:33Z | 38,608,257 | <p>Using regex to find the repeating word, then simply creating a list of the appropriate length:</p>
<pre><code>def splitstring(string):
match= re.match(r'(.*?)(?:\1)*$', string)
word= match.group(1)
return [word] * (len(string)//len(word))
</code></pre>
| 4 | 2016-07-27T08:55:13Z | [
"python"
] |
How to split string into repeated substrings | 38,607,916 | <p>I have strings each of which is one or more copies of some string. For example:</p>
<pre><code>L = "hellohellohello"
M = "good"
N = "wherewhere"
O = "antant"
</code></pre>
<p>I would like to split such strings into a list so that each element just has the part that was repeated. For example:</p>
<pre><code>split... | 3 | 2016-07-27T08:39:33Z | 38,608,329 | <p>Assuming that the length of the repeated word is longer than 1 this would work:</p>
<pre><code>a = "hellohellohello"
def splitstring(string):
for number in range(1, len(string)):
if string[:number] == string[number:number+number]:
return string[:number]
#in case there is no repetition
... | 0 | 2016-07-27T08:58:41Z | [
"python"
] |
How to split string into repeated substrings | 38,607,916 | <p>I have strings each of which is one or more copies of some string. For example:</p>
<pre><code>L = "hellohellohello"
M = "good"
N = "wherewhere"
O = "antant"
</code></pre>
<p>I would like to split such strings into a list so that each element just has the part that was repeated. For example:</p>
<pre><code>split... | 3 | 2016-07-27T08:39:33Z | 38,609,264 | <pre><code>#_*_ coding:utf-8 _*_
import re
'''
refer to the code of Gábor Erds below
'''
N = "wherewhere"
cnt = 0
result = ''
countN = 0
showresult = []
for i in range(1,len(N)+1):
if cnt <= len(re.findall(N[0:i],N)):
cnt = len(re.findall(N[0:i],N))
result = re.findall(N[0:i],N)[0]
cou... | 0 | 2016-07-27T09:40:35Z | [
"python"
] |
Shell command works in shell, but not when when fired from Python subprocess | 38,608,121 | <p>I am trying to execute a shell command from a Python script.
I have tried the usual suspects, subprocess.call, Popen, os.system etc.</p>
<p>The command i am trying to execute is admittedly rather long (7k characters), since one of the parameters is a json string. From what I've read length should not be the issue h... | 1 | 2016-07-27T08:49:06Z | 38,740,554 | <p>Turns out i had a very slight error in the phantomjs script, that behaved differently depending on where it was executed.</p>
| 0 | 2016-08-03T10:08:09Z | [
"python",
"shell",
"phantomjs"
] |
Why metaclass __getattribute__ invoked here? | 38,608,223 | <p>Here is a code snippet retrieved from Python 2.7.12 documentation (<strong>3.4.12. Special method lookup for new-style classes¶</strong>):</p>
<blockquote>
<p>In addition to bypassing any instance attributes in the interest of
correctness, implicit special method lookup generally also bypasses
the <code>__ge... | 0 | 2016-07-27T08:53:28Z | 38,608,763 | <p>Quotation from the same documentation, 3.4.2.1. More attribute access for new-style classes:</p>
<blockquote>
<p><code>object.__getattribute__(self, name)</code></p>
<p>Called <strong>unconditionally</strong> to implement attribute accesses for
<strong>instances</strong> of the class. ...</p>
</blockquote>... | 1 | 2016-07-27T09:18:21Z | [
"python",
"python-2.7",
"class",
"attributes"
] |
Convert strings to variable references | 38,608,263 | <p>I have a list of strings:</p>
<pre><code>A = ['a', 'b', 'c', 'd']
</code></pre>
<p>I would like to have a list B of variable references:</p>
<pre><code>B = [a, b, c, d]
</code></pre>
<p>How can I do that?</p>
<p><strong>Edit1:</strong></p>
<p>I have </p>
<pre><code>df_wgt_dict["Freq"+vars_dict['varName'+str(I... | -7 | 2016-07-27T08:55:35Z | 38,608,499 | <pre><code>A = ['a', 'b', 'c', 'd']
B = []
for s in A:
temp_storage = exec('%s = %d' % (s, my_value))
B.append(temp_storage)
</code></pre>
<p>This will change your list A in list B with variables instead of strings</p>
| -1 | 2016-07-27T09:06:28Z | [
"python"
] |
Convert strings to variable references | 38,608,263 | <p>I have a list of strings:</p>
<pre><code>A = ['a', 'b', 'c', 'd']
</code></pre>
<p>I would like to have a list B of variable references:</p>
<pre><code>B = [a, b, c, d]
</code></pre>
<p>How can I do that?</p>
<p><strong>Edit1:</strong></p>
<p>I have </p>
<pre><code>df_wgt_dict["Freq"+vars_dict['varName'+str(I... | -7 | 2016-07-27T08:55:35Z | 38,608,504 | <p>You can't do this directly. However, if you want to perform some operation with these variables, you can still use the keyword <a href="https://docs.python.org/3/library/functions.html#exec" rel="nofollow"><code>exec</code></a> or the function <a href="https://docs.python.org/2/library/functions.html#eval" rel="nofo... | -1 | 2016-07-27T09:06:42Z | [
"python"
] |
Create an if-else condition column in dask dataframe | 38,608,446 | <p>I need to create a column which is based on some condition on dask dataframe. In pandas it is fairly straightforward:</p>
<pre><code>ddf['TEST_VAR'] = ['THIS' if x == 200607 else
'NOT THIS' if x == 200608 else
'THAT' if x == 200609 else 'NONE'
for x in ddf['shop_week']... | 3 | 2016-07-27T09:03:54Z | 38,609,010 | <p>You could just use:</p>
<pre><code>f = lambda x: 'THIS' if x == 200607 else 'NOT THIS' if x == 200608 else 'THAT' if x == 200609 else 'NONE'
</code></pre>
<p>And then:</p>
<pre><code>ddf1 = ddf.assign(col1 = list(ddf.shop_week.apply(f).compute()))
</code></pre>
<p>Unfortunately I don't have an answer to the seco... | 1 | 2016-07-27T09:29:39Z | [
"python",
"pandas",
"dask"
] |
Create an if-else condition column in dask dataframe | 38,608,446 | <p>I need to create a column which is based on some condition on dask dataframe. In pandas it is fairly straightforward:</p>
<pre><code>ddf['TEST_VAR'] = ['THIS' if x == 200607 else
'NOT THIS' if x == 200608 else
'THAT' if x == 200609 else 'NONE'
for x in ddf['shop_week']... | 3 | 2016-07-27T09:03:54Z | 38,613,444 | <p>Answers:</p>
<ol>
<li><p>What you're doing now is almost ok. You don't need to call <code>compute</code> until you're ready for your final answer.</p>
<pre><code># ddf1 = ddf.assign(col1 = list(ddf.shop_week.apply(f).compute()))
ddf1 = ddf.assign(col1 = ddf.shop_week.apply(f))
</code></pre>
<p>For some cases <co... | 2 | 2016-07-27T12:48:02Z | [
"python",
"pandas",
"dask"
] |
Pandas repeated values | 38,608,453 | <p>Is there a more idiomatic way of doing this in Pandas?</p>
<p>I want to set-up a column that repeats the integers 1 to 48, for an index of length 2000:</p>
<pre><code>df = pd.DataFrame(np.zeros((2000, 1)), columns=['HH'])
h = 1
for i in range(0,2000) :
df.loc[i,'HH'] = h
if h >=48 : h =1
else : h ... | 0 | 2016-07-27T09:04:05Z | 38,608,547 | <p>Here is more direct and faster way:</p>
<pre><code>pd.DataFrame(np.tile(np.arange(1, 49), 2000 // 48 + 1)[:2000], columns=['HH'])
</code></pre>
<hr>
<p>The detailed step:</p>
<ol>
<li><code>np.arange(1, 49)</code> creates an array from <code>1</code> to <code>48</code> (included)</li>
</ol>
<pre><code>>>... | 3 | 2016-07-27T09:08:40Z | [
"python",
"pandas",
"dataframe"
] |
Pandas repeated values | 38,608,453 | <p>Is there a more idiomatic way of doing this in Pandas?</p>
<p>I want to set-up a column that repeats the integers 1 to 48, for an index of length 2000:</p>
<pre><code>df = pd.DataFrame(np.zeros((2000, 1)), columns=['HH'])
h = 1
for i in range(0,2000) :
df.loc[i,'HH'] = h
if h >=48 : h =1
else : h ... | 0 | 2016-07-27T09:04:05Z | 38,609,037 | <pre><code>df = pd.DataFrame({'HH':np.append(np.tile(range(1,49),int(2000/48)), range(1,np.mod(2000,48)+1))})
</code></pre>
<p>That is, appending 2 arrays:</p>
<p>(1) <code>np.tile(range(1,49),int(2000/48))</code></p>
<pre><code>len(np.tile(range(1,49),int(2000/48)))
1968
</code></pre>
<p>(2) <code>range(1,np.mod(2... | 0 | 2016-07-27T09:30:53Z | [
"python",
"pandas",
"dataframe"
] |
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() | 38,608,498 | <p>I am new to pandas.
I am trying to assign a negative sign to one of the column in data frame with below code. but while i do that i get error as below.
I tried with below code</p>
<pre><code>INTERNAL_DEBIT = InternalTxns[InternalTxns['type'].isin(['INTERNAL_DEBIT','INTERNAL'])]
new_amnt = (INTERNAL_DEBIT['amount'... | 1 | 2016-07-27T09:06:27Z | 38,610,365 | <p>You can use the original mask you used from <code>isin</code> with <code>loc</code> to only overwrite those values:</p>
<pre><code>InternalTxns.loc[InternalTxns["type"].isin(["INTERNAL_DEBIT","INTERNAL_TRANSFERââââ_REVERSAL"]),'amount'] *= -1
</code></pre>
| 0 | 2016-07-27T10:27:16Z | [
"python",
"pandas",
"dataframe"
] |
How to split a column into multiple columns with the index of the string with pandas? | 38,608,563 | <p>I have data frame, it looks like:</p>
<pre><code>df = pd.DataFrame({"a":["sea001", "seac002"]})
print(df)
a
0 sea001
1 seac002
</code></pre>
<p>I want to split the a column into two columns, the first three characters in column "b", the rest in column "c"</p>
<pre><code> a b c
0 sea0... | 1 | 2016-07-27T09:09:26Z | 38,608,614 | <p>You can use <code>str</code> with slicing semantics to do this:</p>
<pre><code>In [102]:
df['b'], df['c'] = df['a'].str[:3], df['a'].str[3:]
df
Out[102]:
a b c
0 sea001 sea 001
1 seac002 sea c002
</code></pre>
| 1 | 2016-07-27T09:11:32Z | [
"python",
"pandas"
] |
How to split a column into multiple columns with the index of the string with pandas? | 38,608,563 | <p>I have data frame, it looks like:</p>
<pre><code>df = pd.DataFrame({"a":["sea001", "seac002"]})
print(df)
a
0 sea001
1 seac002
</code></pre>
<p>I want to split the a column into two columns, the first three characters in column "b", the rest in column "c"</p>
<pre><code> a b c
0 sea0... | 1 | 2016-07-27T09:09:26Z | 38,608,657 | <p>try <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow">.str.extract()</a> method:</p>
<pre><code>In [104]: df[['b','c']] = df.a.str.extract(r'(.{3})(.*)', expand=True)
In [105]: df
Out[105]:
a b c
0 sea001 sea 001
1 seac002 sea c002... | 1 | 2016-07-27T09:13:25Z | [
"python",
"pandas"
] |
Error with pip install scikit-image | 38,608,698 | <p>I am using Windows 8.1 64 bit and Python 2.7. While trying to install <code>scikit-image</code> from the shell </p>
<p><code>pip install scikit-image</code></p>
<p>I have encountered this error:</p>
<p><code>Command "python setup.py egg_info" failed with error code 1 in c:\users\france~1\appdata\local\temp\pip-bu... | 2 | 2016-07-27T09:15:16Z | 38,618,044 | <p>install numpy</p>
<pre><code>pip install numpy
</code></pre>
<p>If you face installation issues for numpy, get the pre-built windows installers from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a> for your python version (python version is differen... | 4 | 2016-07-27T16:02:11Z | [
"python",
"installation",
"pip",
"scikit-image"
] |
Linear interpolation of the 4D array in Python/NumPy | 38,608,881 | <p>I have a question about the linear interpolation in python\numpy.
I have a 4D array with the data (all data in binary files) that arrange in this way:
t- time (lets say each hour for a month = 720)
Z-levels (lets say Z'=7)
Y-data1 (one for each t and Z)
X-data2 (one for each t and Z)</p>
<p>So, I want to obtain a ... | 1 | 2016-07-27T09:23:41Z | 38,609,288 | <p>You can create different interpolation formulas for different combinations of z' and t. </p>
<p>For example, for <code>z=7</code>, and a specific value of <code>t</code>, you can create an interpolation formula:</p>
<pre><code>formula = scipy.interp1d(x,y)
</code></pre>
<p>Another one for say <code>z=25</code> an... | 0 | 2016-07-27T09:41:34Z | [
"python",
"arrays",
"numpy",
"4d"
] |
Linear interpolation of the 4D array in Python/NumPy | 38,608,881 | <p>I have a question about the linear interpolation in python\numpy.
I have a 4D array with the data (all data in binary files) that arrange in this way:
t- time (lets say each hour for a month = 720)
Z-levels (lets say Z'=7)
Y-data1 (one for each t and Z)
X-data2 (one for each t and Z)</p>
<p>So, I want to obtain a ... | 1 | 2016-07-27T09:23:41Z | 38,610,635 | <p>In 2D for instance there is <a href="https://en.wikipedia.org/wiki/Bilinear_interpolation" rel="nofollow">bilinear interpolation</a> - with an example on the unit square with the z-values 0, 1, 1 and 0.5 as indicated. Interpolated values in between represented by colour:</p>
<p><a href="http://i.stack.imgur.com/NVW... | 0 | 2016-07-27T10:39:51Z | [
"python",
"arrays",
"numpy",
"4d"
] |
Test the equality of multiple arguments with Numpy | 38,608,956 | <p>I would like to test the equality of multiple args (i.e. it should return <code>True</code> if all args are equal and <code>False</code> if at least one argument differs).</p>
<p>As <code>numpy.equal</code> can only handle two arguments, I would have tried reduce but it, obviously, fails:</p>
<pre><code>reduce(np.... | 2 | 2016-07-27T09:26:52Z | 38,609,133 | <p>You can use <code>np.unique</code> to check if the length of unique items within your array is 1:</p>
<pre><code>np.unique(array).size == 1
</code></pre>
<p>Or <code>np.all()</code> in order to check if all of the items are equal with one of your items (for example the first one):</p>
<pre><code>np.all(array == a... | 2 | 2016-07-27T09:34:39Z | [
"python",
"numpy"
] |
Test the equality of multiple arguments with Numpy | 38,608,956 | <p>I would like to test the equality of multiple args (i.e. it should return <code>True</code> if all args are equal and <code>False</code> if at least one argument differs).</p>
<p>As <code>numpy.equal</code> can only handle two arguments, I would have tried reduce but it, obviously, fails:</p>
<pre><code>reduce(np.... | 2 | 2016-07-27T09:26:52Z | 38,609,892 | <p>The <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package has a builtin function for this. Note that it also works on multidimensional arrays, ie you can use it to check if a stack of images are all identical, for instance.</p>
<pre><code>import numpy_indexed as... | 1 | 2016-07-27T10:06:58Z | [
"python",
"numpy"
] |
Test the equality of multiple arguments with Numpy | 38,608,956 | <p>I would like to test the equality of multiple args (i.e. it should return <code>True</code> if all args are equal and <code>False</code> if at least one argument differs).</p>
<p>As <code>numpy.equal</code> can only handle two arguments, I would have tried reduce but it, obviously, fails:</p>
<pre><code>reduce(np.... | 2 | 2016-07-27T09:26:52Z | 38,610,186 | <p>If your args are floating point values the equality test can produce weird results due to round off errors. In this case you should use a more robust approach, for example <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html" rel="nofollow"><code>numpy.allclose</code></a>:</p>
<pre><code... | 1 | 2016-07-27T10:19:47Z | [
"python",
"numpy"
] |
Iterating over Index in Python | 38,608,970 | <p>I am trying to write a for loop to iterate through my index and only keep the ones that have duplicates.</p>
<p>My current dataframe is two merged together</p>
<pre><code> 0.0102700 0.0308099 0.0616199 0.123240 \
5000000000010 4.330760e-05 4.442720e-05 9.232970e-05 1.994190e-0... | -1 | 2016-07-27T09:27:46Z | 38,609,000 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.duplicated.html" rel="nofollow"><code>Index.duplicated</code></a> with parameter <code>keep=False</code>:</p>
<pre><code>print (df.index[df.index.duplicated(keep=False)])
Int64Index([1000, 1000, 1002, 1002], dtype='int64')
for i in df... | 0 | 2016-07-27T09:29:22Z | [
"python",
"loops",
"pandas",
"indexing",
"iteration"
] |
Iterating over Index in Python | 38,608,970 | <p>I am trying to write a for loop to iterate through my index and only keep the ones that have duplicates.</p>
<p>My current dataframe is two merged together</p>
<pre><code> 0.0102700 0.0308099 0.0616199 0.123240 \
5000000000010 4.330760e-05 4.442720e-05 9.232970e-05 1.994190e-0... | -1 | 2016-07-27T09:27:46Z | 38,609,320 | <pre><code>li = [1000,1000,1001,1002,1002]
for i in li:
temp = i
count = 0
for j in li:
if j is temp:
count +=1
if count > 1:
print i
</code></pre>
<p>This solves your requirement?</p>
| 0 | 2016-07-27T09:42:57Z | [
"python",
"loops",
"pandas",
"indexing",
"iteration"
] |
Iterating over Index in Python | 38,608,970 | <p>I am trying to write a for loop to iterate through my index and only keep the ones that have duplicates.</p>
<p>My current dataframe is two merged together</p>
<pre><code> 0.0102700 0.0308099 0.0616199 0.123240 \
5000000000010 4.330760e-05 4.442720e-05 9.232970e-05 1.994190e-0... | -1 | 2016-07-27T09:27:46Z | 38,609,607 | <p>try some code first before asking:
there are lot of duplicate questions </p>
<pre><code>a = [1000,1000,1001,1002,1002]
c = [x for x in a if a.count(x) > 1]
print c
</code></pre>
| 0 | 2016-07-27T09:55:11Z | [
"python",
"loops",
"pandas",
"indexing",
"iteration"
] |
Runtime Error: Unknown MATLAB location when using a wrapper in python | 38,609,112 | <p>I am trying to use a Matlab wrapper for my code in the ipython spyder IDE.
I get the following error when I run the code:</p>
<pre><code>raise RuntimeError("Unknown MATLAB location: try to initialize MatlabSession with matlab_root set properly.")
RuntimeError: Unknown MATLAB location: try to initialize MatlabSess... | 0 | 2016-07-27T09:33:46Z | 38,610,531 | <p>Basically matlab_root is a variable inside <code>MatlabSession</code>, that points to the folder where MATLAB is installed. What is happening here is that probably matlab_root has a default value that is not where your MATLAB is installed. you need to change/set this variable to the folder where MATLAB is installed.... | 0 | 2016-07-27T10:34:42Z | [
"python",
"matlab",
"ipython",
"spyder"
] |
Adding Digits in a Number (Need Code Explanation) | 38,609,125 | <p>I came across this code segment elsewhere. It simply adds all the digits in a given number:</p>
<pre><code>def sumDigits(n):
sum = 0
while n > 0:
sum += n % 10
n //= 10
return sum
</code></pre>
<p>Problem is, I don't get the logic behind it at all. In particular, I don't get exactly ... | 0 | 2016-07-27T09:34:18Z | 38,609,229 | <p>You should understand 2 things:</p>
<ol>
<li><code>n % 10</code> give you the rightmost digit of a number. For example: <code>123 % 10 = 3</code>. More about <code>%</code> operator <a class='doc-link' href="http://stackoverflow.com/documentation/python/298/simple-math/12336/modulus#t=201607270940153745501">here</a... | 9 | 2016-07-27T09:39:02Z | [
"python",
"algorithm",
"sum-of-digits"
] |
Uploading file with python to bottle server | 38,609,146 | <p>I've got two computers in the same network and I'm trying to pass a file from one to the other with python (in the context of a bigger project). </p>
<p>On the <strong>server side</strong> I've got the following bottle script:</p>
<pre class="lang-py prettyprint-override"><code>import bottle
import json
@bottle.... | 0 | 2016-07-27T09:35:24Z | 38,611,520 | <p>So... The thing is pretty silly... Just leaving the answer here in case someone else stomps with this stupid mistake... </p>
<p>The <strong>bottle.route</strong> and the <strong>requests.url</strong> need to match <em>exactly</em>. In may case, the <strong>route</strong> was <code>api</code> while the <strong>url<... | 0 | 2016-07-27T11:19:53Z | [
"python",
"python-2.7",
"file-upload",
"request",
"bottle"
] |
impossible to resample date with python | 38,609,254 | <p>I have a dataframe called df1 : </p>
<pre><code>df1 = pd.read_csv('C:/Users/Demonstrator/Desktop/equipement3.csv',delimiter=';', usecols = ['TIMESTAMP','ACT_TIME_AERATEUR_1_F1'])
</code></pre>
<blockquote>
<p>TIMESTAMP;ACT_TIME_AERATEUR_1_F1</p>
<p>2015-07-31 23:00:00;90 </p>
<p>2015-07-31 23:10:00;0 <... | 1 | 2016-07-27T09:39:58Z | 38,611,327 | <p>You can add parameter <code>parse_dates</code> and <code>index_col</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a> and then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="n... | 0 | 2016-07-27T11:11:39Z | [
"python",
"date",
"pandas",
"resampling"
] |
Conversion array with float values in the array with the values of str | 38,609,263 | <p>There is an array with the values of <code>float</code> which was prepared as follows:</p>
<pre><code>import numpy as np
result256 = np.linspace(0, 2, 20)
</code></pre>
<p>It is necessary to get an array of <code>result 256</code> with values <code>str</code>.</p>
| 0 | 2016-07-27T09:40:26Z | 38,610,788 | <p>Do you mean like this?</p>
<pre><code>result256str = []
for num in result256: result256str.append(str(num))
</code></pre>
| 0 | 2016-07-27T10:46:44Z | [
"python",
"numpy"
] |
Pandas Dataframe to Seaborn Grouped Barchart | 38,609,339 | <p>I have the following dataframe which I have obtained from a larger dataframe which lists the worst 10 "Benchmark Returns" and their corresponding portfolio returns and dates:</p>
<p><a href="http://i.stack.imgur.com/XGgE8.png" rel="nofollow"><img src="http://i.stack.imgur.com/XGgE8.png" alt="enter image description... | 1 | 2016-07-27T09:43:45Z | 38,611,976 | <p>Please look if this is what you wanted to see.</p>
<p>The trick is to transform the pandas <code>df</code> from wide to long format</p>
<p><strong>Step 1: Prepare data</strong></p>
<pre><code>import seaborn as sns
np.random.seed(123)
index = np.random.randint(1,100,10)
x1 = pd.date_range('2000-01-01','2015-01-0... | 2 | 2016-07-27T11:42:33Z | [
"python",
"pandas",
"visualization",
"seaborn"
] |
Gmail API python implementation | 38,609,383 | <p>I'm implementing a bot where I can read emails and I'm following the <code>Gmail API</code>. I can read all the labels and I have stored it in the list. I am not able to read the messages inside the label</p>
<pre><code>credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discover... | 1 | 2016-07-27T09:45:04Z | 38,609,479 | <p>I think this is what you are supposed to do:</p>
<pre><code> results = service.users().labels().list(userId='me').execute()
</code></pre>
<p>From the official documentation:
<a href="https://developers.google.com/gmail/api/quickstart/python" rel="nofollow">https://developers.google.com/gmail/api/quickstart/python<... | 1 | 2016-07-27T09:48:50Z | [
"python",
"gmail-api"
] |
Gmail API python implementation | 38,609,383 | <p>I'm implementing a bot where I can read emails and I'm following the <code>Gmail API</code>. I can read all the labels and I have stored it in the list. I am not able to read the messages inside the label</p>
<pre><code>credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discover... | 1 | 2016-07-27T09:45:04Z | 38,792,583 | <p>The mistake here is that you are using the 'get' method for labels rather than for messages. This get method is used to find out information about a label, such as the number of unread messages inside that label.</p>
<p>You can see on the line below you are asking for the .labels</p>
<pre><code>results = service.u... | 0 | 2016-08-05T15:13:18Z | [
"python",
"gmail-api"
] |
Regex not working as required | 38,609,390 | <p>Here is my HTML code:</p>
<pre><code><ul class="hide menuSearchType">
<li><a href="../../dynamic/city_select.aspx">Search by city</a></li>
<li><a href="../../searchbyphone.aspx">Search by phone</a></li>
<li><a href="../searchbyaddress.aspx"&... | -3 | 2016-07-27T09:45:37Z | 38,609,864 | <p>Try using the following:</p>
<pre><code>linkList1 = re.findall(re.compile(u'(?<=href=")../\w.*?(?=")'), str(html))
</code></pre>
<p>That guarantees that there has to be a word character after the slash.</p>
| 1 | 2016-07-27T10:05:55Z | [
"python",
"html",
"regex"
] |
Regex not working as required | 38,609,390 | <p>Here is my HTML code:</p>
<pre><code><ul class="hide menuSearchType">
<li><a href="../../dynamic/city_select.aspx">Search by city</a></li>
<li><a href="../../searchbyphone.aspx">Search by phone</a></li>
<li><a href="../searchbyaddress.aspx"&... | -3 | 2016-07-27T09:45:37Z | 38,610,024 | <p>You can replace string using regex, </p>
<pre><code>output = re.sub(r'(?is)(href="../)([^.])','http://www.phonebook.com.pk/'+r'\2',str(html))
</code></pre>
| 1 | 2016-07-27T10:12:56Z | [
"python",
"html",
"regex"
] |
Regex not working as required | 38,609,390 | <p>Here is my HTML code:</p>
<pre><code><ul class="hide menuSearchType">
<li><a href="../../dynamic/city_select.aspx">Search by city</a></li>
<li><a href="../../searchbyphone.aspx">Search by phone</a></li>
<li><a href="../searchbyaddress.aspx"&... | -3 | 2016-07-27T09:45:37Z | 38,611,137 | <p>By Using BeautifulSoup as requested :</p>
<pre><code>from bs4 import Beautifulsoup
soup = BeautifulSoup(html)
all = soup.select('li')
for i in all:
try:
output = re.sub(r'(?is)(href="../)([^.])','http://www.phonebook.com.pk/'+r'\2',str(i))
except:
output = i
print(output)
</code></pre>
| 2 | 2016-07-27T11:02:03Z | [
"python",
"html",
"regex"
] |
Theano partial derivative over element in symbolic vector | 38,609,421 | <p>I recently hit some performance bottlenecks with symbolic matrix derivatives in Sympy (specifically, the single line of code evaluating symbolic matrices via substitution using lambdas was taking ~90% of the program's runtime), so I decided to give Theano a go.</p>
<p>Its previous application was evaluating the par... | 0 | 2016-07-27T09:46:54Z | 38,614,977 | <p>When using theano, all variables should be defined as theano tensors (or shared variables); otherwise, the variable does not become part of the computational graph. In <code>f = data/l_scales_sym</code> the variable <code>data</code> is a numpy array. Try to also define it as a a tensor, it should work. </p>
| 1 | 2016-07-27T13:54:04Z | [
"python",
"theano",
"derivative"
] |
compare an array with two other arrays in python | 38,609,502 | <p>i have a set of 3 arrays which i would compare to eachother.
array a contain a set of values and the values of array b and c should be partly the same.</p>
<p>it is so that if let say <code>a[0] == b[0]</code> than is <code>c[0]</code> always a wrong value</p>
<p>for better explanation i try to show what i mean.</... | 2 | 2016-07-27T09:50:02Z | 38,609,576 | <p>You can try this way instead: </p>
<pre><code>(a==b).all() or (a==c).all()
</code></pre>
| 0 | 2016-07-27T09:53:51Z | [
"python",
"arrays",
"python-3.x",
"numpy"
] |
compare an array with two other arrays in python | 38,609,502 | <p>i have a set of 3 arrays which i would compare to eachother.
array a contain a set of values and the values of array b and c should be partly the same.</p>
<p>it is so that if let say <code>a[0] == b[0]</code> than is <code>c[0]</code> always a wrong value</p>
<p>for better explanation i try to show what i mean.</... | 2 | 2016-07-27T09:50:02Z | 38,609,626 | <p>You want a logical <code>OR</code>:</p>
<pre><code>np.logical_or(a==b, a==c).all()
</code></pre>
| 2 | 2016-07-27T09:55:54Z | [
"python",
"arrays",
"python-3.x",
"numpy"
] |
compare an array with two other arrays in python | 38,609,502 | <p>i have a set of 3 arrays which i would compare to eachother.
array a contain a set of values and the values of array b and c should be partly the same.</p>
<p>it is so that if let say <code>a[0] == b[0]</code> than is <code>c[0]</code> always a wrong value</p>
<p>for better explanation i try to show what i mean.</... | 2 | 2016-07-27T09:50:02Z | 38,609,750 | <p>From your example and explanation, I guess what you want is:</p>
<blockquote>
<p>For each position, <strong>exactly</strong> one of <code>b</code> or <code>c</code> has the same value as <code>a</code></p>
</blockquote>
<p>If that's the case, that can be done with the following code:</p>
<pre><code>def is_exc... | 1 | 2016-07-27T10:00:18Z | [
"python",
"arrays",
"python-3.x",
"numpy"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.