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 |
|---|---|---|---|---|---|---|---|---|---|
Converting a list of list into a dictionary based on common values in python | 38,900,637 | <p>I have a list of list in python as follows:</p>
<pre><code>a = [['John', 24, 'teacher'],['Mary',23,'clerk'],['Vinny', 21, 'teacher'], ['Laura',32, 'clerk']]
</code></pre>
<p>The idea is to create a dict on the basis of their occupation as follows:</p>
<pre><code>b = {'teacher': {'John_24': 'true', 'Vinny_21' 'tru... | 1 | 2016-08-11T15:32:51Z | 38,900,774 | <p>As others have said, you can just use a list instead of a dictionary.</p>
<p>Here is one way to implement this:</p>
<pre><code>a = [
['John', 24, 'teacher'],
['Mary', 23, 'clerk'],
['Vinny', 21, 'teacher'],
['Laura', 32, 'clerk'],
]
b = {}
for name, age, occupation in a:
b.setdefault(occupatio... | 1 | 2016-08-11T15:39:32Z | [
"python",
"list",
"dictionary"
] |
re.sub doesn't modify string in python | 38,900,731 | <p>I have a small python program where I expect the word "verified" (regardless if written in upper, lower case or a mix of upper and lower case). To be reset to "Verified". How do I need to rewrite the code below? </p>
<pre><code> import re
text="verified, vERIFIED, VERIFIED"
text=re.sub(r'\verified', 'Verified', t... | 0 | 2016-08-11T15:37:31Z | 38,900,952 | <p>Simply remove the backslash before the <code>v</code></p>
<pre><code>import re
text="verified, vERIFIED, VERIFIED"
text=re.sub(r'verified', 'Verified', text, flags=re.IGNORECASE)
print text
</code></pre>
| 1 | 2016-08-11T15:48:27Z | [
"python"
] |
Python3 Cannot import function from my own module | 38,900,788 | <p>I have browsed the site for a while and the only occasions people had this error happening were in circular imports which I don't have as far as I understand what circular imports are? My imports are transitive though.</p>
<p>I have 3 files in the same folder:</p>
<pre><code>packer.py
parser.py
statistics.py
</cod... | 0 | 2016-08-11T15:40:13Z | 38,900,871 | <p>ImportErrors may happen if there are duplicate module names. Try naming your <code>parser.py</code> something else, since it is likely conflicting with Python's built-in <a href="https://docs.python.org/2/library/parser.html" rel="nofollow"><code>parser</code></a> module.</p>
| 2 | 2016-08-11T15:44:04Z | [
"python",
"python-3.x"
] |
URLconf error on Django Heroku deployment | 38,900,803 | <p>I am getting the following error on my Django Heroku deployment, not sure what is causing it?:</p>
<pre><code>Page not found (404)
Request Method: GET
Request URL: https://blogpod.herokuapp.com/
Using the URLconf defined in blogpodapi.urls, Django tried these URL patterns, in this order:
^admin/
^api/
^favicon\.... | 0 | 2016-08-11T15:40:49Z | 38,908,446 | <p>To define the root url you have to add this pattern '^$':</p>
<pre><code>url(r'^$', view)
</code></pre>
<p>Then it matches to your case <a href="https://blogpod.herokuapp.com/" rel="nofollow">https://blogpod.herokuapp.com/</a></p>
| 1 | 2016-08-12T01:23:04Z | [
"python",
"django",
"heroku"
] |
How many iterations a needed to train tensorflow with the entire MNIST data set (60000 images)? | 38,900,885 | <p>The MNIST set consists of 60,000 images for training set. While training my Tensorflow, I want to run the train step to train the model with the entire training set. The deep learning example on the Tensorflow website uses 20,000 iterations with a batch size of 50 (totaling to 1,000,000 batches). When I try more tha... | 0 | 2016-08-11T15:44:53Z | 38,905,101 | <p>I think that depends on your stop criteria. You can stop training when loss doesn't improve, or you can have a validation data set, and stop training when validation accuracy doesn't improve any more.</p>
| 0 | 2016-08-11T19:59:36Z | [
"python",
"tensorflow",
"mnist"
] |
How to include related resource with Django Rest Framework JSON API? | 38,900,889 | <p>I am using <a href="https://github.com/django-json-api/django-rest-framework-json-api" rel="nofollow">Django Rest Framework JSON API</a> to create a REST API. I am trying quite simply to include a related resource (2nd degree relation) but Django keeps responding with the error:</p>
<pre><code>This endpoint does no... | 0 | 2016-08-11T15:45:04Z | 38,934,973 | <p>Well, perhaps I was missing something obvious (because this wasn't mentioned in the documentation), but if you look at the <a href="https://github.com/django-json-api/django-rest-framework-json-api/blob/develop/example/serializers.py#L34" rel="nofollow"><code>serializers.py</code></a>file in the example directory of... | 0 | 2016-08-13T16:53:16Z | [
"python",
"django",
"django-rest-framework",
"json-api"
] |
How do I stack rows in a Pandas data frame to get one "long row"? | 38,900,981 | <p>Let's say I have a data frame with 4 rows, 3 columns. I'd like to stack the rows horizontally so that I get one row with 12 columns. How to do it and how to handle colliding column names?</p>
| 2 | 2016-08-11T15:49:39Z | 38,902,076 | <p>You can achieve this by <code>stack</code>ing the frame to produce a series of all the values, we then want to convert this back to a df using <code>to_frame</code> and then <code>reset_index</code> to drop the index levels and then transpose using <code>.T</code>:</p>
<pre><code>In [2]:
df = pd.DataFrame(np.random... | 1 | 2016-08-11T16:51:14Z | [
"python",
"pandas",
"dataframe"
] |
Combining multiple strings into one from text file | 38,900,985 | <p><a href="http://i.stack.imgur.com/22l2X.jpg" rel="nofollow">img4</a></p>
<p>I am using Python pandas/jupyter notebook, and I am having trouble getting the output of a text file to combine into one line. I imported a text file into Python, which I stored in variable AB. I then looped through the data within one of t... | 0 | 2016-08-11T15:49:47Z | 38,901,634 | <pre><code>''.join( [ "".join(letter.split()) for letter in AB["level_0"] ] ).replace('\n','')
</code></pre>
| 0 | 2016-08-11T16:23:11Z | [
"python"
] |
Read from list in contet | 38,901,005 | <p>I'm very new to python and I'm trying to do a basic api request using the requests library, but I'm having some trouble reading a list in the returned body. </p>
<p>The body of my response looks like this: </p>
<pre><code>{
"files": [{
"url": "http://someurl.json",
"lastModified": 14709241800... | -1 | 2016-08-11T15:51:06Z | 38,901,035 | <p>Simply with:</p>
<pre><code>url = data['files'][0]['url']
last_modified = data['files'][0]['lastModified']
</code></pre>
<p>your data is a dictionary that contains a <code>list</code> of dictionaries for the <code>"files"</code> key. To get the first entry of <code>files</code> you must index the list with <code>... | 1 | 2016-08-11T15:52:43Z | [
"python",
"python-3.x",
"python-requests"
] |
Python sqlite3 cannot rollback transaction due to 'SQL statements in progress' when script run from Windows command line. | 38,901,055 | <p>I'm operating table merges on some sqlite3 databases in Python. When one of the merging functions spots an error due to a condition, it returns False. If a False is returned then a rollback is performed. Something like this:</p>
<pre><code>con_out = sqlite3.connect('db',isolation_level=None)
out_cursor = con_out.cu... | 0 | 2016-08-11T15:53:53Z | 38,915,923 | <p>Just in case if anyone wondering, I found the problem. Before I even set the isolation_level of the database to None, I execute:</p>
<pre><code>out_cursor.execute("PRAGMA journal_mode = MEMORY")
db_con_out.commit()
</code></pre>
<p>For some reason this statement was not committing and was still in progress, blocki... | 0 | 2016-08-12T10:37:15Z | [
"python",
"sqlite3"
] |
Create a DataFrame with a MultiIndex | 38,901,145 | <p>I would like to make my DataFrame like the one below and export it to excel. I have all the data available for all the '-' that I have put. I want to know what data structure to pass to pd.Dataframe() to make a table like this.</p>
<p>Would like to know how pandas read these data structures to form a DataFrame.</p>... | 1 | 2016-08-11T15:58:44Z | 38,901,309 | <pre><code>idx = pd.MultiIndex.from_product([['Zara', 'LV', 'Roots'],
['Orders', 'GMV', 'AOV']],
names=['Brand', 'Metric'])
col = ['Yesterday', 'Yesterday-1', 'Yesterday-7', 'Thirty day average']
df = pd.DataFrame('-', idx, col)
df
</code></pre>
<p><s... | 6 | 2016-08-11T16:06:55Z | [
"python",
"pandas",
"multi-index"
] |
insert a variable into an url | 38,901,302 | <p>I got a CSV file with numbers and I want to insert these numbers into a specific location in an url : jus after " "value": "
Here is my code :</p>
<pre><code>with open('update_cases_id.csv') as p:
for lines in p:
uuid = lines.rstrip()
url_POST = "www.example.com/"
values = {}
v... | 0 | 2016-08-11T16:06:22Z | 38,901,544 | <p>You can do this with string formatting, this should work for you:</p>
<pre><code># ...snip
values['filters'] = '{"op":"and","content":[{"op":"in","content":{"field":"cases.case_id","value":%s}]}' % uuid
# snip...
</code></pre>
<p>The <code>%s</code> will be replaced by the uuid by the % replacement operator:</p>
... | 0 | 2016-08-11T16:18:34Z | [
"python",
"csv",
"parsing",
"urllib2"
] |
insert a variable into an url | 38,901,302 | <p>I got a CSV file with numbers and I want to insert these numbers into a specific location in an url : jus after " "value": "
Here is my code :</p>
<pre><code>with open('update_cases_id.csv') as p:
for lines in p:
uuid = lines.rstrip()
url_POST = "www.example.com/"
values = {}
v... | 0 | 2016-08-11T16:06:22Z | 38,902,043 | <p>Try to use <code>Template</code>.</p>
<pre><code>from string import Template
params = Template('{"op":"and","content":[{"op":"in","content":{"field":"cases.case_id","value": ${your_value}}}]}')
params = params.safe_substitute(your_value=123)
# params is '{"op":"and","content":[{"op":"in","content":{"field":"cases.c... | 0 | 2016-08-11T16:49:11Z | [
"python",
"csv",
"parsing",
"urllib2"
] |
Pandas: using groupby to make a table | 38,901,307 | <p>I have dataframe</p>
<pre><code>i,Unnamed: 0,ID,active_seconds,subdomain,search_term,period,code,buy
0,56574,08cd0141663315ce71e0121e3cd8d91f,6,market.yandex.ru,None,515,100.0,1.0
1,56576,08cd0141663315ce71e0121e3cd8d91f,26,market.yandex.ru,None,515,100.0,1.0
2,56578,08cd0141663315ce71e0121e3cd8d91f,14,marke... | 3 | 2016-08-11T16:06:44Z | 38,901,484 | <p>Use <code>'nunique'</code> instead of <code>len</code></p>
<pre><code>df.groupby(['ID', 'buy']).agg({'period': 'nunique', 'active_seconds': sum}) \
.rename(columns={'active_seconds': 'count_sec', 'period': 'sum_session'}).reset_index()
</code></pre>
<p><a href="http://i.stack.imgur.com/OX7IZ.png" rel="nofollow... | 2 | 2016-08-11T16:15:46Z | [
"python",
"pandas"
] |
Convert an array directly to an image (each cell becomes one pixel) in python | 38,901,354 | <p>I want to convert an 64x64 cell array to an 64x64 pixel image. Using matplotlib and pylab I am ending up with images that are approximately 900x900 with the extra pixels being blended together. </p>
<pre><code>py.figure(1)
py.clf()
py.imshow( final_image , cmap='Greys_r' )
</code></pre>
<p>How do I convert from ce... | 0 | 2016-08-11T16:09:02Z | 38,901,681 | <p>That is example of using PIL to create image 2x2. a is array of colors of size 4 (flat)</p>
<pre><code>from PIL import Image
a = [(0, 0, 0), (255, 0, 0), (0, 255, 0), (0, 0, 255)]
# Create RGB image with size 2x2
img = Image.new("RGB", (2, 2))
# Save it to the new function
img.putdata(a)
# Save to the file
img... | 0 | 2016-08-11T16:25:41Z | [
"python",
"data-representation"
] |
Flask view can't access model class even through it's defined in the same file | 38,901,397 | <p>I have a simple single file app to test using SQLAlchemy with Flask. The <code>getResult</code> view uses the <code>MainResult</code> model. However, navigating to <code>/getResult</code> raise <code>NameError: global name 'MainResult' is not defined</code>. That class is defined in the same file as the view, so ... | 0 | 2016-08-11T16:10:57Z | 38,902,217 | <p>Python executes files sequentially. <code>app.run</code> runs forever. So anything after <code>app.run</code> in the file will not have been executed and won't be until the server stops. <code>MainResult</code> isn't defined until after the app is run, so the view can't see it. Move it above the <code>__main__</... | 0 | 2016-08-11T17:00:29Z | [
"python",
"flask"
] |
How do I migrate changes in Django when I'm uninheriting a model? | 38,901,428 | <p>If I have two models and one inherits from another and setup the database with migrate etc. like so:</p>
<pre><code>class TemplateProduct(models.Model):
type = models.CharField(max_length=20)
class Product(TemplateProduct):
name = models.CharField(max_length=80)
</code></pre>
<p>Then how would I migrate t... | 0 | 2016-08-11T16:12:50Z | 38,951,708 | <p>So my solution was to delete both models. Then <code>python manage.py makemigrations --merge</code>, then I added the models back the way I wanted them, finally running <code>python manage.py makemigrations --merge</code> again to add the models back in. </p>
<p>This may not be the most elegant solution but it work... | 0 | 2016-08-15T08:26:20Z | [
"python",
"django",
"django-models"
] |
Pandas: using groupby with condition | 38,901,472 | <p>I have df</p>
<pre><code>i,Unnamed: 0,ID,active_seconds,subdomain,search_term,period,code,buy
0,56574,08cd0141663315ce71e0121e3cd8d91f,6,market.yandex.ru,None,515,100.0,1.0
1,56576,08cd0141663315ce71e0121e3cd8d91f,26,market.yandex.ru,None,515,100.0,1.0
2,56578,08cd0141663315ce71e0121e3cd8d91f,14,market.yande... | 0 | 2016-08-11T16:15:23Z | 38,906,511 | <p>If I understand your question correctly, you want to join with a different data frame when buy == 1. Assuming the first data frame is named df and the second data frame that contains dates is named df2 then this is my proposed solution:</p>
<pre><code>df.groupby(['ID', 'buy']).agg({'active_seconds': sum}).rename(co... | 1 | 2016-08-11T21:35:12Z | [
"python",
"pandas"
] |
Pandas swap columns based on condition | 38,901,563 | <p>I have a pandas dataframe like the following:</p>
<pre><code> Col1 Col2 Col3
0 A 7 NaN
1 B 16 NaN
1 B 16 15
</code></pre>
<p>What I want to do is to swap Col2 with Col3 where the value of Col3 is <code>NaN</code>. Based on other posts and answers on SO, I have this code so far:</p>... | 3 | 2016-08-11T16:19:23Z | 38,901,797 | <p>You can use <code>loc</code> to do the swap:</p>
<pre><code>df.loc[df['Col3'].isnull(), ['Col2', 'Col3']] = df.loc[df['Col3'].isnull(), ['Col3', 'Col2']].values
</code></pre>
<p>Note that <code>.values</code> is required to make sure the swap is done properly, otherwise Pandas would try to align based on index and... | 5 | 2016-08-11T16:32:40Z | [
"python",
"pandas",
"swap"
] |
Pandas swap columns based on condition | 38,901,563 | <p>I have a pandas dataframe like the following:</p>
<pre><code> Col1 Col2 Col3
0 A 7 NaN
1 B 16 NaN
1 B 16 15
</code></pre>
<p>What I want to do is to swap Col2 with Col3 where the value of Col3 is <code>NaN</code>. Based on other posts and answers on SO, I have this code so far:</p>... | 3 | 2016-08-11T16:19:23Z | 38,903,431 | <p>Try this: (its faster)</p>
<pre><code>df["Col3"], df["Col2"] = np.where(df['Col3'].isnull(), [df["Col2"], df["Col3"]], [df["Col3"], df["Col2"] ])
df
Col1 Col2 Col3
0 A NaN 7.0
1 B NaN 16.0
1 B 16.0 15.0
%timeit df.loc[df['Col3'].isnull(), ['Col2', 'Col3']] = df.loc[df['Col3'].isnull(... | 1 | 2016-08-11T18:14:01Z | [
"python",
"pandas",
"swap"
] |
Python: < not supported between str and int | 38,901,601 | <p>I'm learning Python through <em>Automate the Boring Stuff</em> and I'm running into a something I don't quite understand.</p>
<p>I'm trying to create a simple for loop that prints the elements of a list in this format: <code>W, X, Y, and Z</code>.</p>
<p>My code looks like the following: </p>
<pre><code>spam = ['... | 0 | 2016-08-11T16:21:33Z | 38,902,006 | <p>Ah, but <code>for i in array</code> iterates over each <em>element</em>, so <code>if i < len(item)-1:</code> is comparing a <em>string</em> (the array element <code>item</code>) and an integer (<code>len(item)-1:</code>).</p>
<p>So, the problem is you misunderstood <a href="https://docs.python.org/3/tutorial/con... | 1 | 2016-08-11T16:46:25Z | [
"python",
"syntax"
] |
Saving model form not working in Python and Django | 38,901,603 | <p>I have the following models:</p>
<pre><code>class Equipment(models.Model):
asset_number = models.CharField(max_length = 200)
serial_number = models.CharField(max_length = 200)
description = models.TextField(max_length = 200)
def __str__(self):
return self.description
</code></pre>
<p>And Vi... | 1 | 2016-08-11T16:21:36Z | 38,957,147 | <p>You have not passed your request to form.</p>
<pre><code>if request.method == "POST":
#form = EquipmentForm()
form = EquipmentForm(request.POST)
</code></pre>
| 0 | 2016-08-15T14:33:46Z | [
"python",
"django"
] |
Pandas add column to df based on values in a second df | 38,901,643 | <p>I have two separate dataframes <code>df1</code> and <code>df2</code>, both dataframes contain an <code>id</code> column which links rows between them. <code>df2</code> has a <code>group</code> column that <code>df1</code> does not contain. What I would like to do is go through each <code>id</code> in <code>df1</code... | 2 | 2016-08-11T16:23:32Z | 38,901,742 | <pre><code>df1 = pd.DataFrame([[1, 'a'],
[2, 'b'],
[3, 'c']], columns=['id', 'attr'])
df2 = pd.DataFrame([[2, 'd'],
[3, 'e'],
[4, 'f']], columns=['id', 'group'])
df1.merge(df2, how='left')
</code></pre>
<p><a href="http://i.stack.imgur.co... | 4 | 2016-08-11T16:29:09Z | [
"python",
"pandas"
] |
Pandas add column to df based on values in a second df | 38,901,643 | <p>I have two separate dataframes <code>df1</code> and <code>df2</code>, both dataframes contain an <code>id</code> column which links rows between them. <code>df2</code> has a <code>group</code> column that <code>df1</code> does not contain. What I would like to do is go through each <code>id</code> in <code>df1</code... | 2 | 2016-08-11T16:23:32Z | 38,901,806 | <p>You can merge the two dataframes in one by joining them on the id column and then keep only the columns that you need:</p>
<pre><code>df1 = merge(df1, df2, how='left', on='id')
df1.drop('unwanted_column',1)
</code></pre>
| 2 | 2016-08-11T16:33:18Z | [
"python",
"pandas"
] |
Python script can't find path | 38,901,653 | <p>When I execute the following line in my script:</p>
<pre><code>if os.path.exists('/home/jsc0606/Desktop/project/myfile.py')
</code></pre>
<p>I get <code>False</code>. However, when I execute the same line in the terminal in the same directory, I get <code>True</code>. Does anyone know why Python can't find the fil... | 0 | 2016-08-11T16:24:14Z | 38,901,801 | <p>As stated in <a href="https://docs.python.org/2/library/os.path.html" rel="nofollow">the docs</a> about <code>os.path.exists</code>:</p>
<blockquote>
<p>On some platforms, this function may return <code>False</code> if <em>permission is not granted</em> to execute <code>os.stat()</code> on the requested file, eve... | 0 | 2016-08-11T16:33:09Z | [
"python"
] |
ReLU Function In A Recurrent Neural Network. Weights Become Infinity or Zero | 38,901,684 | <p>I am new to machine learning. I've read that the ReLU function is better than a sigmoid function for a recurrent neural network because of the vanishing gradient problem.</p>
<p>I'm trying to implement a very basic recurrent neural network with 3 input nodes, 10 hidden nodes and 3 output nodes.</p>
<p>There is the... | 0 | 2016-08-11T16:25:51Z | 38,907,274 | <p>I do not think the number of hidden nodes is the problem. </p>
<p>In the first case the weights are approaching infinity since the gradient descent update is wrong. The gradient of the loss with respect to a weight represents the direction in which you should update the weight in order to increase the loss. Since o... | 1 | 2016-08-11T22:51:48Z | [
"python",
"machine-learning",
"neural-network",
"artificial-intelligence"
] |
What are the options for changing the behavior of a Django/python module? | 38,901,834 | <p>I want to change the behavior of a class method without re-implementing large portions of the module. What are my options for doing this?</p>
<p>Iâm using the wagtail_blog module in a current project. Separate models are created for Blog and BlogIndexPage. The BlogIndexPage returns a list of all related Blog page... | 0 | 2016-08-11T16:35:09Z | 38,906,453 | <p>I'm not familiar with the <code>wagtail</code> CMS, but I guess you can do something like:</p>
<pre><code>class MyBlogIndexPage(BlogIndexPage):
def get_context(self, *args, **kwargs):
context = super(MyBlogIndexPage, self).get_context(*args, **kwargs)
#do context changes
return context
<... | 0 | 2016-08-11T21:29:48Z | [
"python",
"django",
"django-models",
"wagtail"
] |
basic groupby operations in Dask | 38,901,845 | <p>I am attempting to use Dask to handle a large file (50 gb). Typically, I would load it in memory and use Pandas. I want to groupby two columns "A", and "B", and whenever column "C" starts with a value, I want to repeat that value in that column for that particular group.</p>
<p>In pandas, I would do the following:<... | 1 | 2016-08-11T16:35:53Z | 39,048,926 | <p>It appears dask does not currently implement the <code>fillna</code> method for <code>GroupBy</code> objects. I've tried PRing it some time ago and gave up quite quickly.</p>
<p>Also, dask doesn't support the <code>method</code> parameter (as it isn't always trivial to implement with delayed algorithms).</p>
<p>A ... | 1 | 2016-08-19T23:24:37Z | [
"python",
"pandas",
"dask"
] |
Matplotlib with Google App Engine local development server | 38,901,858 | <p>I want to use matplotlib in my Google App Engine project. I followed the steps, described <a href="https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27" rel="nofollow">here</a> in the official docs. What I did:</p>
<p>1) Created a directory named lib in my application root directory.</p>
... | 2 | 2016-08-11T16:36:51Z | 38,902,275 | <p><code>matplotlib</code> is one of the <a href="https://cloud.google.com/appengine/docs/python/tools/built-in-libraries-27" rel="nofollow">Google-provided 3rd party libs</a>, so you should be following just the <a href="https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27#requesting_a_librar... | 0 | 2016-08-11T17:04:26Z | [
"python",
"google-app-engine",
"matplotlib"
] |
Determine series order in matplotlib chart | 38,901,901 | <p>I am banging my head against matplotlib bar chart.
How do I change the order of bars here, such that women are shown before men?</p>
<pre><code>#!/usr/bin/env python
# a bar plot with errorbars
import numpy as np
import matplotlib.pyplot as plt
N = 5
menMeans = (20, 35, 30, 35, 27)
menStd = (2, 3, 4, 1, 2)
ind = ... | 1 | 2016-08-11T16:39:23Z | 38,902,078 | <p>The solution is quite easy, the order is the xlocation:</p>
<pre><code> rects2 = ax.bar(ind - width, womenMeans, width, color='y', yerr=womenStd)
</code></pre>
<p>This will plot the bars for the second series before the first one.</p>
| 0 | 2016-08-11T16:51:28Z | [
"python",
"matplotlib"
] |
Unexpected colors in multiple scatterplots in matplotlib | 38,901,925 | <p>I'm sure I'm messing up something really simple here, but can't seem to figure it out. I'm simply trying to plot groups of data as scatterplots with different colors for each group by cycling through a dataframe and repeatedly calling <code>ax.scatter</code>. A minimal example is:</p>
<pre><code>import numpy as np;... | 3 | 2016-08-11T16:41:06Z | 38,902,894 | <p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/visualization.html#scatter-plot" rel="nofollow"><code>scatter()</code></a> method of <code>pandas</code> by specifying the target <code>ax</code>and repeating the plots to plot multiple column groups in a single axes,<code>ax</code>.</p>
<pre><code>... | 1 | 2016-08-11T17:44:00Z | [
"python",
"pandas",
"matplotlib"
] |
Unexpected colors in multiple scatterplots in matplotlib | 38,901,925 | <p>I'm sure I'm messing up something really simple here, but can't seem to figure it out. I'm simply trying to plot groups of data as scatterplots with different colors for each group by cycling through a dataframe and repeatedly calling <code>ax.scatter</code>. A minimal example is:</p>
<pre><code>import numpy as np;... | 3 | 2016-08-11T16:41:06Z | 38,913,294 | <p>Should have spent a bit more time whittling down the minimum working example. Turns out the problem was with the call to <code>sns.color_palette</code>, which returns a <code>(float,float,float)</code> tuple that confuses <code>scatter</code> as it apparently interprets one of the numbers as the alpha value. </p>
<... | 1 | 2016-08-12T08:25:40Z | [
"python",
"pandas",
"matplotlib"
] |
Python - urllib3 recieve 403 'Forbidden' while crawling websites | 38,901,929 | <p>I am using <code>Python3</code> and <code>urllib3</code> for crawling and downloading websites. I crawled a list of 4000 different domains and at about 5 of them i got back <code>HttpErrorCode</code> - <code>403 - 'Forbidden'</code>.</p>
<p>On my browser the website does exist and respond correctly. Probably these... | 1 | 2016-08-11T16:41:18Z | 38,905,673 | <p>You specify <code>keep_alive=True</code>, which adds a header <code>connection: keep-alive</code></p>
<p>You then also add a header <code>Connection: keep-alive</code> (note the slight difference in case). And this seems to be causing the problem. To fix it just remove the redundant line </p>
<pre><code>headers['C... | 1 | 2016-08-11T20:35:57Z | [
"python",
"python-3.x",
"urllib",
"urllib3"
] |
ImportError: No module named jira | 38,901,974 | <p>Hi I'm running a python script that transitions tickets from "pending build" to "in test" in Jira. I've ran it on my local machine (Mac OS X) and it works perfectly but when I try to include it as a build task in my bamboo deployment, I get the error </p>
<p>"from jira import JIRA</p>
<p>ImportError: No module nam... | 0 | 2016-08-11T16:44:24Z | 38,902,162 | <p>That is very hard to understand what you problem is. From what I understood you are saying that when you run your module as standalone file, everything works, but when you imoprt it you get an error. Here are some steps towards solving the problem.</p>
<ol>
<li>Make sure that your script is in Python package. In or... | 0 | 2016-08-11T16:56:56Z | [
"python",
"bamboo",
"suse",
"python-jira"
] |
Python Pandas : How to return grouped lists in a column as a dict | 38,902,042 | <p><a href="http://stackoverflow.com/questions/38895856/python-pandas-how-to-compile-all-lists-in-a-column-into-one-unique-list/38896038#38896038">Python Pandas : How to compile all lists in a column into one unique list</a></p>
<p>Starting with data from previous question: </p>
<pre><code>f = pd.DataFrame({'id':['a'... | 1 | 2016-08-11T16:49:10Z | 38,902,168 | <p>Edited using <code>agg</code> from @ayhan (much faster than apply).</p>
<pre><code>from collections import Counter
df.groupby("id")["val"].agg(lambda x: Counter([a for b in x for a in b]))
</code></pre>
<p>Out:</p>
<pre><code>id
a {'val2': 2, 'val6': 1, 'val7': 1, 'val1': 1}
b {'val9': 1, 'val33':... | 1 | 2016-08-11T16:57:09Z | [
"python",
"pandas",
"dictionary",
"group-by"
] |
Python Pandas : How to return grouped lists in a column as a dict | 38,902,042 | <p><a href="http://stackoverflow.com/questions/38895856/python-pandas-how-to-compile-all-lists-in-a-column-into-one-unique-list/38896038#38896038">Python Pandas : How to compile all lists in a column into one unique list</a></p>
<p>Starting with data from previous question: </p>
<pre><code>f = pd.DataFrame({'id':['a'... | 1 | 2016-08-11T16:49:10Z | 38,902,188 | <p>Apply is flexible. Whenever possible, it converts the returning object to something that is more usable. From the <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#flexible-apply" rel="nofollow">docs</a>:</p>
<blockquote>
<p>Some operations on the grouped data might not fit into either the
aggre... | 1 | 2016-08-11T16:58:14Z | [
"python",
"pandas",
"dictionary",
"group-by"
] |
numpy array flags information is not saved when dumping to pickle | 38,902,070 | <p>I'm writing a class that has an attribute of numpy array type.
Since I'd like it to be read-only, I set its WRITABLE flag to be false:</p>
<pre><code>import numpy as np
class MyClass:
def __init__(self):
self.my_array = np.zeros(5)
self.my_array.setflags(write=False)
</code></pre>
<p>After doin... | 0 | 2016-08-11T16:50:54Z | 38,904,943 | <p>For pickling arrays, numpy uses the <code>np.save</code> function. Details of this save are in <code>np.lib.format</code> file. This format saves a header and a byte representation of the data buffer. The content of header is a dictionary. </p>
<pre><code>In [1212]: np.lib.format.header_data_from_array_1_0(x)
O... | 0 | 2016-08-11T19:48:39Z | [
"python",
"arrays",
"numpy",
"pickle"
] |
Performance issues with pandas and filtering on datetime column | 38,902,239 | <p>I've a pandas dataframe with a datetime64 object on one of the columns.</p>
<pre><code> time volume complete closeBid closeAsk openBid openAsk highBid highAsk lowBid lowAsk closeMid
0 2016-08-07 21:00:00+00:00 9 True 0.84734 0.84842 0.84706 0.84814 0.84734 0.84842 0.84706 0.84814 0.84788
... | 13 | 2016-08-11T17:01:57Z | 38,934,632 | <p>It's a bit of speculation because I can't test it but two ideas come to my mind.</p>
<ol>
<li><p>Using a lookup series to determine the start and end indices of a data frame to be returned:</p>
<pre><code>s = pd.Series(np.arange(len(df)), index=df.time)
start = s.asof(start)
end = s.asof(end)
ret = df.iloc[start +... | 0 | 2016-08-13T16:14:42Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Performance issues with pandas and filtering on datetime column | 38,902,239 | <p>I've a pandas dataframe with a datetime64 object on one of the columns.</p>
<pre><code> time volume complete closeBid closeAsk openBid openAsk highBid highAsk lowBid lowAsk closeMid
0 2016-08-07 21:00:00+00:00 9 True 0.84734 0.84842 0.84706 0.84814 0.84734 0.84842 0.84706 0.84814 0.84788
... | 13 | 2016-08-11T17:01:57Z | 38,964,404 | <p>Pandas query can use numexpr as engine to speed up evaluation:</p>
<pre><code>df.query('time > @start & time <= @end')
</code></pre>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.D... | 0 | 2016-08-15T23:19:36Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Performance issues with pandas and filtering on datetime column | 38,902,239 | <p>I've a pandas dataframe with a datetime64 object on one of the columns.</p>
<pre><code> time volume complete closeBid closeAsk openBid openAsk highBid highAsk lowBid lowAsk closeMid
0 2016-08-07 21:00:00+00:00 9 True 0.84734 0.84842 0.84706 0.84814 0.84734 0.84842 0.84706 0.84814 0.84788
... | 13 | 2016-08-11T17:01:57Z | 38,974,448 | <p>it seems to me that using the <code>ix</code> locator is faster</p>
<pre><code>df.sort_values(by='time',inplace=True)
df.ix[(df.time > start) & (df.time <= end),:]
</code></pre>
| 0 | 2016-08-16T12:02:35Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Performance issues with pandas and filtering on datetime column | 38,902,239 | <p>I've a pandas dataframe with a datetime64 object on one of the columns.</p>
<pre><code> time volume complete closeBid closeAsk openBid openAsk highBid highAsk lowBid lowAsk closeMid
0 2016-08-07 21:00:00+00:00 9 True 0.84734 0.84842 0.84706 0.84814 0.84734 0.84842 0.84706 0.84814 0.84788
... | 13 | 2016-08-11T17:01:57Z | 39,027,509 | <p>I've learned that those datetime objects can become very memory hungry and require more computational effort, <strong>Especially</strong> if they are set to be the index (DatetimeIndex objects?)</p>
<p>I think your best bet is to just cast the df.time, start and end into UNIX timestamps (as ints, no longer the date... | 0 | 2016-08-18T21:06:03Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Performance issues with pandas and filtering on datetime column | 38,902,239 | <p>I've a pandas dataframe with a datetime64 object on one of the columns.</p>
<pre><code> time volume complete closeBid closeAsk openBid openAsk highBid highAsk lowBid lowAsk closeMid
0 2016-08-07 21:00:00+00:00 9 True 0.84734 0.84842 0.84706 0.84814 0.84734 0.84842 0.84706 0.84814 0.84788
... | 13 | 2016-08-11T17:01:57Z | 39,037,324 | <p>I guess you are already running things in a relatively efficient way.</p>
<p>When working with time series, it's usually best practice use the column using your timestamps as the <code>DataFrame</code> index. Using a <code>RangeIndex</code> as your index isn't of much use. However, I ran a couple of tests on a (265... | 0 | 2016-08-19T10:57:37Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Performance issues with pandas and filtering on datetime column | 38,902,239 | <p>I've a pandas dataframe with a datetime64 object on one of the columns.</p>
<pre><code> time volume complete closeBid closeAsk openBid openAsk highBid highAsk lowBid lowAsk closeMid
0 2016-08-07 21:00:00+00:00 9 True 0.84734 0.84842 0.84706 0.84814 0.84734 0.84842 0.84706 0.84814 0.84788
... | 13 | 2016-08-11T17:01:57Z | 39,045,224 | <p>If efficiency is your goal, I'd use numpy for just about everything</p>
<p>I rewrote <code>get_new_candles</code> as <code>get_new_candles2</code></p>
<pre><code>def get_new_candles2(clock_tick, previous_tick):
start = previous_tick - timedelta(minutes=1)
end = clock_tick - timedelta(minutes=3)
ge_star... | 2 | 2016-08-19T18:02:10Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
How to update an array of exponential moving average in pandas? | 38,902,271 | <p>I'm using <code>pandas.ewma</code> to compute the exponential moving average of a time series. As new data are appended to the time series, I also need to update its exponential moving average array. How can I do this, without recomputing exponential moving average from the beginning of the time series.</p>
<p>Here... | -1 | 2016-08-11T17:04:20Z | 38,903,448 | <p>Algebraically, it is clear that this can be done. </p>
<p>The EWMA for time <em>m</em> <a href="https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average" rel="nofollow">can be shown to be</a></p>
<p><em>∑ <sub>i = 1</sub><sup>m</sup>[α<sup>m - i</sup> y<sub>i</sub>]</em>.</p>
<p>Suppose y... | 0 | 2016-08-11T18:14:56Z | [
"python",
"pandas",
"numpy"
] |
I need a way to map multiple keys to the same value in a dictionary | 38,902,324 | <p>Admittedly, this question seems like it might be a popular one, but I couldn't really find it (perhaps I wasn't using the right search terms). Anyway, I need something of this sort:</p>
<pre><code>tel = {}
tel['1 12'] = 1729
tel['9 10'] = 1729
tel['1 2'] = 9
tel['2 1'] = 9
tel['1 1'] = 2
print(tel)
{['1 1'] : 2, [... | 1 | 2016-08-11T17:07:02Z | 38,903,042 | <p>As many of the comments have already pointed out, you seem to have your <strong>key/value</strong> structure <strong>inverted</strong>. I would recommend factoring out your <code>int</code> values as <strong>keys</strong> instead. This way you achieve efficient dictionary look ups using the int value as a key, and i... | 2 | 2016-08-11T17:52:05Z | [
"python",
"python-3.x",
"dictionary"
] |
Ansible CSV lookup in Jinja2 template, how to handle missing key | 38,902,351 | <p>j2 template and here is a snippet:</p>
<pre><code>{% set denyGroups %}
{{lookup('csvfile', '{{ ansible_hostname }} file={{ csvFile }} delimiter=, col=5')}}
{% endset %}
{%- if denyGroups |trim() -%}
simple_deny_groups = {{ denyGroups |replace(";", ",") }}
{%- endif -%}
</code></pre>
<p>I am injecting values into t... | 0 | 2016-08-11T17:09:13Z | 38,903,019 | <p><code>list index out of range</code> â it's a problem with number of columns.<br>
Columns are counted from zero, so for <code>col=5</code> â there must be 6 columns in the file.<br>
If you want to return a default item if key is missing, use <code>default=myvalue</code> option.</p>
<p>Update: Let's look into <a... | 1 | 2016-08-11T17:50:23Z | [
"python",
"csv",
"ansible",
"jinja2"
] |
Tkinter/TTK: How to determine if a ProgressBar reaches the maximum value? | 38,902,376 | <p>I'm trying to make simple program that prints "done" to the console when a progress bar reaches the maximum value using ttk.</p>
<p>example:</p>
<pre><code>from tkinter import *
import tkinter.ttk
root = Tk()
pb = tkinter.ttk.Progressbar(root, orient=HORIZONTAL, length=200, mode='determinate')
pb.pack()
pb.start... | 0 | 2016-08-11T17:10:48Z | 38,905,144 | <p>You can update the value yourself by instructing a function to be called every 100ms or so, like this:</p>
<pre><code>from tkinter import *
import tkinter.ttk
root = Tk()
pb = tkinter.ttk.Progressbar(root, orient=HORIZONTAL, length=200, mode='determinate')
pb.pack()
def task():
pb['value'] += 1
if pb['va... | 1 | 2016-08-11T20:02:34Z | [
"python",
"python-3.x",
"tkinter",
"ttk"
] |
Meeting room calendars missing - Office 365 API | 38,902,417 | <p>I am trying to get the list of all calendars for a user. This user has delegate permissions to view the calendar of all the meeting rooms (resources). If I log into the user's account and I am able to see the meeting room calendars in the "Other Calendars" section. I also created my own calendar called "Test" in the... | 0 | 2016-08-11T17:13:19Z | 38,911,002 | <p>The delegate-token which request with the <strong>Auth code grant flow</strong> only able to get the calendars of sign-in user.</p>
<p>If you want to the get the events from the specific room, you can use the app-only token request with <strong>client credential flow</strong>. </p>
<p><a href="http://graph.microso... | 0 | 2016-08-12T06:05:43Z | [
"python",
"office365",
"office365api"
] |
TensorFlow strings: what they are and how to work with them | 38,902,433 | <p>When I read file with <code>tf.read_file</code> I get something with type <code>tf.string</code>. Documentation says only that it is "Variable length byte arrays. Each element of a Tensor is a byte array." (<a href="https://www.tensorflow.org/versions/r0.10/resources/dims_types.html" rel="nofollow">https://www.tenso... | 0 | 2016-08-11T17:14:04Z | 38,902,908 | <p>Unlike Python, where a string can be treated as a list of characters for the purposes of slicing and such, TensorFlow's <code>tf.string</code>s are indivisible values. For instance, <code>x</code> below is a <code>Tensor</code> with shape <code>(2,)</code> whose each element is a variable length string.</p>
<pre><c... | 1 | 2016-08-11T17:44:58Z | [
"python",
"string",
"numpy",
"tensorflow"
] |
Creating runtime variable in python to fetch data from dictionary object | 38,902,444 | <p>I have created dictionary object my parsing a json file in python....lets assume the data is as follows</p>
<pre><code> plants = {}
# Add three key-value tuples to the dictionary.
plants["radish"] = {"color":"red", "length":4}
plants["apple"] = {"smell":"sweet", "season":"winter"}
plants["carrot"] = {"use":"... | 0 | 2016-08-11T17:14:51Z | 38,905,654 | <p>Consider parsing the text file line by line to retrieve file contents. In the read, split the line by period which denotes the keys of dictionaries. From there, use such a list of keys to retrieve dictionary values. Then, iteratively output values to csv, conditioned by number of items:</p>
<p><strong>Txt</strong> ... | 1 | 2016-08-11T20:34:34Z | [
"python",
"json",
"python-2.7"
] |
Python argparse to a game | 38,902,469 | <p>I'm trying to figure out argparse for my adventure game.
This is my code:</p>
<pre><code>parser = argparse.ArgumentParser(description='Adventure')
parser.add_argument('--cheat','-c', action='store_true', help='cheat')
parser.add_argument('--info','-i', action='store_true', help='Information' )
parser.add_argument('... | 1 | 2016-08-11T17:16:34Z | 38,902,546 | <p>The error messages is pretty clear: <code>'Namespace' object has no attribute 'c'</code>.</p>
<p><code>argparse</code> library automatically determines the name of the attribute to store the value of the command line option <a href="https://docs.python.org/3/library/argparse.html#dest" rel="nofollow">in the followi... | 2 | 2016-08-11T17:21:34Z | [
"python",
"python-3.x",
"argparse"
] |
How to run a .py file in Ipython? | 38,902,487 | <h1>Python and Ipython versions:</h1>
<ol>
<li>The version of the notebook server is <code>3.0.0-f75fda4</code>.</li>
<li>Python <code>2.7.9</code> |Anaconda <code>2.2.0</code> (64-bit)| </li>
</ol>
<h1>Problem description</h1>
<p>I am using the <code>undaqtools</code> module in Python. The package page is <a href=... | 1 | 2016-08-11T17:17:26Z | 38,904,956 | <p>You should not be running <code>undaq</code> in ipython. It is a stand-alone script.</p>
<p>To run a python program you need to use the python interpreter. A typical installation of python associates .py files with the python interpreter. However it seems that on your system this hasn't happened.</p>
<p>Check that... | 0 | 2016-08-11T19:49:29Z | [
"python",
"windows",
"ipython",
"argparse"
] |
How to run a .py file in Ipython? | 38,902,487 | <h1>Python and Ipython versions:</h1>
<ol>
<li>The version of the notebook server is <code>3.0.0-f75fda4</code>.</li>
<li>Python <code>2.7.9</code> |Anaconda <code>2.2.0</code> (64-bit)| </li>
</ol>
<h1>Problem description</h1>
<p>I am using the <code>undaqtools</code> module in Python. The package page is <a href=... | 1 | 2016-08-11T17:17:26Z | 38,905,205 | <p>With a simple script, <code>echo_argv.py</code>:</p>
<pre><code>import sys
print(sys.argv)
</code></pre>
<p>Running it in Ipython with your commandline:</p>
<pre><code>In [1222]: %run echo_argv *
['echo_argv.py', 'stack38002264.py', 'stack37714032.py', 'test', 'stack37930737.py ...]
</code></pre>
<p>shows that i... | 0 | 2016-08-11T20:06:18Z | [
"python",
"windows",
"ipython",
"argparse"
] |
Python 3.5/Tkinter: Using Matplotlib in a multi-frame GUI (keeps crashing!) | 38,902,494 | <p>I am trying to achieve something very similar to this question (<a href="http://stackoverflow.com/questions/36928338/cannot-draw-matplotlib-chart-in-tkinter-gui-without-crashing">cannot draw matplotlib chart in tkinter GUI without crashing</a>). The only differences between the code shown in the link and my code are... | -1 | 2016-08-11T17:17:49Z | 38,904,578 | <p>Alright. So it turns out that the issue had nothing to do with my code. As I mentioned above, I'm using the Anaconda Python package, meaning my primary installer ISN'T Pip but is Conda. Whenever I do <code>conda upgrade matplotlib</code>, I would get a message claiming that everything is up to date. However, when I ... | -1 | 2016-08-11T19:25:26Z | [
"python",
"user-interface",
"canvas",
"matplotlib",
"tkinter"
] |
Why does the behavior of the patch library change depending on how values are imported? | 38,902,714 | <p>The <code>patch</code> function from the <code>mock</code> library is sensitive to how things are imported. Is there a deep reason why I can't just use the fully qualified name where the function was originally defined regardless of how it is imported in other modules?</p>
<p>using a "module import" works fine</p>
... | 0 | 2016-08-11T17:32:20Z | 38,903,066 | <p>The problem is that once you directly import the symbol there is <strong>no link whatsoever</strong> between the binding you are using in the <code>__main__</code> module and the binding found in the <code>inner</code> module. So <code>patch</code>ing <em>the module</em> does <strong>not</strong> change the already ... | 1 | 2016-08-11T17:53:19Z | [
"python",
"magicmock"
] |
Variable Scope Issue in Python | 38,903,023 | <p>I am new to Python and I have been working with it for a bit, but I am stuck on a problem. Here is my code:</p>
<pre><code>def collatz(num,ctr):
if(num != 1):
ctr+=1
if(num%2==0):
collatz(num/2,ctr)
else:
collatz(num*3+1,ctr)
return ctr
test=collatz(9,0)
</cod... | 3 | 2016-08-11T17:50:52Z | 38,903,067 | <p>I changed your recursive calls to set the value received back from the recursive calls into ctr. The way you wrote it, you were discarding the values you got back from recursing.</p>
<pre><code>def collatz(num,ctr):
if(num != 1):
ctr+=1
if(num%2==0):
ctr=collatz(num/2... | 3 | 2016-08-11T17:53:27Z | [
"python",
"recursion",
"call",
"callstack"
] |
Variable Scope Issue in Python | 38,903,023 | <p>I am new to Python and I have been working with it for a bit, but I am stuck on a problem. Here is my code:</p>
<pre><code>def collatz(num,ctr):
if(num != 1):
ctr+=1
if(num%2==0):
collatz(num/2,ctr)
else:
collatz(num*3+1,ctr)
return ctr
test=collatz(9,0)
</cod... | 3 | 2016-08-11T17:50:52Z | 38,903,079 | <p>An example: </p>
<pre><code>def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return result
n = input("Give me a number: ")
while n != 1:
n = collatz(int(n))
</code></pre>
| 0 | 2016-08-11T17:53:56Z | [
"python",
"recursion",
"call",
"callstack"
] |
Variable Scope Issue in Python | 38,903,023 | <p>I am new to Python and I have been working with it for a bit, but I am stuck on a problem. Here is my code:</p>
<pre><code>def collatz(num,ctr):
if(num != 1):
ctr+=1
if(num%2==0):
collatz(num/2,ctr)
else:
collatz(num*3+1,ctr)
return ctr
test=collatz(9,0)
</cod... | 3 | 2016-08-11T17:50:52Z | 38,903,101 | <p>The variable will return the final number of the collatz sequence starting from whatever number you put in. The collatz conjecture says this will always be 1</p>
| -3 | 2016-08-11T17:55:22Z | [
"python",
"recursion",
"call",
"callstack"
] |
Variable Scope Issue in Python | 38,903,023 | <p>I am new to Python and I have been working with it for a bit, but I am stuck on a problem. Here is my code:</p>
<pre><code>def collatz(num,ctr):
if(num != 1):
ctr+=1
if(num%2==0):
collatz(num/2,ctr)
else:
collatz(num*3+1,ctr)
return ctr
test=collatz(9,0)
</cod... | 3 | 2016-08-11T17:50:52Z | 38,903,235 | <p>The variable <code>ctr</code> in your example will always be <code>1</code> because of the order of the recursive call stack. As one value of <code>ctr</code> is returned, then the call stack will start returning the previous values of <code>ctr</code>. Basically, at the very last recursive call, the highest value o... | 3 | 2016-08-11T18:02:57Z | [
"python",
"recursion",
"call",
"callstack"
] |
Variable Scope Issue in Python | 38,903,023 | <p>I am new to Python and I have been working with it for a bit, but I am stuck on a problem. Here is my code:</p>
<pre><code>def collatz(num,ctr):
if(num != 1):
ctr+=1
if(num%2==0):
collatz(num/2,ctr)
else:
collatz(num*3+1,ctr)
return ctr
test=collatz(9,0)
</cod... | 3 | 2016-08-11T17:50:52Z | 38,903,352 | <p>Function parameters in Python are passed by value, not by reference. If you pass a number to a function, the function receives a copy of that number. If the function modifies its parameter, that change will not be visible outside the function:</p>
<pre><code>def foo(y):
y += 1
print("y=", y) # prints 11
x = ... | 0 | 2016-08-11T18:09:18Z | [
"python",
"recursion",
"call",
"callstack"
] |
Find the Number of Distinct Topics After LDA in Python/ R | 38,903,061 | <p>As far as I know, I need to fix the number of topics for LDA modeling in Python/ R. However, say I set <code>topic=10</code> while the results show that, for a document, nine topics are all about 'health' and the distinct number of topics for this document is <code>2</code> indeed. How can I spot it without examinin... | 0 | 2016-08-11T17:53:03Z | 38,916,691 | <p>First, your question kind of assumes that topics identified by LDA correspond to real semantic topics - I'd be very careful about that assumption and take a look at the documents and words assigned to topics you want to interpret that way, as LDA often have random extra words assigned, can merge two or more actual t... | 1 | 2016-08-12T11:17:53Z | [
"python",
"lda",
"topic-modeling",
"text-analysis"
] |
Python: Avoid using multiple nested for loops to iterate over strings | 38,903,075 | <p>Is there a simpler way to iterate over multiple strings than a massive amount of nested for loops? </p>
<pre><code>list = ['rst','uvw','xy']
for x in list[0]:
for y in list[1]:
for z in list[2]:
print x+y+z
rux
ruy
...
tvx
tvy
twx
twy
</code></pre>
<p>Example list I really want to avoid t... | 1 | 2016-08-11T17:53:49Z | 38,903,206 | <p>You need itertools.product:</p>
<pre><code>import itertools
list = ['rst','uvw','xy','awfg22','xayx','1bbc1','thij','bob','thisistomuch']
for x in itertools.product(*list):
print(''.join(x))
</code></pre>
<p>product returns all possible tuples of elements from iterators it gets. So</p>
<pre><code>itertools.pr... | 2 | 2016-08-11T18:01:06Z | [
"python",
"for-loop"
] |
Python: Avoid using multiple nested for loops to iterate over strings | 38,903,075 | <p>Is there a simpler way to iterate over multiple strings than a massive amount of nested for loops? </p>
<pre><code>list = ['rst','uvw','xy']
for x in list[0]:
for y in list[1]:
for z in list[2]:
print x+y+z
rux
ruy
...
tvx
tvy
twx
twy
</code></pre>
<p>Example list I really want to avoid t... | 1 | 2016-08-11T17:53:49Z | 38,903,207 | <p>You are looking for the <code>product</code> function from <code>itertools</code>:</p>
<pre><code>import itertools
lst = ['rst','uvw','xy']
[''.join(s) for s in itertools.product(*lst)]
# ['rux',
# 'ruy',
# 'rvx',
# 'rvy',
# 'rwx',
# ...
# 'twx',
# 'twy']
</code></pre>
| 3 | 2016-08-11T18:01:07Z | [
"python",
"for-loop"
] |
Python: Avoid using multiple nested for loops to iterate over strings | 38,903,075 | <p>Is there a simpler way to iterate over multiple strings than a massive amount of nested for loops? </p>
<pre><code>list = ['rst','uvw','xy']
for x in list[0]:
for y in list[1]:
for z in list[2]:
print x+y+z
rux
ruy
...
tvx
tvy
twx
twy
</code></pre>
<p>Example list I really want to avoid t... | 1 | 2016-08-11T17:53:49Z | 38,903,436 | <p>Another way? Definitely. Simpler? Maybe not...</p>
<p>I'm guessing it's because you don't necessarily know how many strings you'll have in your list.</p>
<p>What about:
sl = ['abc','mno','xyz']</p>
<pre><code>def strCombo(l,s=''):
if(len(l)==0):
return s
elif(len(l)==1):
return [(s+x) ... | 0 | 2016-08-11T18:14:22Z | [
"python",
"for-loop"
] |
Exception handling fail in Python | 38,903,175 | <p>I am very new to Python. I am trying to handle the exception in file upload web API. But I am not able to catch. If is goes to success it shows the uploaded file.</p>
<p>app.py:</p>
<pre><code>from flask import Flask
from flask_cors import CORS, cross_origin
from flask import request,jsonify
import smtplib, os, c... | -1 | 2016-08-11T17:59:28Z | 38,903,504 | <p>Try this to catch all exceptions:</p>
<pre><code>try:
raise ValueError('stuff')
except BaseException as e:
print 'Statement:', e.args
print 'Type:', type(e)
</code></pre>
<p>Outputs:</p>
<blockquote>
<p>Statement: ('stuff',) </p>
<p>Type: (class 'ValueError')</p>
</blockquote>
<p>This will let... | 1 | 2016-08-11T18:17:32Z | [
"python",
"flask"
] |
Convert a For loop to While loop in python | 38,903,208 | <p>I am trying to convert these two <strong>for</strong> loops to <strong>while</strong> loops:</p>
<pre><code>sum = 0
for i in range (10, 30):
for j in range(i, 10*i):
sum += j
</code></pre>
<p>Any ideas?</p>
| -4 | 2016-08-11T18:01:11Z | 38,903,315 | <p>What <code>for i in range(a,b)</code> does is it runs the loop for value of <code>i</code> starting from <code>a</code> till it reaches <code>b-1</code> , same you can replecate with while loop statement. What we are doing here is <strong>before starting the loop we initiated <code>i</code> to be qual to a</strong> ... | 1 | 2016-08-11T18:07:15Z | [
"python"
] |
How to write the if else condition inside the list python? | 38,903,297 | <p>I got the pixel size for the image , i need to write a if condition at the pixel </p>
<p>if jpg or tiff: do something
else '0,0'</p>
<p>How can i write in the below code ?</p>
<pre><code>def get(self, request, **response_kwargs):
main_request = MediaRequest.objects.get(request_unique_id=self.kwargs['requ... | -3 | 2016-08-11T18:06:27Z | 38,903,389 | <p>See ternary operator (or conditional expression): <code>"X if C else Y"</code></p>
<p><a href="https://www.python.org/dev/peps/pep-0308/" rel="nofollow">https://www.python.org/dev/peps/pep-0308/</a></p>
<pre><code>for media_file in files:
files_list.append ({
'preview' : "/render/" + str(main_reque... | 0 | 2016-08-11T18:11:16Z | [
"python",
"django",
"python-2.7",
"python-3.x",
"django-views"
] |
How to write the if else condition inside the list python? | 38,903,297 | <p>I got the pixel size for the image , i need to write a if condition at the pixel </p>
<p>if jpg or tiff: do something
else '0,0'</p>
<p>How can i write in the below code ?</p>
<pre><code>def get(self, request, **response_kwargs):
main_request = MediaRequest.objects.get(request_unique_id=self.kwargs['requ... | -3 | 2016-08-11T18:06:27Z | 38,904,814 | <pre><code> 'pixel' : Image.open(settings.MEDIA_ROOT + main_request.request_unique_id
+ "/"+ media_file.filename).size if ("JPG" in media_file.filename.upper())
or ("TIF" in media_file.filename.upper()) else '0, 0'}
</code></pre>
| 0 | 2016-08-11T19:39:22Z | [
"python",
"django",
"python-2.7",
"python-3.x",
"django-views"
] |
Handling "flags" types in telegram's TL schema language | 38,903,321 | <p>I wrote a tl parser so can now use the latest layer (53). But I am unsure how to handle "flags" types. They are only mentioned in the tl docs but not defined (as far as I can tell) at the bottom of the page here: <a href="https://core.telegram.org/mtproto/TL-formal" rel="nofollow">link</a>. </p>
<p>For example, whe... | 1 | 2016-08-11T18:07:27Z | 38,904,456 | <blockquote>
<p>But if the flags are bits in some variable, which variable?</p>
</blockquote>
<pre><code>Message#c09be45f flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true id:int from_id:flags.8?int to_id:Peer fwd_from:flags.2?MessageFwdHeader via_bot_i... | 1 | 2016-08-11T19:16:55Z | [
"python",
"api",
"telegram"
] |
Using Regular expressions to match a portion of the string?(python) | 38,903,383 | <p>What regular expression can i use to match genes(<strong>in bold</strong>) in the gene list string:</p>
<p>GENE_LIST: <strong>F59A7.7</strong>; <strong>T25D3.3</strong>; <strong>F13B12.4</strong>; <strong>cysl-1</strong>; <strong>cysl-2</strong>; <strong>cysl-3</strong>; <strong>cysl-4</strong>; <strong>F01D4.8</st... | 0 | 2016-08-11T18:11:06Z | 38,903,507 | <p><strong>UPDATE</strong></p>
<p>It's in fact much simpler:</p>
<pre><code>[^\s;]+
</code></pre>
<p>however, first use substring to take only the part you need (the genes, without GENELIST )</p>
<p>demo: <a href="https://regex101.com/r/yW5tU1/1" rel="nofollow">regex demo</a></p>
| 0 | 2016-08-11T18:17:42Z | [
"python",
"regex"
] |
Using Regular expressions to match a portion of the string?(python) | 38,903,383 | <p>What regular expression can i use to match genes(<strong>in bold</strong>) in the gene list string:</p>
<p>GENE_LIST: <strong>F59A7.7</strong>; <strong>T25D3.3</strong>; <strong>F13B12.4</strong>; <strong>cysl-1</strong>; <strong>cysl-2</strong>; <strong>cysl-3</strong>; <strong>cysl-4</strong>; <strong>F01D4.8</st... | 0 | 2016-08-11T18:11:06Z | 38,903,564 | <p>Given:</p>
<pre><code>>>> s="GENE_LIST: F59A7.7; T25D3.3; F13B12.4; cysl-1; cysl-2; cysl-3; cysl-4; F01D4.8"
</code></pre>
<p>You can use Python string methods to do:</p>
<pre><code>>>> s.split(': ')[1].split('; ')
['F59A7.7', 'T25D3.3', 'F13B12.4', 'cysl-1', 'cysl-2', 'cysl-3', 'cysl-4', 'F01D4... | 1 | 2016-08-11T18:20:34Z | [
"python",
"regex"
] |
Using Regular expressions to match a portion of the string?(python) | 38,903,383 | <p>What regular expression can i use to match genes(<strong>in bold</strong>) in the gene list string:</p>
<p>GENE_LIST: <strong>F59A7.7</strong>; <strong>T25D3.3</strong>; <strong>F13B12.4</strong>; <strong>cysl-1</strong>; <strong>cysl-2</strong>; <strong>cysl-3</strong>; <strong>cysl-4</strong>; <strong>F01D4.8</st... | 0 | 2016-08-11T18:11:06Z | 38,903,585 | <p>You can use the following:</p>
<pre><code>\s([^;\s]+)
</code></pre>
<p><a href="https://regex101.com/r/iC8zQ7/2" rel="nofollow">Demo</a></p>
<ul>
<li>The captured group, <code>([^;\s]+)</code>, will contain the desired substrings followed by whitespace (<code>\s</code>)</li>
</ul>
<hr>
<pre><code>>>> s... | 1 | 2016-08-11T18:21:28Z | [
"python",
"regex"
] |
Using Regular expressions to match a portion of the string?(python) | 38,903,383 | <p>What regular expression can i use to match genes(<strong>in bold</strong>) in the gene list string:</p>
<p>GENE_LIST: <strong>F59A7.7</strong>; <strong>T25D3.3</strong>; <strong>F13B12.4</strong>; <strong>cysl-1</strong>; <strong>cysl-2</strong>; <strong>cysl-3</strong>; <strong>cysl-4</strong>; <strong>F01D4.8</st... | 0 | 2016-08-11T18:11:06Z | 38,928,788 | <pre><code>string = "GENE_LIST: F59A7.7; T25D3.3; F13B12.4; cysl-1; cysl-2; cysl-3; cysl-4; F01D4.8"
re.findall(r"([^;\s]+)(?:;|$)", string)
</code></pre>
<p>The output is:</p>
<pre><code>['F59A7.7',
'T25D3.3',
'F13B12.4',
'cysl-1',
'cysl-2',
'cysl-3',
'cysl-4',
'F01D4.8']
</code></pre>
| 0 | 2016-08-13T03:03:05Z | [
"python",
"regex"
] |
Pip install-couldn't find a version that satisfies the requirement | 38,903,415 | <p>I am trying to install a package called <a href="https://github.com/Jefferson-Henrique/GetOldTweets-python" rel="nofollow">got</a> using pip. But it keeps showing up errors of 'couldn't find a version that satisfies the requirement".</p>
<p><a href="http://i.stack.imgur.com/8kdNc.png" rel="nofollow"><img src="http:... | 0 | 2016-08-11T18:12:42Z | 38,904,214 | <p>Your package <code>got</code> is indeed not on Pypi.</p>
<p>Your error is thrown when no package have been found.</p>
<p>eg:</p>
<pre><code>â pip install notfoundpackage
Collecting notfoundpackage
Could not find a version that satisfies the requirement notfoundpackage (from versions: )
No matching distributio... | 0 | 2016-08-11T18:59:16Z | [
"python",
"package",
"install",
"pip"
] |
Pip install-couldn't find a version that satisfies the requirement | 38,903,415 | <p>I am trying to install a package called <a href="https://github.com/Jefferson-Henrique/GetOldTweets-python" rel="nofollow">got</a> using pip. But it keeps showing up errors of 'couldn't find a version that satisfies the requirement".</p>
<p><a href="http://i.stack.imgur.com/8kdNc.png" rel="nofollow"><img src="http:... | 0 | 2016-08-11T18:12:42Z | 38,904,430 | <p>This package doesn't include a <code>setup.py</code>, so you can't install it from pip. </p>
<p>If it did, you could install it with:
<code>
pip install git+https://github.com/Jefferson-Henrique/GetOldTweets-python.git
</code></p>
| 0 | 2016-08-11T19:14:58Z | [
"python",
"package",
"install",
"pip"
] |
Python - cannot access class property | 38,903,477 | <p>I'm writing a class to access a mySQL db from python.</p>
<p>Here's the code:</p>
<pre><code>#!/usr/bin/python
import MySQLdb
import configparser
class db():
def __init__(self):
try:
self.handler = MySQLdb.connect(host="localhost", user=user, passwd=passwd, db=dbname)
self.c... | -1 | 2016-08-11T18:16:13Z | 38,903,555 | <p>Your code has mixed tabs and spaces, causing Python to get confused about what statements are at what indentation level. The assignment to <code>self.res</code> has ended up at class level, outside of the method it was intended to be a part of.</p>
<p>Stop mixing tabs and spaces. Turn on "show whitespace" in your e... | 5 | 2016-08-11T18:20:15Z | [
"python",
"class"
] |
printing from csv.reader | 38,903,650 | <p>This should be an easy one, but I'm having a bit of a brain fart. the CSV maintains a list of four latitude and longitude pairs. Based on the code, if I print row[0] it prints just the latitudes and if I print row[1] it prints the longitudes. How to I format the code to print a specific lat/lon pair instead? Say.. T... | 0 | 2016-08-11T18:26:04Z | 38,903,724 | <p>Looping over <code>reader</code> gives you each row. If you wanted to get the second row, use the <a href="https://docs.python.org/2/library/functions.html#next" rel="nofollow"><code>next()</code> function</a> instead, ignore one and get the second:</p>
<pre><code>reader = csv.reader(csvfile)
next(reader) # ignore... | 3 | 2016-08-11T18:30:00Z | [
"python",
"csv"
] |
Django form input missing in POST data | 38,903,691 | <p>I'm using Django 1.9.8 and I'm trying to learn how to use form validation. I'm working on a form for registering users. I have 2 problems that I'm stuck on.</p>
<ol>
<li><p>The field for re-entering the password isn't accessible (rather, just not there at all) in the forms.py file methods. When I use <code>raise E... | 1 | 2016-08-11T18:27:49Z | 38,904,173 | <p>I am not %100 sure why <code>self.cleaned_data.get('repassword')</code> returns <code>None</code> in that method, however <code>clean_password</code> is not the right place for performing validations of fields that depend on each other.</p>
<p>According to <a href="https://docs.djangoproject.com/en/1.10/ref/forms/v... | 2 | 2016-08-11T18:56:48Z | [
"python",
"django",
"django-forms",
"django-templates"
] |
Building a set of tile coordinates | 38,903,768 | <p>I have an image which I want to divide into tiles of specific size (and cropping tiles that don't fit).</p>
<p>The output of this operation should be a list of coordinates in tuples <code>[(x, y, width, height),...]</code>. For example, dividing a 50x50 image in tiles of size 20 would give: <code>[(0,0,20,20),(20,0... | 0 | 2016-08-11T18:32:54Z | 38,904,126 | <p>Got it with:</p>
<pre><code>output = [(x,y,w,h) for x,w in zip(range(width)[::tile_size],[tile_size]*(w_tiles-1) + [w_padding]) for y,h in zip(range(height)[::tile_size],[tile_size]*(h_tiles-1) + [h_padding])]
</code></pre>
| 0 | 2016-08-11T18:54:37Z | [
"python",
"list-comprehension"
] |
Building a set of tile coordinates | 38,903,768 | <p>I have an image which I want to divide into tiles of specific size (and cropping tiles that don't fit).</p>
<p>The output of this operation should be a list of coordinates in tuples <code>[(x, y, width, height),...]</code>. For example, dividing a 50x50 image in tiles of size 20 would give: <code>[(0,0,20,20),(20,0... | 0 | 2016-08-11T18:32:54Z | 38,904,711 | <pre><code>import itertools
def tiles(h, w, ts):
# here is the one list comprehension for list of tuples
return [tuple(list(ele) + [ts if w-ele[0] > 20 else w-ele[0], ts if h-ele[1] > 20 else h-ele[1]]) for ele in itertools.product(*[filter(lambda x: x % ts == 0, range(w)), filter(lambda x: x % ts == 0, ... | 0 | 2016-08-11T19:33:20Z | [
"python",
"list-comprehension"
] |
Why isn't this regex working? It should be working based on diveintopython3 | 38,903,795 | <pre><code>pattern='''
^ #beginning of string
M{0,3} # thousands- 0 to 3 MS
(CM|CD|D?C{0,3}) Â Â # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 Cs), or 500-800 (D, followed by 0 to 3 Cs)
(XC|XL|L?X{0,3}) Â Â # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 Xs), or 50-80 (L, followed by 0 t... | 1 | 2016-08-11T18:34:29Z | 38,903,918 | <p>It works fine for me:</p>
<pre><code>romanstring = "M"
m = re.search(pattern, romanstring, re.VERBOSE)
print(m.string)
</code></pre>
<p>Perhaps you were confused because re.search returns a "match object" instead of returning the matched string directly.</p>
| 0 | 2016-08-11T18:40:32Z | [
"python",
"regex",
"python-3.x"
] |
C++ Call Function When Terminated from Python Subprocess | 38,903,857 | <p>I'm using C++, Python 3.5, and Windows 7. I'm currently calling a C++ executable from my Python code using subprocess, then terminating the executable using the following code:</p>
<pre><code>open = Popen([path\to\exe])
open.terminate()
</code></pre>
<p>This seems unlikely, but is it possible for my C++ code to ca... | 0 | 2016-08-11T18:37:41Z | 38,904,232 | <p>To be able to terminate your C++ code you have to first do things like</p>
<pre><code>p = subprocess.Popen(["path\to\exe"])
#... do stuff
#and when you want to terminate it
p.terminate()
</code></pre>
<p>But you cannot call <code>Popen</code> again because it would spawn another instance, that would would kill imm... | 0 | 2016-08-11T19:00:42Z | [
"python",
"c++",
"function",
"exit",
"terminate"
] |
Sort list of dictionaries on two criteria | 38,903,913 | <p>Recently started programming with python and I have a question to which I cannot come up with an answer. I have a large list of dictionairies with various keys and values (more than below). I want to sort the order of the dictionaries appearing in the list. <code>list_one</code>:</p>
<pre><code>list_one = [{'countr... | 0 | 2016-08-11T18:40:16Z | 38,903,979 | <p>Produce a dictionary mapping country name to order number:</p>
<pre><code>country_ordering = {'France': 1, 'China': 2, 'Australia': 3,
'Spain': 4, 'Russia': 5}
</code></pre>
<p>then use that in your sort key, returning a tuple with the <code>id</code> and a value from that mapping:</p>
<pre><c... | 3 | 2016-08-11T18:44:28Z | [
"python",
"sorting",
"dictionary"
] |
Python 2.6 unittest - how to set a value to use for a global variable in a function that you're testing | 38,903,951 | <p>I'm having trouble setting the value of a global variable in a function that I'm writing for unit tests. </p>
<p>The function is probably not ready to be used in a test. Or at least to be used to test in an easy manner, but I'm trying to work around that. </p>
<p>Here is an example of the function I'm trying to te... | 1 | 2016-08-11T18:42:45Z | 38,904,056 | <p>The globals are defined with a double leading underscore, so they are not imported by the <code>from my_module import *</code> statement.</p>
<p>You <em>can</em> make them accessible with the following:</p>
<pre><code>from my_module import __my_global_var1, __my_global_var2
</code></pre>
<p>Alternatively, if you ... | 1 | 2016-08-11T18:50:15Z | [
"python",
"python-unittest"
] |
Coverting a list of array of lists of lists into dataframe | 38,904,006 | <p>I need help in conversion of a list of array of lists of lists into a dataframe</p>
<p>my data is something like this</p>
<pre><code>[array([[ 0.01568627, 0.01568627, 0.01176471],
[ 0.01176471, 0.01176471, 0.01176471],
[ 0.01176471, 0.01176471, 0.01176471],
...,
[ 0.05098039, 0.05098039, 0.050... | 0 | 2016-08-11T18:46:00Z | 38,905,047 | <p>Consider concatenating with <code>pd.concat()</code> from a list comprehension. Do note you will lose slight precision of two decimal points to fit <code>float64</code> dtype. Below will output a 3-column dataframe:</p>
<pre><code>from numpy import array
import pandas as pd
lst = [array([[ 0.01568627, 0.01568627,... | 0 | 2016-08-11T19:55:43Z | [
"python",
"arrays"
] |
Python - Pandas Output Limits Columns | 38,904,049 | <p>When dealing with Pandas, I'm attempting to print analysis of an objects Kinematic and Angular states. My code for doing so is as follows:</p>
<pre><code>def displayData(tList, xList, zList, dxList, dzList, thetaList, dthetaList, Q_sList):
states = pd.DataFrame({ 't' : tList,
'x' : x... | 4 | 2016-08-11T18:49:29Z | 38,911,212 | <p>There are two useful <a href="http://pandas.pydata.org/pandas-docs/stable/options.html" rel="nofollow">settings</a> which can be used in this case: <code>pd.options.display.width</code> and <code>pd.options.display.expand_frame_repr</code></p>
<p>Here is a small demo:</p>
<pre><code>In [118]: pd.options.display.ex... | 1 | 2016-08-12T06:22:42Z | [
"python",
"pandas",
"dataframe",
"io"
] |
How to format the beginning a loop correctly? | 38,904,167 | <p>this is a very simple question (ironic cause I can't answer it :/). I have a program which I designed both for myself and my colleague to use, with all the data being stored in a directories. However, I want to set up the loop so that it work both for me and him. I tried all of these:</p>
<pre><code>file_location =... | 0 | 2016-08-11T18:56:18Z | 38,904,290 | <p>You can get a directory relative to a user's home (called <code>~</code> in the function call) using <a href="https://docs.python.org/2/library/os.path.html#os.path.expanduser" rel="nofollow"><code>os.path.expanduser()</code></a>. In your case, the line would be </p>
<pre><code>file_location = glob.glob(os.path.ex... | 4 | 2016-08-11T19:05:48Z | [
"python",
"loops",
"iteration",
"dropbox"
] |
How to format the beginning a loop correctly? | 38,904,167 | <p>this is a very simple question (ironic cause I can't answer it :/). I have a program which I designed both for myself and my colleague to use, with all the data being stored in a directories. However, I want to set up the loop so that it work both for me and him. I tried all of these:</p>
<pre><code>file_location =... | 0 | 2016-08-11T18:56:18Z | 38,904,331 | <p>Usually is a good practice not hardcoding paths if you're gonna use your paths for other tasks which need well-formed paths (ie: subprocess, writing paths to shell scripts), I'd recommend to manage paths using the os.path module instead, for example:</p>
<pre><code>import os, glob
home_path = os.path.expanduser("~... | 2 | 2016-08-11T19:08:31Z | [
"python",
"loops",
"iteration",
"dropbox"
] |
How can I be more specific with this regular expression? | 38,904,253 | <p>I'm using python and trying to separate the following string into two strings:</p>
<pre><code>'"99233 (I21.4,I50.23), 93010 (I21.4,I50.23)"'
stringA = "99233 (I21.4,I50.23),"
stringB = "93010 (I21.4,I50.23)"
</code></pre>
<p>I'm using the following expression in python:</p>
<pre><code>pattern = re.compile('\d{5}... | 2 | 2016-08-11T19:02:32Z | 38,904,286 | <p>You could come up with:</p>
<pre><code>import re
string = '99233 (I21.4,I50.23), 93010 (I21.4,I50.23)'
parts = re.split(r'(?<=\)),\ ', string)
print(parts)
# ['99233 (I21.4,I50.23)', '93010 (I21.4,I50.23)']
</code></pre>
<p>This uses a positive lookbehind and splits on the space.<br>
See <a href="http://ideone... | 1 | 2016-08-11T19:05:10Z | [
"python",
"regex"
] |
How can I be more specific with this regular expression? | 38,904,253 | <p>I'm using python and trying to separate the following string into two strings:</p>
<pre><code>'"99233 (I21.4,I50.23), 93010 (I21.4,I50.23)"'
stringA = "99233 (I21.4,I50.23),"
stringB = "93010 (I21.4,I50.23)"
</code></pre>
<p>I'm using the following expression in python:</p>
<pre><code>pattern = re.compile('\d{5}... | 2 | 2016-08-11T19:02:32Z | 38,904,413 | <pre><code>import re
data = '"99233 (I21.4,I50.23), 93010 (I21.4,I50.23)"'
print re.findall(r'\d{5}.*\(.*?\)', data)
</code></pre>
| 1 | 2016-08-11T19:13:55Z | [
"python",
"regex"
] |
How can I be more specific with this regular expression? | 38,904,253 | <p>I'm using python and trying to separate the following string into two strings:</p>
<pre><code>'"99233 (I21.4,I50.23), 93010 (I21.4,I50.23)"'
stringA = "99233 (I21.4,I50.23),"
stringB = "93010 (I21.4,I50.23)"
</code></pre>
<p>I'm using the following expression in python:</p>
<pre><code>pattern = re.compile('\d{5}... | 2 | 2016-08-11T19:02:32Z | 38,904,518 | <p>You can use a positive lookahead:</p>
<p><code>\d{5}.*(?=\))</code></p>
<p>Additionally you could make this:</p>
<p><code>(\d{5})(.*(?=\())(.*)(?=\))</code></p>
<p>Then you could grab the 5 digit string with back-reference 1, and the inner-string with back-reference 3</p>
<p>Or you could take it one step furthe... | 0 | 2016-08-11T19:21:01Z | [
"python",
"regex"
] |
How to calculate sum of Nth power of each cell for a column in dataframe? | 38,904,340 | <p>I have a dataframe like this:</p>
<pre><code> A B C
396 1147.430 1147.219 0.000184
397 1147.110 1147.630 -0.000453
398 1146.870 1147.469 -0.000522
399 1147.110 1147.680 -0.000497
400 1147.170 1147.640 -0.000410
401 1147.210 1147.430 -0.000192
</code></pre>
<p>I want to take the ... | 0 | 2016-08-11T19:09:02Z | 38,904,384 | <pre><code>df['C'].pow(3).sum()
Out: -4.2772918200000004e-10
</code></pre>
<p>Or,</p>
<pre><code>(df['C']**3).sum()
Out: -4.2772918200000004e-10
</code></pre>
| 2 | 2016-08-11T19:12:33Z | [
"python",
"pandas",
"dataframe"
] |
Substracting values from different DataFrame | 38,904,348 | <p>I got two DataFrames and Want to substract.</p>
<p>df1:</p>
<pre><code> Val1 Val2 Val3
0 -27 -0.8 -6.786321 -7.024615 -13.946589
1 -27 -0.9 -5.746795 -5.804550 -11.576365
2 -27 -1.0 -4.624857 -4.372321 -9.103681
3 -27 -1.2 -2.685832 -2.418888 -5.057056 ... | 1 | 2016-08-11T19:09:57Z | 38,904,458 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sub.html" rel="nofollow"><code>pd.DataFrame.sub</code></a>, like this:</p>
<pre><code>In [113]: df1.sub(df2.Bench.values, axis=0)
Out[113]:
Val1 Val2 Val3
0 -27 -0.8 -7.246421 -7.484715 -14.406689... | 1 | 2016-08-11T19:16:56Z | [
"python",
"pandas"
] |
Substracting values from different DataFrame | 38,904,348 | <p>I got two DataFrames and Want to substract.</p>
<p>df1:</p>
<pre><code> Val1 Val2 Val3
0 -27 -0.8 -6.786321 -7.024615 -13.946589
1 -27 -0.9 -5.746795 -5.804550 -11.576365
2 -27 -1.0 -4.624857 -4.372321 -9.103681
3 -27 -1.2 -2.685832 -2.418888 -5.057056 ... | 1 | 2016-08-11T19:09:57Z | 38,904,483 | <p>You can use</p>
<pre><code>pd.DataFrame(df1.values - df2.values)
</code></pre>
| 0 | 2016-08-11T19:18:38Z | [
"python",
"pandas"
] |
Python to Matlab Conversion? | 38,904,366 | <p>I have this python code here below (for bubble sort). Below that is my attempt at converting it to MATLAB code. I'm new to MATLAB, and I'm doing the conversion for practice. I would appreciate feedback on how accurate/incorrect my conversion is.</p>
<p>The python version:</p>
<pre><code>def bubble_sort(alist):
... | 1 | 2016-08-11T19:11:10Z | 38,904,549 | <p>A few issues here:</p>
<ol>
<li><p>You need to use <code>numel</code> rather than <code>size</code> to get the number of elements in an array. <code>size</code> will give you a vector of sizes of each dimension and <code>numel</code> will give you the total number of elements</p></li>
<li><p>You need to actually cr... | 2 | 2016-08-11T19:23:14Z | [
"python",
"matlab"
] |
Python to Matlab Conversion? | 38,904,366 | <p>I have this python code here below (for bubble sort). Below that is my attempt at converting it to MATLAB code. I'm new to MATLAB, and I'm doing the conversion for practice. I would appreciate feedback on how accurate/incorrect my conversion is.</p>
<p>The python version:</p>
<pre><code>def bubble_sort(alist):
... | 1 | 2016-08-11T19:11:10Z | 38,904,556 | <p>Your python version is inefficient:</p>
<pre><code>def bubble_sort(alist):
return bubble_sort_helper(alist, len(alist))
def bubble_sort_helper(alist, n):
if n < 2:
return alist
for i in range(n-1):
if alist[i] > alist[i+1]:
alist[i], alist[i+1] = alist[i+1], alist[i]
... | 1 | 2016-08-11T19:23:44Z | [
"python",
"matlab"
] |
Python storing number with leading zeros in Dictionary | 38,904,377 | <p>I have a dictionary called table. I want to assign this number to the below dic key. it keeps giving me an error saying "invalid token". I have tried converting it string, int, and float but to no avail</p>
<p><code>table['Fac_ID'] = 00000038058</code></p>
| -2 | 2016-08-11T19:12:15Z | 38,904,437 | <p>you're unwilingly invoking Python 2.x octal mode but:</p>
<ul>
<li>you can't because there's a 8 in it (bad or good luck?)</li>
<li>in python 3 (also works in python 2.7), octal prefix is no longer <code>0</code> but <code>0o</code>: invalid token occurs because of that.</li>
</ul>
<p>It would be better to store y... | 2 | 2016-08-11T19:15:34Z | [
"python",
"dictionary",
"leading-zero"
] |
Python storing number with leading zeros in Dictionary | 38,904,377 | <p>I have a dictionary called table. I want to assign this number to the below dic key. it keeps giving me an error saying "invalid token". I have tried converting it string, int, and float but to no avail</p>
<p><code>table['Fac_ID'] = 00000038058</code></p>
| -2 | 2016-08-11T19:12:15Z | 38,904,442 | <p>Don't convert it to a string, use it as a string in the first place:</p>
<pre><code>>>> table['Fac_ID'] = str(00000038058)
File "<stdin>", line 1
table['Fac_ID'] = str(00000038058)
^
SyntaxError: invalid token
>>> table['Fac_ID'] = '00000038058'
>... | 1 | 2016-08-11T19:15:49Z | [
"python",
"dictionary",
"leading-zero"
] |
Python storing number with leading zeros in Dictionary | 38,904,377 | <p>I have a dictionary called table. I want to assign this number to the below dic key. it keeps giving me an error saying "invalid token". I have tried converting it string, int, and float but to no avail</p>
<p><code>table['Fac_ID'] = 00000038058</code></p>
| -2 | 2016-08-11T19:12:15Z | 38,904,475 | <p>Surround the number in quotes.</p>
<p>table['Fac_ID'] = "00000038058"</p>
| 0 | 2016-08-11T19:18:03Z | [
"python",
"dictionary",
"leading-zero"
] |
Python storing number with leading zeros in Dictionary | 38,904,377 | <p>I have a dictionary called table. I want to assign this number to the below dic key. it keeps giving me an error saying "invalid token". I have tried converting it string, int, and float but to no avail</p>
<p><code>table['Fac_ID'] = 00000038058</code></p>
| -2 | 2016-08-11T19:12:15Z | 38,904,544 | <p>You can use <a href="https://docs.python.org/2/library/string.html#string.zfill" rel="nofollow"><code>zfill</code></a> to pad zeros. Assuming you want to pad up to 11 zeroes:</p>
<pre><code>>>> str(38058).zfill(11)
'00000038058'
</code></pre>
<p>This obviously creates a zero padded string to be used as t... | 0 | 2016-08-11T19:22:53Z | [
"python",
"dictionary",
"leading-zero"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.