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
Removing some of the duplicates from a list in Python
38,599,066
<p>I would like to remove a certain number of duplicates of a list without removing all of them. For example, I have a list <code>[1,2,3,4,4,4,4,4]</code> and I want to remove 3 of the 4's, so that I am left with <code>[1,2,3,4,4]</code>. A naive way to do it would probably be</p> <pre><code>def remove_n_duplicates(...
5
2016-07-26T20:13:25Z
38,599,466
<p>You can use Python's set functionality with the &amp; operator to create a list of lists and then flatten the list. The result list will be [1, 2, 3, 4, 4].</p> <pre><code>x = [1,2,3,4,4,4,4,4] x2 = [val for sublist in [[item]*max(1, x.count(item)-3) for item in set(x) &amp; set(x)] for val in sublist] </code></pre...
0
2016-07-26T20:39:17Z
[ "python", "list", "duplicates" ]
Removing some of the duplicates from a list in Python
38,599,066
<p>I would like to remove a certain number of duplicates of a list without removing all of them. For example, I have a list <code>[1,2,3,4,4,4,4,4]</code> and I want to remove 3 of the 4's, so that I am left with <code>[1,2,3,4,4]</code>. A naive way to do it would probably be</p> <pre><code>def remove_n_duplicates(...
5
2016-07-26T20:13:25Z
38,600,022
<p>Here is another trick which might be useful sometimes. Not to be taken as the recommended recipe. </p> <pre><code>def remove_n_duplicates(remove_from, what, how_many): exec('remove_from.remove(what);'*how_many) </code></pre>
-1
2016-07-26T21:17:10Z
[ "python", "list", "duplicates" ]
Removing some of the duplicates from a list in Python
38,599,066
<p>I would like to remove a certain number of duplicates of a list without removing all of them. For example, I have a list <code>[1,2,3,4,4,4,4,4]</code> and I want to remove 3 of the 4's, so that I am left with <code>[1,2,3,4,4]</code>. A naive way to do it would probably be</p> <pre><code>def remove_n_duplicates(...
5
2016-07-26T20:13:25Z
38,600,220
<p>If the list is sorted, there's the fast solution:</p> <pre><code>def remove_n_duplicates(remove_from, what, how_many): index = 0 for i in range(len(remove_from)): if remove_from[i] == what: index = i break if index + how_many &gt;= len(remove_from): #There aren't ...
0
2016-07-26T21:31:09Z
[ "python", "list", "duplicates" ]
How does Djangos user permissions work?
38,599,174
<p>I am lacking of basic understanding of the user permission model of django. What I basically want is that a user can delete its own account with a button. But I fear that I grant the user more permissions to delete things than the user should. Like deleting other users?!?</p> <p>So i guess i have to use something ...
0
2016-07-26T20:19:30Z
38,599,394
<p>Just to let an user to delete his own account you don't really need the permission system. You can do it in a view like this:</p> <pre><code>from django.contrib.auth import logout def delete_my_account(request): user = request.user if user.is_authenticated(): logout(request) user.delete() ...
1
2016-07-26T20:34:18Z
[ "python", "django", "python-3.x", "permissions" ]
Changing or Turning off _FillValues
38,599,252
<p>I want to either turn off the filling or change the _FillValue to None/NaN in the NetCDF file. How do you do this? I have tried looking it up and nobody talks about it. When I output a variable such as longitude, this is what I get:</p> <p><strong>float32 lons(lons) units: degree_east unlimited dimensions: ...
0
2016-07-26T20:25:25Z
38,685,109
<p><a href="http://unidata.github.io/netcdf4-python/#netCDF4.Dataset.set_fill_off" rel="nofollow" title="_Fill_Value">_Fill_Value</a> is the proper name for the attribute you want.</p> <pre><code>dateset.set_fill_off() </code></pre> <p>should work.</p> <pre><code>dataset.setncattr("_Fill_Value", None) </code></pre> ...
0
2016-07-31T14:44:28Z
[ "python", "missing-data", "netcdf" ]
Iterate through columns to compare each one with a specific column in Python
38,599,261
<p>I'm trying to use pandas in python to solve this problem. I have a data frame with nearly 1000 columns. For each column, I'd like to return a boolean value for a mathematical operation - specifically <code>Column A</code> - <code>Column n</code> => 0.</p> <pre><code>"ID" "Column A" "Column B" "Column C" "Column D...
2
2016-07-26T20:25:51Z
38,599,495
<p>This should do it:</p> <pre><code>c = 'Column A' d = df.set_index('ID') lt = d.drop(c, axis=1).lt(d[c], axis=0) pd.concat([d[c], lt], axis=1).reset_index() </code></pre> <p><a href="http://i.stack.imgur.com/bEKvB.png" rel="nofollow"><img src="http://i.stack.imgur.com/bEKvB.png" alt="enter image description here"><...
1
2016-07-26T20:41:38Z
[ "python", "loops", "pandas" ]
Iterate through columns to compare each one with a specific column in Python
38,599,261
<p>I'm trying to use pandas in python to solve this problem. I have a data frame with nearly 1000 columns. For each column, I'd like to return a boolean value for a mathematical operation - specifically <code>Column A</code> - <code>Column n</code> => 0.</p> <pre><code>"ID" "Column A" "Column B" "Column C" "Column D...
2
2016-07-26T20:25:51Z
38,599,523
<p>You can apply a <code>lambda</code> function that subtracts each column series from the target column and then tests if the result is greater than or equal to zero (<code>ge(0)</code>).</p> <pre><code>d = {'Column A': {'A': 100, 'B': 75}, 'Column B': {'A': 200, 'B': 20}, 'Column C': {'A': 300, 'B': 74}, ...
1
2016-07-26T20:43:28Z
[ "python", "loops", "pandas" ]
Iterate through columns to compare each one with a specific column in Python
38,599,261
<p>I'm trying to use pandas in python to solve this problem. I have a data frame with nearly 1000 columns. For each column, I'd like to return a boolean value for a mathematical operation - specifically <code>Column A</code> - <code>Column n</code> => 0.</p> <pre><code>"ID" "Column A" "Column B" "Column C" "Column D...
2
2016-07-26T20:25:51Z
38,602,339
<pre><code>df = df.set_index("ID") dd = df.apply(lambda x: x.lt(df["Column A"])) dd["Column A"] = df["Column A"] dd Column A Column B Column C Column D ID A 100 False False True B 75 True True False </code></pre>
0
2016-07-27T01:37:08Z
[ "python", "loops", "pandas" ]
When making a program that draws forever, how do I keep the drawings on screen?
38,599,295
<p>It's a fairly simple code I made in my free time, but since it's random the pointer always has a chance of going off screen. I've watched my child use Scratch before and in their drawing/sprites if it hits the edge it can bounce off back in, so it's never off screen. I am looking for a code like that but for Python....
0
2016-07-26T20:28:25Z
38,600,243
<pre><code>from turtle import * from random import* while True: forward(randint(1, 360)) right(randint(1, 360)) if xcor() &lt; 0: setx(20) if ycor() &lt; 0: sety(20) if xcor() &gt; window_width(): setx(window_width()-20) if ycor() &gt; window_height(): set...
0
2016-07-26T21:32:16Z
[ "python", "turtle-graphics" ]
Accesing a matrix within a .mat file with python
38,599,329
<p>I'm translating matlab code to python. I have a few matrices within a .mat file called 'AK_1'. I only want to access the data in one of these matrices. The matlab code accesses it this way where .response1 is the desired matrix:</p> <blockquote> <p>numtrials1 = subject_data1.response1(1,:);</p> </blockquote> <p>...
0
2016-07-26T20:30:45Z
38,599,482
<p>create and save a structure containing 3 matrices in matlab:</p> <pre><code>a=1:5 b.aa=a b.bb=a b.cc=a save(struct.mat,'b') </code></pre> <p>load .mat file in python</p> <pre><code>from scipy.io import loadmat matfile = loadmat('d:/struct.mat') </code></pre> <p>you can now access for example b.aa and b.bb via:</...
0
2016-07-26T20:40:15Z
[ "python", "matlab", "matrix" ]
Accesing a matrix within a .mat file with python
38,599,329
<p>I'm translating matlab code to python. I have a few matrices within a .mat file called 'AK_1'. I only want to access the data in one of these matrices. The matlab code accesses it this way where .response1 is the desired matrix:</p> <blockquote> <p>numtrials1 = subject_data1.response1(1,:);</p> </blockquote> <p>...
0
2016-07-26T20:30:45Z
38,600,257
<p>Say you have a <code>myfile.mat</code> with the following struct S:</p> <pre><code>S = response1: [5x5 double] response2: [5x5 double] response3: [5x5 double] </code></pre> <p>And you want to access <code>response1</code> from python. Then:</p> <pre><code>&gt;&gt;&gt; from scipy.io import loadmat &gt...
1
2016-07-26T21:33:29Z
[ "python", "matlab", "matrix" ]
How to set SAS program macro variables through a python script
38,599,404
<p>I have multiple SAS program files, each of which has various macro variables which need to be set dynamically through an excel file. I was wondering if I can pass the values from the excel file to the SAS program through a python script (or shell script). I wish to automate the process of setting parameter for each ...
0
2016-07-26T20:35:25Z
38,734,883
<p>You can pass a string to SAS using the <code>-sysparm</code> command line option, and this string will be available in SAS as the <code>&amp;sysparm</code> automatic variable.</p> <p>E.g. (from the command line:)</p> <pre>sas myprogram.sas -sysparm myparam</pre> <p>If you need to parse the string inside SAS, the ...
0
2016-08-03T05:13:43Z
[ "python", "parameters", "automation", "sas" ]
How to set SAS program macro variables through a python script
38,599,404
<p>I have multiple SAS program files, each of which has various macro variables which need to be set dynamically through an excel file. I was wondering if I can pass the values from the excel file to the SAS program through a python script (or shell script). I wish to automate the process of setting parameter for each ...
0
2016-07-26T20:35:25Z
40,027,782
<p>So I did figure out how I can solve this:</p> <pre><code> subprocess.call(['C:\\Program Files\\SASHome\\SASFoundation\\9.4\\sas.exe', '-config', config_path, '-autoexec', autoexec_path,'-sasinitialfolder',sasinitialfolder,'-sysin', sas_script_path,'-log',ori_log]) </code></pre> <p>I made a subprocess call f...
0
2016-10-13T17:52:11Z
[ "python", "parameters", "automation", "sas" ]
An equivalent to R's %in% operator in Python
38,599,455
<p>I'm starting to learn a bit more about Python. One function I often want but don't know how to program/do in Python is the <code>x %in% y</code> operator in R. It works like so:</p> <pre><code>1:3 %in% 2:4 ##[1] FALSE TRUE TRUE </code></pre> <p>The first element in <code>x</code> (1) has no match in <code>y</...
2
2016-07-26T20:38:46Z
38,599,487
<p><code>%in%</code> is simply <code>in</code> in Python. But, like most other things in Python outside numpy, it’s not vectorised:</p> <pre><code>In [1]: 1 in [1, 2, 3] Out[1]: True In [2]: [1, 2] in [1, 2, 3] Out[2]: False </code></pre>
1
2016-07-26T20:40:48Z
[ "python" ]
An equivalent to R's %in% operator in Python
38,599,455
<p>I'm starting to learn a bit more about Python. One function I often want but don't know how to program/do in Python is the <code>x %in% y</code> operator in R. It works like so:</p> <pre><code>1:3 %in% 2:4 ##[1] FALSE TRUE TRUE </code></pre> <p>The first element in <code>x</code> (1) has no match in <code>y</...
2
2016-07-26T20:38:46Z
38,599,505
<p>It's actually very simple. </p> <pre><code>if/for element in list-like object. </code></pre> <p>Specifically, when doing so for a list it will compare every element in that list. When using a dict as the list-like object (iterable), it will use the dict keys as the object to iterate through. </p> <p>Cheers </p> ...
2
2016-07-26T20:42:13Z
[ "python" ]
while loop not working in tkinter animation
38,599,605
<p>I am trying to create an animation of a turning wheel and want to have a small delay in a while loop and then update the wheel every time. I have tried both the "after" function in tkinter as well as the "sleep" function in python but it either crashes or finishes the conputation and only shows me the last position...
0
2016-07-26T20:48:19Z
38,599,751
<p>This code:</p> <pre><code>while (1): root.after(1000, spin) </code></pre> <p>.. is going to schedule the <code>spin</code> function to run in 1 second. And it's going to do that thousands of times in the blink of an eye. Even though you're asking <code>spin</code> to run in one second, the while loop itself is...
0
2016-07-26T20:56:59Z
[ "python", "loops", "animation", "tkinter", "delay" ]
while loop not working in tkinter animation
38,599,605
<p>I am trying to create an animation of a turning wheel and want to have a small delay in a while loop and then update the wheel every time. I have tried both the "after" function in tkinter as well as the "sleep" function in python but it either crashes or finishes the conputation and only shows me the last position...
0
2016-07-26T20:48:19Z
38,599,822
<p><code>after</code> is used inside the function you are trying to put in a loop:</p> <pre><code>def f(): ... root.after(1000, f) </code></pre> <p>(1000 means 1000 milliseconds which is 1 second. This means the program will perform an operation every 1 second. And you can change it to any number you wish.) A...
0
2016-07-26T21:02:28Z
[ "python", "loops", "animation", "tkinter", "delay" ]
while loop not working in tkinter animation
38,599,605
<p>I am trying to create an animation of a turning wheel and want to have a small delay in a while loop and then update the wheel every time. I have tried both the "after" function in tkinter as well as the "sleep" function in python but it either crashes or finishes the conputation and only shows me the last position...
0
2016-07-26T20:48:19Z
38,604,020
<p>I have noticed that many beginners 'who don't know better' try to animate tkinter with a while loop. It turns out that this is not a silly idea. I recently figured out how to make this work using asyncio and the new in 3.5 async-await syntax. I also worked out a generic template for a simple app. I happen to lik...
0
2016-07-27T04:55:38Z
[ "python", "loops", "animation", "tkinter", "delay" ]
Parallel calls of sleep don't add up
38,599,607
<p>Using the subprocess module, I'm running 1000 calls to sleep(1) in parallel:</p> <pre><code>import subprocess import time start = time.clock() procs = [] for _ in range(1000): proc = subprocess.Popen(["sleep.exe", "1"]) procs.append(proc) for proc in procs: proc.communicate() end = time.clock() print...
0
2016-07-26T20:48:30Z
38,599,670
<p>This is because, <code>subprocess.Popen(..)</code> is <strong>not a blocking call</strong>. The thread just triggers the child process creation and moves on. It does not wait for it to finish.</p> <p>In other words, you are spawning 1000 asynchronous processes in a loop, and then waiting on them one by one later on...
1
2016-07-26T20:51:49Z
[ "python", "multithreading", "optimization" ]
Parallel calls of sleep don't add up
38,599,607
<p>Using the subprocess module, I'm running 1000 calls to sleep(1) in parallel:</p> <pre><code>import subprocess import time start = time.clock() procs = [] for _ in range(1000): proc = subprocess.Popen(["sleep.exe", "1"]) procs.append(proc) for proc in procs: proc.communicate() end = time.clock() print...
0
2016-07-26T20:48:30Z
38,599,715
<p>Sleeping doesn't require any processor time, so your OS can run far more than 4 sleep requests at a time, even though it has only 4 cores. Ideally it would be able to process the entire batch of 1000 in only 1 second, but there's lots of overhead in the creation and teardown of the individual processes.</p>
2
2016-07-26T20:54:55Z
[ "python", "multithreading", "optimization" ]
Why is my code looping at just one line in the while loop instead over the whole block?
38,599,634
<p>Sorry for the unsophisticated question title but I need help desperately: </p> <p>My objective at work is to create a script that pulls all the records from exacttarget salesforce marketing cloud API. I have successfully setup the API calls, and successfully imported the data into DataFrames. </p> <p><strong>The p...
0
2016-07-26T20:49:43Z
38,599,896
<p>You don't seem to be updating <code>Results_Message</code> in your loop, so it's always going to have the value it gets in line 29: <code>Results_Message = getResponse1.message</code>. Unless there's code involved that you didn't share, that is.</p>
0
2016-07-26T21:07:44Z
[ "python", "parsing", "soap", "dataframe" ]
Exception printing only one word
38,599,734
<p>I have part of a class that looks like this:</p> <pre><code>def set_new_mode(self,mode): try: #this will fail, since self.keithley is never initialized print self.keithley self.keithley.setzerocheck(on=True) self.keithley.selectmode(mode,nplc=6) self.keithley.setzerocheck...
1
2016-07-26T20:55:57Z
38,599,937
<p>If you modify your code:</p> <pre><code>import Tkinter as tk class Fnord(tk.Tk): def set_new_mode(self,mode): try: import pdb; pdb.set_trace() #this will fail, since self.keithley is never initialized print self.keithley Fnord().set_new_mode('whatever') </code></pre...
1
2016-07-26T21:10:52Z
[ "python", "exception" ]
python dictionary to csv where each key is in seperate row and value in separate columns
38,599,741
<p>I am having trouble trying to output my dictionary to CSV file. I have a Dictionary that contains as keys time dates and as values, companies pertaining to those dates which are in string format. I tried looking through the website for identical question, but it doesn't really help my case. I tried the following ...
0
2016-07-26T20:56:24Z
38,600,089
<p>You may need to put something like this:</p> <pre><code>for key,values in sorted(a.items()): w.writerow(str(key) + "," + ","join(values)) </code></pre> <p><code>",".join(values)</code> will split the list of values into a string delimited by commas. I'm assuming you want commas separating your columns because ...
0
2016-07-26T21:22:37Z
[ "python", "dictionary", "export-to-csv" ]
python dictionary to csv where each key is in seperate row and value in separate columns
38,599,741
<p>I am having trouble trying to output my dictionary to CSV file. I have a Dictionary that contains as keys time dates and as values, companies pertaining to those dates which are in string format. I tried looking through the website for identical question, but it doesn't really help my case. I tried the following ...
0
2016-07-26T20:56:24Z
38,600,270
<p>This line is putting the key (the date) in the key variable, and the values, as a <em>list</em> in values. So values will indeed contain something like ['AA' 'BB' 'AAPL'].</p> <pre><code>for key,values in sorted(a.items()): </code></pre> <p>Next, you're telling writerow "write a row with two elements: the first is...
0
2016-07-26T21:34:12Z
[ "python", "dictionary", "export-to-csv" ]
python dictionary to csv where each key is in seperate row and value in separate columns
38,599,741
<p>I am having trouble trying to output my dictionary to CSV file. I have a Dictionary that contains as keys time dates and as values, companies pertaining to those dates which are in string format. I tried looking through the website for identical question, but it doesn't really help my case. I tried the following ...
0
2016-07-26T20:56:24Z
38,600,420
<p>Am sorry if I read this wrong, but are you using python pandas?</p> <blockquote> <p>" I have a Dictionary that contains as keys pandas time dates and as values, >companies pertaining to those dates which are in string format."</p> </blockquote> <p>in that case something like this might work</p> <pre><code>impor...
0
2016-07-26T21:46:47Z
[ "python", "dictionary", "export-to-csv" ]
how to replace values in columns by new values in pandas
38,599,818
<p>I have this code:</p> <pre><code>def chgFormat(x): newFormat = 0 if x[-1] == 'K': if len(x)==1:newFormat=1000 else:newFormat = float(x[:-1])*1000 elif x[-1] == 'M': newFormat = float(x[:-1]) * 100000 elif x[-1] == 'B': newFormat = float(x[:-1]) * 1000000 elif x[-1...
0
2016-07-26T21:02:03Z
38,599,914
<p>You may try this </p> <pre><code>frame['DAMAGE_PROPERTY'] = frame['DAMAGE_PROPERTY'].apply(chgFormat, axis=1) </code></pre>
2
2016-07-26T21:09:13Z
[ "python", "pandas", "dataframe" ]
python xml.etree - how to search on more than one attribute
38,599,880
<p>I have an XML file with this line:</p> <pre><code>&lt;op type="create" file="C:/Users/mureadr/Desktop/A/HMI_FORGF/bld/armle-v7/release/SimpleNetwork/Makefile" found="0"/&gt; </code></pre> <p>I want to use <code>xml.etree</code> to search on more than one attribute:</p> <pre><code>result = tree.search('.//op[@type...
1
2016-07-26T21:06:19Z
38,599,908
<p>You can use multiple square brackets in succession</p> <pre><code>'.//op[@type="create"][@file="/some/path"]' </code></pre> <p><strong>UPDATE</strong>: I see that you are using python's <code>xml.etree</code> module. I am not sure if the above answer is valid for that module (It has extremely limited support for X...
1
2016-07-26T21:08:51Z
[ "python", "xml" ]
Custom wrapper for containers implementing __iter__ and __getitem__
38,599,902
<p>I'm trying to write a custom wrapper class for containers. To implement the iterator-prototocol I provide <code>__iter__</code> and <code>__next__</code> and to access individual items I provide <code>__getitem__</code>:</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import absolute_import...
1
2016-07-26T21:08:20Z
38,600,431
<p>Your container is its own iterator, which limits it greatly. You can only iterate each container once, after that, it is considered "empty" as far as the iteration protocol goes.</p> <p>Try this with your code to see:</p> <pre><code>c = MyContainer([1,2,3]) l1 = list(c) # the list constructor will call iter on its...
1
2016-07-26T21:48:03Z
[ "python", "numpy" ]
Index must be called with a collection of some kind: assign column name to dataframe
38,599,912
<p>I have <code>reweightTarget</code> as follows and I want to convert it to a pandas Dataframe. However, I got following error:</p> <blockquote> <p>TypeError: Index(...) must be called with a collection of some kind, 't' was passed</p> </blockquote> <p>If I remove <code>columns='t'</code>, it works fine. Can any...
0
2016-07-26T21:09:12Z
38,614,231
<p>Documentation: <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html</a></p> <blockquote> <p>columns : <strong>Index or array-like</strong> </p> <p>Column labels to use for resulting fra...
1
2016-07-27T13:22:19Z
[ "python", "pandas", "dataframe" ]
when I pip install, my packages are going in my macs local library
38,599,918
<p>when I pip install a package it gets insalled on my macs library. I am using pycharm whih allows me to click on a package like a hyperlink. And instead of going to my site-packages in my virtualenv it's going to my macs library which is</p> <pre><code>/Library/Frameworks/Python.Framework/Versions/3.5/lib/python3.5/...
0
2016-07-26T21:09:36Z
38,600,050
<p>I think you want to create a virtual environment for your project.</p> <p>Install this tool virtualenv.</p> <p><code>$ pip install virtualenv</code></p> <p>Then create your project's folder</p> <p><code>$ cd my_project_folder</code> <code>$ virtualenv venv</code></p> <p>This creates a copy of Python in whicheve...
0
2016-07-26T21:19:43Z
[ "python", "osx", "pip" ]
when I pip install, my packages are going in my macs local library
38,599,918
<p>when I pip install a package it gets insalled on my macs library. I am using pycharm whih allows me to click on a package like a hyperlink. And instead of going to my site-packages in my virtualenv it's going to my macs library which is</p> <pre><code>/Library/Frameworks/Python.Framework/Versions/3.5/lib/python3.5/...
0
2016-07-26T21:09:36Z
38,600,167
<p>You should install your virtual environment and then run pip within that environment. So, for example, I use Anaconda (which I thoroughly recommend if you are installing alot of scientific libraries). </p> <p>To activate the environment "hle" I type in:</p> <pre><code>source /Users/admin/.conda/envs/hle/bin/activa...
0
2016-07-26T21:27:48Z
[ "python", "osx", "pip" ]
when I pip install, my packages are going in my macs local library
38,599,918
<p>when I pip install a package it gets insalled on my macs library. I am using pycharm whih allows me to click on a package like a hyperlink. And instead of going to my site-packages in my virtualenv it's going to my macs library which is</p> <pre><code>/Library/Frameworks/Python.Framework/Versions/3.5/lib/python3.5/...
0
2016-07-26T21:09:36Z
38,600,235
<p>You should activate your virtual environment to install packages on that. In Pycharm you can do it like this:</p> <p>Go to <code>File</code> > <code>Settings</code> > <code>Project</code> > <code>Project Interpreter</code></p> <p>Now you have to select the interpreter for this project. Browse or select the interpr...
1
2016-07-26T21:31:52Z
[ "python", "osx", "pip" ]
Iterate through pandas rows efficiently
38,599,952
<p>I have a list that looks like this:</p> <pre><code>lst = ['a','b','c'] </code></pre> <p>and a dataframe that looks like this:</p> <pre><code>id col1 1 ['a','c'] 2 ['b'] 3 ['b', 'a'] </code></pre> <p>I am looking to create a new column in the dataframe that has the length of the intersection of the lst and...
2
2016-07-26T21:11:48Z
38,600,073
<p>Have you tried this?</p> <pre><code>lstset = set(lst) df['intersection'] = df['col1'].apply(lambda x: len(set(x).intersection(lstset))) </code></pre> <p>Another possibility is</p> <pre><code>df['intersection'] = df['col1'].apply(lambda x: len([1 for item in x if item in lst])) </code></pre>
3
2016-07-26T21:21:09Z
[ "python", "pandas", "set" ]
How to extract index/column/data from Pandas DataFrame Based on logic operation?
38,599,987
<p>I have the following dataframe:</p> <pre><code>import numpy as np import pandas as pd data = np.random.rand(5,5) df = pd.DataFrame(data, index = list('abcde'), columns = list('ABCDE')) df = df[df&gt;0] df A B C D E a NaN 2.038740 1.371158 NaN NaN b 0.575567 N...
2
2016-07-26T21:13:52Z
38,600,180
<p>You can stack the data frame, which will drop NA values automatically and then reset the index to be columns, after which it will be easy to convert to a list of tuples:</p> <pre><code>[tuple(r) for r in df.stack().reset_index().values] # [('a', 'B', 2.03874), # ('a', 'C', 1.371158), # ('b', 'A', 0.575567), # (...
4
2016-07-26T21:28:29Z
[ "python", "pandas", "dataframe" ]
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet launching debug on pycharm
38,600,097
<p>I've a Django (version 1.9) application running with python 2.7.10 and i'm using Virtualenv. Running the application with <code>./manage.py runserver</code> i've no error, but when i try to run in debug i got <code>django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.</code> </p> <p>Here it is the pyc...
0
2016-07-26T21:23:05Z
38,615,663
<p>Try to add you settings file to system <code>PATH</code>. In my projects settings are in the folder /project_name/project_name/settings/development.py (that is slightly different from standard way). And in my case Evironment variables string is </p> <p><code>DJANGO_SETTINGS_MODULE=project_name.settings.development;...
0
2016-07-27T14:20:51Z
[ "python", "django", "virtualenv" ]
Error while Running POX controller script using Python 3.5.1
38,600,144
<p>I have written a POX controller script for my research and it is working great under <code>Python 2.7</code> interpreter (Using PyCharm IDE). However, when I choose <code>Python 3.5.1</code>, I get the following error:</p> <pre><code>/usr/bin/python3.5 /home/XXX/pox/pox.py openflow.discovery my_controller Traceback...
0
2016-07-26T21:26:22Z
38,676,610
<p>I have the same problem with Python 3.X.</p> <p>POX requires Python 2.7 according to the documentation <a href="https://github.com/noxrepo/pox" rel="nofollow">POX Readme</a>, <a href="https://openflow.stanford.edu/display/ONL/POX+Wiki#POXWiki-DoesPOXsupportPython3%3F" rel="nofollow">POX Wiki: Does POX support Pytho...
0
2016-07-30T17:26:53Z
[ "python", "python-3.x", "pycharm", "sdn", "pox" ]
Python inheriting docstring errors 'read only'
38,600,186
<p>I have read all the other posts here about this topic but since most of them are quite old I feel better to open a new one with my own problem, since the solutions proposed there don't work for me but I have not seen any complaint in the comments.</p> <p>For instance the solution proposed <a href="http://stackoverf...
1
2016-07-26T21:28:58Z
38,602,787
<p>Using the now fixed version of the <a href="http://stackoverflow.com/a/8101118/190597">DocStringInheritor</a> metaclass,</p> <pre><code>class DocStringInheritor(type): """ A variation on http://groups.google.com/group/comp.lang.python/msg/26f7b4fcb4d66c95 by Paul McGuire """ def __new__(meta...
1
2016-07-27T02:35:51Z
[ "python", "python-2.7", "python-decorators" ]
Line printing in Python
38,600,216
<p>This exercise is from chapter 20 of Zed Shaw's book.</p> <p>I am trying to understand a behavior of line number.</p> <p>When I use the following code, the line number from the text file gets printed as 4, which is wrong. It is in the 3rd line.</p> <pre><code>current_line += current_line </code></pre> <p>However,...
3
2016-07-26T21:30:34Z
38,600,272
<p>current_line += current_line expands out to</p> <pre><code>current_line = current_line + current_line </code></pre> <p>So lets take a look at what you did, by expanding it out (We will ignore the print statements).</p> <pre><code>current_line = 1 current_line = current_line + current_line # (1 + 1 = 2) #current_l...
2
2016-07-26T21:34:15Z
[ "python", "line-numbers" ]
Line printing in Python
38,600,216
<p>This exercise is from chapter 20 of Zed Shaw's book.</p> <p>I am trying to understand a behavior of line number.</p> <p>When I use the following code, the line number from the text file gets printed as 4, which is wrong. It is in the 3rd line.</p> <pre><code>current_line += current_line </code></pre> <p>However,...
3
2016-07-26T21:30:34Z
38,600,314
<p>You're not increasing the value of of <code>current_line</code> by a constant factor of 1, instead you're increasing by a <em>geometric progression</em>.</p> <p><code>current_line += current_line</code> assigns the value of <code>current_line</code> to be itself <code>+</code> itself:</p> <pre><code>current_line =...
1
2016-07-26T21:37:21Z
[ "python", "line-numbers" ]
Formatting string into datetime using Pandas - trouble with directives
38,600,300
<p>I have a string that is the full year followed by the ISO week of the year (so some years have 53 weeks, because the week counting starts at the first full week of the year). I want to convert it to a <code>datetime</code> object using <code>pandas.to_datetime()</code>. So I do:</p> <pre><code>pandas.to_datetime('2...
4
2016-07-26T21:36:31Z
38,600,540
<p>I think that the following question would be useful to you: <a href="http://stackoverflow.com/questions/304256/whats-the-best-way-to-find-the-inverse-of-datetime-isocalendar">Reversing date.isocalender()</a></p> <p>Using the functions provided in that question this is how I would proceed:</p> <pre><code>import dat...
2
2016-07-26T21:57:31Z
[ "python", "string", "date", "datetime", "pandas" ]
Python Power set , can't figure out my error
38,600,315
<p>My code will crash and run forever:</p> <pre><code>def subsets(nums): """ :type nums: List[int] :rtype: List[List[int]] """ results = [[]] for num in nums: for result in results: results.extend([result + [num]]) return results </code></pre> <p>While I googled, and f...
0
2016-07-26T21:37:22Z
38,600,410
<p>The critical part is this:</p> <pre><code>for result in results: results.extend([result + [num]]) </code></pre> <p>Here, you are iterating over the <code>results</code> list. An iterator is always something living, that does not finish until you actually reached the end. For lists, you can simply imagine this ...
4
2016-07-26T21:46:01Z
[ "python", "powerset" ]
How to URL encode Chinese characters?
38,600,436
<p>I used the following code to encode parameters list:</p> <pre><code>params['username'] = user params['q'] = q params = urllib.quote(params) </code></pre> <p>But it doesn't work when <code>q</code> is equal to <code>香港</code>. The following error is returned:</p> <pre><code>'ascii' codec can't encode character...
1
2016-07-26T21:48:41Z
38,604,877
<p>It seems that you're working on Python 2+.</p> <p>Cause your question isn't clear enough, I offer a normal way to solve it.</p> <p>Here's two advice to fix it:</p> <ul> <li>add <code># -*- coding: utf-8 -*-</code> before your file</li> <li>encode Chinese characters to utf-8</li> </ul> <p>Here's example:</p> <pr...
1
2016-07-27T06:02:23Z
[ "python", "urlencode", "chinese-locale" ]
Combination of two lists while keeping the order
38,600,453
<p>I'm trying to join two lists and output all possible combinations of the merged list that maintains the ordering of the original two lists. For example:</p> <pre><code>list_1 = [9,8] list_2 = [2,1] #output combo= [9821,9281,2981,2918,2198,9218] </code></pre> <p>where in each element in the list "combo", <strong>2...
9
2016-07-26T21:50:11Z
38,600,652
<p>Give this a try:</p> <pre><code>import itertools lst1 = ['a', 'b'] lst2 = [1, 2] for locations in itertools.combinations(range(len(lst1) + len(lst2)), len(lst2)): result = lst1[:] for location, element in zip(locations, lst2): result.insert(location, element) print(''.join(map(str, result))) ...
4
2016-07-26T22:07:51Z
[ "python", "combinations", "permutation", "itertools" ]
Combination of two lists while keeping the order
38,600,453
<p>I'm trying to join two lists and output all possible combinations of the merged list that maintains the ordering of the original two lists. For example:</p> <pre><code>list_1 = [9,8] list_2 = [2,1] #output combo= [9821,9281,2981,2918,2198,9218] </code></pre> <p>where in each element in the list "combo", <strong>2...
9
2016-07-26T21:50:11Z
38,600,753
<p>I don't know more about python but I have an idea may help.<br> The idea is using the recursive:<br> To join two lists n &amp; m items, we have two cases:</p> <ul> <li>Join two lists n-1 &amp; m items, then put the n-th items at the end.</li> <li>Join two lists n &amp; m-1 items, then put the m-th items at the end...
1
2016-07-26T22:15:22Z
[ "python", "combinations", "permutation", "itertools" ]
Combination of two lists while keeping the order
38,600,453
<p>I'm trying to join two lists and output all possible combinations of the merged list that maintains the ordering of the original two lists. For example:</p> <pre><code>list_1 = [9,8] list_2 = [2,1] #output combo= [9821,9281,2981,2918,2198,9218] </code></pre> <p>where in each element in the list "combo", <strong>2...
9
2016-07-26T21:50:11Z
38,601,070
<p>A solution using a recursive generator (requires Python 3 for <code>yield from ...</code>):</p> <pre><code>def f(a,b,p=[]): if len(a)==0 or len(b)==0: yield p+a+b else: yield from f(a[1:],b,p+[a[0]]) yield from f(a,b[1:],p+[b[0]]) </code></pre> <p>at each step, you can pick the firs...
2
2016-07-26T22:46:53Z
[ "python", "combinations", "permutation", "itertools" ]
Combination of two lists while keeping the order
38,600,453
<p>I'm trying to join two lists and output all possible combinations of the merged list that maintains the ordering of the original two lists. For example:</p> <pre><code>list_1 = [9,8] list_2 = [2,1] #output combo= [9821,9281,2981,2918,2198,9218] </code></pre> <p>where in each element in the list "combo", <strong>2...
9
2016-07-26T21:50:11Z
38,601,112
<p>Long(ish) one-liner</p> <pre><code>from itertools import * from copy import deepcopy list({''.join(str(l.pop(0)) for l in deepcopy(p)) for p in permutations(chain(repeat(list_1, len(list_1)), repeat(list_2, len(list_2))))}) </code></pre> <p>See my answer to the similar problem <a href="http://stackoverflow.com/qu...
1
2016-07-26T22:50:40Z
[ "python", "combinations", "permutation", "itertools" ]
Combination of two lists while keeping the order
38,600,453
<p>I'm trying to join two lists and output all possible combinations of the merged list that maintains the ordering of the original two lists. For example:</p> <pre><code>list_1 = [9,8] list_2 = [2,1] #output combo= [9821,9281,2981,2918,2198,9218] </code></pre> <p>where in each element in the list "combo", <strong>2...
9
2016-07-26T21:50:11Z
38,601,116
<p>It would be a bit cleaner if your output was a list of lists instead of concatenated digits, but it doesn't matter. Here's a simple recursive solution in python3 (but you can trivially convert it to python2).</p> <pre><code>def combine(xs, ys): if xs == []: return [ys] if ys == []: return [xs] x, *xs_ta...
3
2016-07-26T22:51:00Z
[ "python", "combinations", "permutation", "itertools" ]
code to regenerate a dataframe in pandas for Stackoverflow/SO questions
38,600,508
<p>Lets say I have the following dataframe. I want to ask a question on Stackoverflow/SO regarding a type of manipulation I am trying to do. Now, to help users on SO its generally best practice to supply the code to regenerate the dataframe in question.</p> <pre><code> sunlight sum ...
2
2016-07-26T21:54:42Z
38,600,809
<p>Use <code>to_dict()</code></p> <p>Let's say you have this <code>df</code></p> <pre><code>df = pd.DataFrame(np.arange(16).reshape(4, 4), list('abcd'), pd.MultiIndex.from_product([list('AB'), ['One', 'Two']])) df </code></pre> <p><a href="http://i.stack.imgur.com/0Jsjf.png" rel="nofollow"><img src...
4
2016-07-26T22:21:57Z
[ "python", "pandas" ]
How to open a Popup window which contains a graph written in javascript?
38,600,514
<p>I am using Django to implement a website and I would like to add a button such that when someone clicks it, it would open a Popup window which contains a graph written in javascript. And since I am writing the website in Django, I need to call a function in views.py to get the updated data and then draw the graph ba...
0
2016-07-26T21:55:11Z
38,600,858
<p>It's completely possible using bootstrap modals, here's documentation about it : <a href="http://www.w3schools.com/bootstrap/bootstrap_modal.asp" rel="nofollow">http://www.w3schools.com/bootstrap/bootstrap_modal.asp</a></p> <p>And a sample code :</p> <pre><code>&lt;div class="modal fade" id="id_you_want_for_modal"...
0
2016-07-26T22:26:09Z
[ "javascript", "jquery", "python", "html", "django" ]
How to open a Popup window which contains a graph written in javascript?
38,600,514
<p>I am using Django to implement a website and I would like to add a button such that when someone clicks it, it would open a Popup window which contains a graph written in javascript. And since I am writing the website in Django, I need to call a function in views.py to get the updated data and then draw the graph ba...
0
2016-07-26T21:55:11Z
38,605,945
<p>There can be two ways of performing the task that you want. Here are the methods.</p> <p><strong>Version 1 (The synchronous way)</strong><br> Suppose you have a url say <code>/x/</code> which opens <code>main.html</code>. So you can add whatever data, graph needs to the <code>context</code> on a <code>GET</code> c...
1
2016-07-27T07:03:43Z
[ "javascript", "jquery", "python", "html", "django" ]
Loop over list of dictionaries and within list values
38,600,591
<p>Suppose I have a list of two dictionaries:</p> <pre><code>iter_list = [{0: [2, 1, 3], 1: [3, 2, 1], 2: [1, 2, 3], 3: [2, 3, 1], 4: [1, 2, 3], 5: [2, 3, 1]}, {0: [2, 3, 1], 1: [1, 2, 3], 2: [1, 2, 3]...
0
2016-07-26T22:02:03Z
38,600,663
<p>If I understand you correctly, in your case, you need to iterate the iter_list 3 times</p> <pre><code>&gt;&gt;&gt; for i in iter_list: ... for x in range(3): ... for key, value in i.iteritems(): ... print key, value[x] ... </code></pre> <p>Output:</p> <pre><code>0 2 1 3 2 1 3 2 4 1 5 2 0 1...
5
2016-07-26T22:08:48Z
[ "python", "python-2.7" ]
Loop over list of dictionaries and within list values
38,600,591
<p>Suppose I have a list of two dictionaries:</p> <pre><code>iter_list = [{0: [2, 1, 3], 1: [3, 2, 1], 2: [1, 2, 3], 3: [2, 3, 1], 4: [1, 2, 3], 5: [2, 3, 1]}, {0: [2, 3, 1], 1: [1, 2, 3], 2: [1, 2, 3]...
0
2016-07-26T22:02:03Z
38,600,694
<p>A list comprehension should do:</p> <pre><code>&gt;&gt;&gt; output_list = [[k, d[k][i]] for d in iter_list for i in range(3) for k in sorted(d)]: &gt;&gt;&gt; for k, dki in output_list: ... print k, dki ... 0 2 1 3 2 1 3 2 4 1 5 2 0 1 1 2 2 2 3 3 4 2 5 3 0 3 1 1 2 3 3 1 4 3 5 1 0 2 1 1 2 1 3 1 4 2 5 1 0 3 1 2 ...
1
2016-07-26T22:10:18Z
[ "python", "python-2.7" ]
Loop over list of dictionaries and within list values
38,600,591
<p>Suppose I have a list of two dictionaries:</p> <pre><code>iter_list = [{0: [2, 1, 3], 1: [3, 2, 1], 2: [1, 2, 3], 3: [2, 3, 1], 4: [1, 2, 3], 5: [2, 3, 1]}, {0: [2, 3, 1], 1: [1, 2, 3], 2: [1, 2, 3]...
0
2016-07-26T22:02:03Z
38,600,789
<p>perhaps you want to do this:</p> <pre><code>for i in iter_list: for j in range(3): for key, value in i.iteritems(): print key, value[j] </code></pre> <p>assuming the values in the dictionaries have a fixed length of 3, otherwise you have to figure out where 3 comes from. For example, it cou...
1
2016-07-26T22:19:03Z
[ "python", "python-2.7" ]
Loop over list of dictionaries and within list values
38,600,591
<p>Suppose I have a list of two dictionaries:</p> <pre><code>iter_list = [{0: [2, 1, 3], 1: [3, 2, 1], 2: [1, 2, 3], 3: [2, 3, 1], 4: [1, 2, 3], 5: [2, 3, 1]}, {0: [2, 3, 1], 1: [1, 2, 3], 2: [1, 2, 3]...
0
2016-07-26T22:02:03Z
38,600,868
<p>A different approach using <a href="https://docs.python.org/2.7/library/functions.html#zip" rel="nofollow"><code>zip</code></a> and <a href="https://docs.python.org/2.7/library/itertools.html#itertools.chain" rel="nofollow"><code>itertools.chain</code></a> and <a href="https://docs.python.org/2.7/tutorial/controlflo...
2
2016-07-26T22:27:10Z
[ "python", "python-2.7" ]
Names features importance plot after preprocessing
38,600,813
<p>Before building a model I make scaling like this</p> <pre><code>X = StandardScaler(with_mean = 0, with_std = 1).fit_transform(X) </code></pre> <p>and after build a features importance plot </p> <pre><code>xgb.plot_importance(bst, color='red') plt.title('importance', fontsize = 20) plt.yticks(fontsize = 10) plt.yl...
0
2016-07-26T22:22:14Z
38,616,018
<p>first we get list of feature names before preprocessing </p> <pre><code>dtrain = xgb.DMatrix( X, label=y) dtrain.feature_names </code></pre> <p>Then</p> <pre><code>bst.get_fscore() mapper = {'f{0}'.format(i): v for i, v in enumerate(dtrain.feature_names)} mapped = {mapper[k]: v for k, v in bst.get_fscore().items(...
0
2016-07-27T14:34:24Z
[ "python", "xgboost" ]
incorrect camera pose from two-view SFM
38,600,871
<p>In order to validate results of two-view SFM approach for estimating camera pose [R|t], I made use of the chessboard patterns which I used for calibration, especially that "calibrateCamera" function in OpenCV returns rotation and translation vectors for each pattern. And hence, relative pose between let's say the fi...
2
2016-07-26T22:27:29Z
38,615,754
<p>Your problem is that you are using the points from the chessboard: you cannot estimate the Fundamental matrix from coplanar points. One way to fix this is to match scene points using a generic approach, like SIFT or SURF. The other way is to estimate the Essential matrix directly using the 5-point algorithm, because...
0
2016-07-27T14:24:14Z
[ "python", "opencv", "computer-vision", "structure-from-motion" ]
How to serialize pyspark GroupedData object?
38,600,908
<p>I am running a <code>groupBy()</code> on a dataset having several millions of records and want to save the resulting output (a pyspark <code>GroupedData</code> object) so that I can de-serialize it later and resume from that point (running aggregations on top of that as needed).</p> <pre><code>df.groupBy("geo_city"...
1
2016-07-26T22:31:59Z
38,601,071
<p>There is none because <code>GroupedData</code> is not really a thing. It doesn't perform any operations on data at all. It only describes how actual aggregation should proceed when you execute an action on the results of a subsequent <code>agg</code>.</p> <p>You could probably serialize underlaying JVM object and r...
2
2016-07-26T22:47:01Z
[ "python", "apache-spark", "pyspark", "spark-dataframe", "pyspark-sql" ]
In Django, how to get all instances of a model where an instance of another model related to the first by fk does not exist?
38,600,932
<p>This is really tricky to me. I have the following models:</p> <pre><code>class Item(models.Model): title = models.CharField(max_length=150) item_type = models.CharField(choices=item_choices) class Suggestion(models.Model): user = models.ForeignKey(User) item = models.ForeignKey(Item) </code...
0
2016-07-26T22:34:35Z
38,600,990
<p>One approach is to create a queryset of items with suggestions related to the user, then use that as a subquery.</p> <pre><code>items_suggested_by_user = Item.objects.filter(suggestion__user=user) item_types = Item.objects.filter(item_type=item_type) items = item_types.exclude(item__in=items_suggested_by_user) </co...
1
2016-07-26T22:39:58Z
[ "python", "django" ]
In Django, how to get all instances of a model where an instance of another model related to the first by fk does not exist?
38,600,932
<p>This is really tricky to me. I have the following models:</p> <pre><code>class Item(models.Model): title = models.CharField(max_length=150) item_type = models.CharField(choices=item_choices) class Suggestion(models.Model): user = models.ForeignKey(User) item = models.ForeignKey(Item) </code...
0
2016-07-26T22:34:35Z
38,600,999
<p>This can be done with <code>.exclude()</code>:</p> <pre><code>items = Item.objects.filter(item_type=item_type).exclude(suggestion__user=user) </code></pre> <p>This follows the backwards relation to <code>Suggestion</code>, and the forward relation to <code>User</code>, and excludes any <code>Item</code>s where the...
2
2016-07-26T22:40:43Z
[ "python", "django" ]
Inherit property getter documentation
38,600,933
<p>The decorator proposed <a href="http://stackoverflow.com/a/8101598/551045">here</a> is able to inherit the docstring for methods but not for properties and getters.</p> <p>I have tried to naively expand it but it seems that docstrings of properties are read-only. Is there any way to inherit those?</p> <pre><code>i...
1
2016-07-26T22:34:37Z
38,600,995
<p>Yeah, property docstrings are read-only. You'd have to make a new property:</p> <pre><code>replacement = property(fget=original.fget, fset=original.fset, fdel=original.fdel, __doc__=parentprop.__doc__) </code></pre> <p>and replace the original wi...
0
2016-07-26T22:40:22Z
[ "python", "python-decorators" ]
Inherit property getter documentation
38,600,933
<p>The decorator proposed <a href="http://stackoverflow.com/a/8101598/551045">here</a> is able to inherit the docstring for methods but not for properties and getters.</p> <p>I have tried to naively expand it but it seems that docstrings of properties are read-only. Is there any way to inherit those?</p> <pre><code>i...
1
2016-07-26T22:34:37Z
38,601,305
<p>This version supports multiple inheritance and copying the documentation from a base's base by using <code>__mro__</code> instead of <code>__bases__</code>.</p> <pre><code>def fix_docs(cls): """ This will copy all the missing documentation for methods from the parent classes. :param type cls: class to ...
0
2016-07-26T23:10:51Z
[ "python", "python-decorators" ]
How can i run deepdream on android
38,600,982
<p>How can I run Google deep dream on android? Can I execute the phython script or do I need to port it to java for performance reasons?</p>
0
2016-07-26T22:38:50Z
39,757,493
<p>Short answer is no.</p> <p>Google deepdream is an iPython notebook with dependencies on caffe which itself has several dependencies. </p> <p>There is however no reason why someone couldn't develop a similar tool for Android. There is an app called dreamscope for producing these kinds of images that is available fo...
0
2016-09-28T20:55:50Z
[ "java", "android", "python" ]
Python: I have pandas dataframe which has the same column name. How to change one of those?
38,601,014
<p>I have pandas dataframe which has the same column names. (column names are a,b,a,a,a) Below is example.</p> <p><a href="http://i.stack.imgur.com/wYLzJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/wYLzJ.png" alt="enter image description here"></a></p> <p>Is there any way I can change column name only for ...
2
2016-07-26T22:42:33Z
38,601,198
<p>Does this work?:</p> <pre><code>column_names = df.columns.values column_names[2] = 'Changed' df.columns = column_names </code></pre>
1
2016-07-26T22:58:28Z
[ "python", "pandas", "dataframe", "rename" ]
Python: I have pandas dataframe which has the same column name. How to change one of those?
38,601,014
<p>I have pandas dataframe which has the same column names. (column names are a,b,a,a,a) Below is example.</p> <p><a href="http://i.stack.imgur.com/wYLzJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/wYLzJ.png" alt="enter image description here"></a></p> <p>Is there any way I can change column name only for ...
2
2016-07-26T22:42:33Z
38,602,453
<p>df.rename(inplace=True,columns={'3col':'Changed'})</p>
0
2016-07-27T01:52:34Z
[ "python", "pandas", "dataframe", "rename" ]
Easy way to use parallel options of scikit-learn functions on HPC
38,601,026
<p>In many functions from scikit-learn implemented user-friendly parallelization. For example in <code>sklearn.cross_validation.cross_val_score</code> you just pass desired number of computational jobs in <code>n_jobs</code> argument. And for PC with multi-core processor it will work very nice. But if I want use such...
9
2016-07-26T22:43:34Z
38,814,491
<p>SKLearn manages its parallelism with <a href="https://pythonhosted.org/joblib/" rel="nofollow">Joblib</a>. Joblib can swap out the multiprocessing backend for other distributed systems like <a href="http://distributed.readthedocs.io/en/latest/" rel="nofollow">dask.distributed</a> or <a href="https://ipython.org/ipy...
3
2016-08-07T13:11:15Z
[ "python", "parallel-processing", "scikit-learn", "multiprocessing", "cluster-computing" ]
Class that takes another class as argument, copies behavior
38,601,052
<p>I'd like to create a class in Python that takes a single argument in the constructor, another Python class. The instance of the Copy class should have all the attributes and methods of the original class, without knowing what they should be beforehand. Here's some code that almost works:</p> <pre><code>import copy ...
0
2016-07-26T22:45:13Z
38,601,169
<p>I am unsure why you would wish to do this, but you probably have your reasons.</p> <p>You can leverage off normal inheritance:</p> <p>eg:</p> <pre><code> class A(object): l = 'a' class C(object): l = 'c' def createClass(cls): class B(cls): pass return B ...
1
2016-07-26T22:56:28Z
[ "python", "class", "oop", "inheritance", "metaclass" ]
Class that takes another class as argument, copies behavior
38,601,052
<p>I'd like to create a class in Python that takes a single argument in the constructor, another Python class. The instance of the Copy class should have all the attributes and methods of the original class, without knowing what they should be beforehand. Here's some code that almost works:</p> <pre><code>import copy ...
0
2016-07-26T22:45:13Z
38,601,263
<p>You need to copy the <code>__dict__</code>:</p> <pre><code>import copy class A(): l = 'a' class Copy(): def __init__(self, original_class): self.__dict__ = copy.deepcopy(original_class.__dict__) print(self.l) c = Copy(A) # -&gt; a print(c.l) # -&gt; a </code></pre>
1
2016-07-26T23:05:51Z
[ "python", "class", "oop", "inheritance", "metaclass" ]
Class that takes another class as argument, copies behavior
38,601,052
<p>I'd like to create a class in Python that takes a single argument in the constructor, another Python class. The instance of the Copy class should have all the attributes and methods of the original class, without knowing what they should be beforehand. Here's some code that almost works:</p> <pre><code>import copy ...
0
2016-07-26T22:45:13Z
38,601,499
<p>This is an interesting question to point out a pretty cool feature of Python's pass-by-value semantics, as it is intimately tied to why your original code doesn't work correctly and why @martineau's solution works well.</p> <h2>Why Your Code As Written Doesn't Work</h2> <p>Python doesn't support pure pass-by-refer...
1
2016-07-26T23:35:31Z
[ "python", "class", "oop", "inheritance", "metaclass" ]
Is it possible to get_attribute() from several elements with the same name?
38,601,055
<p>I have a lot of list elements with the same class name but with different id. </p> <p>Example:</p> <pre><code>&lt;li class="test class" id="111-11-111"&gt; pass &lt;/li&gt; &lt;li class="test class" id="222-22-222"&gt; pass &lt;/li&gt; &lt;li class="test class" id="333-33-333"&gt; pass &lt;/li&gt; </code></pre> <...
2
2016-07-26T22:45:53Z
38,601,128
<p>you can use xpath:</p> <pre><code>listOfLi = driver.find_elements_by_xpath("//li[class='test class']") </code></pre> <p>or css selector:</p> <pre><code>listOfLi = driver.find_elements_by_css_selector(".test.class") </code></pre> <p>you can access each li element by indexing them one by one:</p> <pre><code>for e...
3
2016-07-26T22:51:56Z
[ "python", "selenium", "selenium-webdriver" ]
Append to array for each item of a loop
38,601,075
<p>With the following code:</p> <pre><code>class Calendar_Data(Resource): def get(self): result = [] details_array = [] # Times are converted to seconds for day in life.days: for span in day.spans: if type(span.place) is str: details = { 'name': span.place, ...
0
2016-07-26T22:47:26Z
38,601,361
<p>You aren't redeclaring your list (Python has lists not arrays) in between each loop. You need to move the creation of your <code>details_array</code> inside one of the loops so it is recreated as empty. You'll likely wnt it to look like this:</p> <pre><code>for day in life.days: details_array = [] for span ...
1
2016-07-26T23:18:11Z
[ "python", "arrays", "loops" ]
Python does not recognize subclass unless it's imported in __init__.py
38,601,088
<p>I have a project with multiple sub-folders, most of which are Python packages. One of them contains an abstract class called BaseStep (created using the <code>abc</code> module), which during runtime looks for subclasses of itself using: <code>for subclass in cls.__subclasses__(): ...</code>. <code>BaseStep</code> i...
0
2016-07-26T22:47:55Z
38,601,109
<p>The <code>SampleStep</code> subclass <strong>does not exist</strong> until its file is imported.</p>
2
2016-07-26T22:50:24Z
[ "python", "oop", "python-import" ]
Python does not recognize subclass unless it's imported in __init__.py
38,601,088
<p>I have a project with multiple sub-folders, most of which are Python packages. One of them contains an abstract class called BaseStep (created using the <code>abc</code> module), which during runtime looks for subclasses of itself using: <code>for subclass in cls.__subclasses__(): ...</code>. <code>BaseStep</code> i...
0
2016-07-26T22:47:55Z
38,601,149
<p>Python is a dynamic language. Things like class definitions technically happen at runtime, not some earlier compile time as in other languages like C and Java. This means that until you import your <code>sample_step</code> module and run definition of its <code>SampleStep</code> class, that class doesn't exist as fa...
3
2016-07-26T22:53:57Z
[ "python", "oop", "python-import" ]
How to improve scapy performance reading large files
38,601,091
<p>I have to read and parse .pcap files that are too large to load into memory. I am currently using sniff in offline mode</p> <pre><code>sniff(offline=file_in, prn=customAction, store=0) </code></pre> <p>with a customAction function that looks roughly like this:</p> <pre><code>customAction(packet): global COUN...
2
2016-07-26T22:48:30Z
38,654,715
<p>It seems that scapy causes PyPy's JIT warm-up times to be high, but the JIT is still working if you run for long enough. Here are the results I got (on Linux 64):</p> <pre><code>size of .pcap CPython time PyPy time 2MB 4.9s 7.3s 5MB 15.3s ...
0
2016-07-29T09:02:05Z
[ "python", "performance", "scapy", "pcap", "pypy" ]
How to improve scapy performance reading large files
38,601,091
<p>I have to read and parse .pcap files that are too large to load into memory. I am currently using sniff in offline mode</p> <pre><code>sniff(offline=file_in, prn=customAction, store=0) </code></pre> <p>with a customAction function that looks roughly like this:</p> <pre><code>customAction(packet): global COUN...
2
2016-07-26T22:48:30Z
38,660,456
<p>I think that the short answer is that Scapy is just slow as hell. I tried just scanning a pcap file with sniff() or PcapReader, and not doing anything with the packets. The process was reading less than 3MB/s from my SSD, and the CPU usage was 100%. There are other pcap reader libraries for Python out there. I'd sug...
0
2016-07-29T13:43:58Z
[ "python", "performance", "scapy", "pcap", "pypy" ]
'str' object does not support item assignment (Python)
38,601,139
<pre><code>def remove_char(text): for letter in text[1]: text[0] = text[0].replace(letter," ") return text[0] </code></pre> <p>This is returning:</p> <pre><code>'str' object does not support item assignment </code></pre> <p>Why? And how can I make this work?</p>
0
2016-07-26T22:52:46Z
38,601,176
<p>In Python, strings are not mutable, which means they cannot be changed. You can, however, replace the whole variable with the new version of the string.</p> <p>Example:</p> <pre><code>text = ' ' + text[1:] # replaces first character with space </code></pre>
2
2016-07-26T22:56:51Z
[ "python" ]
'str' object does not support item assignment (Python)
38,601,139
<pre><code>def remove_char(text): for letter in text[1]: text[0] = text[0].replace(letter," ") return text[0] </code></pre> <p>This is returning:</p> <pre><code>'str' object does not support item assignment </code></pre> <p>Why? And how can I make this work?</p>
0
2016-07-26T22:52:46Z
38,601,180
<p>Strings are immutable. By trying:</p> <pre><code>text[0] = text[0].replace(letter," ") </code></pre> <p>you are trying to access the string and change it, which is disallowed due to the string's immutability. Instead, you can use a <code>for</code> loop and some slicing:</p> <pre><code>for i in range(0, len(y)): ...
1
2016-07-26T22:56:58Z
[ "python" ]
'str' object does not support item assignment (Python)
38,601,139
<pre><code>def remove_char(text): for letter in text[1]: text[0] = text[0].replace(letter," ") return text[0] </code></pre> <p>This is returning:</p> <pre><code>'str' object does not support item assignment </code></pre> <p>Why? And how can I make this work?</p>
0
2016-07-26T22:52:46Z
38,602,456
<p>Assuming that the parameter <code>text</code> is a string, the line <code>for letter in text[1]:</code> doesn't make much sense to me since <code>text[1]</code> is a single character. What's the point of iterating over a one-letter string?</p> <p>However, if <code>text</code> is a <strong>list of strings</strong>, ...
0
2016-07-27T01:53:01Z
[ "python" ]
Show multiple paths of equal length in NetworkX
38,601,205
<p>If there are multiple paths from a source to destination, how do I get these ALL of these paths using NetworkX? Note that this is a simplified example, I want to actually be using the nx.all_pairs_shortest_path() function and get all shortest paths between any two nodes.</p> <p>Code:</p> <pre><code>import networkx...
0
2016-07-26T22:59:14Z
38,601,709
<p><code>all_shortest_paths</code> does what you're after, but it is a generator. If you want a list, then put <code>list</code> around it</p> <pre><code>shortest_path_generator = nx.all_shortest_paths(G,0,3) list(shortest_path_generator) </code></pre>
0
2016-07-27T00:00:54Z
[ "python", "networkx", "shortest-path" ]
Run script with arguments via ssh with at command from python script
38,601,256
<p>I have a python program which needs to call a script on a remote system via ssh. </p> <p>This ssh call needs to happen (once) at a specified date which can be done via the linux at command.</p> <p>I am able to call both of these external bash commands using either the <code>os</code> module or the <code>subproces...
0
2016-07-26T23:05:12Z
38,601,355
<p><strong>new answer</strong></p> <p>now that you edited your question you should probably be using format strings</p> <pre><code>cmd = '''ssh {user} "{cmd} '{arg0}' '{arg1}'"'''.format(user="user@remote",cmd="somescript",arg0="hello",arg2="hello world") print cmd </code></pre> <hr> <p><strong>old answer</strong><...
2
2016-07-26T23:17:44Z
[ "python", "bash", "ssh", "at-job" ]
Display a sequence of images with next and previous buttons in python matplotlib
38,601,307
<p>I have a sequence of images that I want to display them one by one and allow the user to navigate between the images using next and previous buttons in matplotlib. Here is my code:</p> <pre><code>fig, ax = plt.subplots() class Index(object): ind = 0 def next(self, event): self.ind += 1 print self.i...
1
2016-07-26T23:11:05Z
38,601,396
<p>Try to call <code>fig.canvas.draw()</code> in the end of functions <code>prev</code> and <code>next</code>, because you need to redraw a plot after loading a new picture.</p> <p>Another problem: your index <code>self.ind</code> may be out of range you do not check it value before <code>imread</code>.</p>
0
2016-07-26T23:21:21Z
[ "python", "matplotlib" ]
run_async_query in Python gcloud BigQuery using Standard SQL instead of Legacy SQL
38,601,331
<p>I need to run an async query using the gcloud python BigQuery library. Furthermore I need to run the query using the beta <a href="https://cloud.google.com/bigquery/sql-reference/" rel="nofollow">standard sql</a> instead of the default <a href="https://cloud.google.com/bigquery/query-reference" rel="nofollow">legac...
0
2016-07-26T23:14:02Z
38,798,887
<p>The <a href="https://github.com/GoogleCloudPlatform/gcloud-python/blob/master/gcloud/bigquery/job.py#L997" rel="nofollow">use_legacy_sql property</a> did not exist as of version 0.17.0, so you'd have needed to check out the current master branch. However it does now exist of as release 0.18.0 so after upgrading gclo...
1
2016-08-05T23:08:24Z
[ "python", "google-bigquery", "gcloud-python", "google-cloud-python" ]
Hibernate a BeagleBone Black
38,601,376
<p>I'm a student, I am a beginner with beaglebones. I have a project and in the project we have a BeagleBone Black connected to a battery and solar panels. It will work autonomously, and the beagle will send datas by the 3G network through an 3G usb. What I want to do is to save as more energy as it's possible. What I...
0
2016-07-26T23:19:23Z
38,619,053
<p>It looks like it might:</p> <p><a href="http://processors.wiki.ti.com/index.php/AM335x_Linux_Power_Management_User_Guide#Suspend_.26_Resume" rel="nofollow">http://processors.wiki.ti.com/index.php/AM335x_Linux_Power_Management_User_Guide#Suspend_.26_Resume</a></p> <p>Although I'm not sure if all of this was properl...
0
2016-07-27T16:56:11Z
[ "python", "sleep", "beagleboneblack" ]
Violent Python - Having trouble with OptParse outputting the correct information
38,601,395
<p>I am working directly from the Violent Python PDF, page 147.</p> <p>I am currently using the pygeoip module to find the location of IP adresses. I was able to do this first step fairly easily and it is represented by the #1 hash in the code.</p> <p>The second step includes taking data from a pcap file and matching...
0
2016-07-26T23:21:16Z
38,601,608
<p>Like viraptor said, separate the exercises into different script files and then try again. Not only were the exercises written to be in separate scripts, it is far easier to find a bug if you have less code to look through (and less code that can potentially go wrong).</p>
1
2016-07-26T23:48:34Z
[ "python", "optparse" ]
What is the point of uWSGI?
38,601,440
<p>I'm looking at the <a href="https://en.wikipedia.org/wiki/Web_Server_Gateway_Interface" rel="nofollow">WSGI specification</a> and I'm trying to figure out how servers like <a href="https://uwsgi-docs.readthedocs.io/en/latest" rel="nofollow">uWSGI</a> fit into the picture. I understand the point of the WSGI spec is t...
0
2016-07-26T23:27:07Z
38,604,388
<p>A traditional web server does not understand or have any way to run Python applications. That's why WSGI server come in. On the other hand Nginx supports reverse proxy to handle requests and pass back responses for Python WSGI servers.</p> <p>This link might help you: <a href="https://www.fullstackpython.com/wsgi-s...
2
2016-07-27T05:27:37Z
[ "python", "nginx", "flask", "wsgi", "uwsgi" ]
What is the point of uWSGI?
38,601,440
<p>I'm looking at the <a href="https://en.wikipedia.org/wiki/Web_Server_Gateway_Interface" rel="nofollow">WSGI specification</a> and I'm trying to figure out how servers like <a href="https://uwsgi-docs.readthedocs.io/en/latest" rel="nofollow">uWSGI</a> fit into the picture. I understand the point of the WSGI spec is t...
0
2016-07-26T23:27:07Z
38,685,758
<p>Okay, I think I get this now. I read the following description in a <a href="https://en.wikipedia.org/wiki/Web_Server_Gateway_Interface" rel="nofollow">Wikipedia artile</a>:</p> <blockquote> <p>Between the server and the application, there may be a WSGI middleware, which implements both sides of the API. The se...
0
2016-07-31T15:54:03Z
[ "python", "nginx", "flask", "wsgi", "uwsgi" ]
Return list of columns in Dataframe that have a specific value as new column
38,601,477
<p>I have a number of columns that have values of either "Yes" or "No" in them. I am hoping to create a function that adds an additional column listing the columns for a specific row that are equal to "Yes". If they are all equal to "No" it would simply return nothing. </p> <p>Example </p> <pre><code>Column 1 Column...
2
2016-07-26T23:32:14Z
38,601,556
<p>Assuming that all of your column names are strings:</p> <pre><code>df['New Column'] = df.apply(lambda row: ', '.join(row.index[row == 'Yes']), axis=1) </code></pre> <p>If you have non-string column names (e.g. an integer) you can do essentially the same thing, but cast the type to string first:</p> <pre><code>df[...
1
2016-07-26T23:42:22Z
[ "python", "pandas" ]
Return list of columns in Dataframe that have a specific value as new column
38,601,477
<p>I have a number of columns that have values of either "Yes" or "No" in them. I am hoping to create a function that adds an additional column listing the columns for a specific row that are equal to "Yes". If they are all equal to "No" it would simply return nothing. </p> <p>Example </p> <pre><code>Column 1 Column...
2
2016-07-26T23:32:14Z
38,601,985
<p>I'd do this:</p> <pre><code>df['New'] = df.apply(lambda x: df.columns[x == 'Yes'].tolist(), axis=1) df </code></pre> <p><a href="http://i.stack.imgur.com/TeA8a.png" rel="nofollow"><img src="http://i.stack.imgur.com/TeA8a.png" alt="enter image description here"></a></p>
1
2016-07-27T00:39:16Z
[ "python", "pandas" ]
How to access kml/xml attributes after filtering in python(lxml)?
38,601,538
<p>I have looked around a bit and can't seem to find a solution to my problem. My underlying problem is that I need to find the name of all KML elements whose child polygons contain points with a given lat/lon. </p> <p>Looking around I found that using keytree, shapely, and lxml I can filter all of the KML elements do...
0
2016-07-26T23:40:55Z
38,601,943
<p>Your target text is not attribute of any element. Given <code>&lt;Polygon&gt;</code> as context element, you want to go to parent element <code>&lt;Placemark&gt;</code> and then get its child element <code>&lt;name&gt;</code>. This can be done in a single line using XPath :</p> <pre><code>.... print hits hit_parent...
1
2016-07-27T00:31:49Z
[ "python", "python-2.7", "xml-parsing", "lxml", "kml" ]
Set specific cell of multi-indexed Pandas DataFrame
38,601,573
<p>I have a DataFrame (df_test) with row labels ('letters') and column names ('numbers') which can be grouped by row labels.</p> <pre><code>&gt;&gt;&gt; letters = ['a','a','a','a','a','b','b','b','c','c','c','c'] &gt;&gt;&gt; n = {'numbers': [0,1,2,3,4,0,1,2,0,1,2,3]} &gt;&gt;&gt; df_test = pd.DataFrame(n, index=lett...
2
2016-07-26T23:44:20Z
38,601,750
<p>write a function to <code>apply</code> with in a <code>groupby</code></p> <pre><code>def first_last_me(df, c='Position'): df[c] = 'M' df.iloc[0, -1] = 'S' df.iloc[-1, -1] = 'E' return df df_test.groupby(level=0).apply(first_last_me) </code></pre> <p><a href="http://i.stack.imgur.com/tvozQ.png" rel...
1
2016-07-27T00:06:09Z
[ "python", "pandas", "dataframe" ]
Set specific cell of multi-indexed Pandas DataFrame
38,601,573
<p>I have a DataFrame (df_test) with row labels ('letters') and column names ('numbers') which can be grouped by row labels.</p> <pre><code>&gt;&gt;&gt; letters = ['a','a','a','a','a','b','b','b','c','c','c','c'] &gt;&gt;&gt; n = {'numbers': [0,1,2,3,4,0,1,2,0,1,2,3]} &gt;&gt;&gt; df_test = pd.DataFrame(n, index=lett...
2
2016-07-26T23:44:20Z
38,621,283
<p>Because @piRSquared's answer didn't work with my DataFrame for reasons still unknown, this is what I ended up going with.</p> <pre><code>&gt;&gt;&gt; letters = ['a','a','a','a','a','b','b','b','c','c','c','c'] &gt;&gt;&gt; n = {'numbers': [0,1,2,3,4,0,1,2,0,1,2,3]} &gt;&gt;&gt; df_test = pd.DataFrame(n, index=lette...
0
2016-07-27T19:09:11Z
[ "python", "pandas", "dataframe" ]
What is the standard docstring for a django model metaclass?
38,601,591
<p>Models in django can come with a meta class like so:</p> <pre><code>class Address(models.Model): """Address model.""" class Meta: """Meta McMetaface.""" verbose_name = "Address" verbose_name_plural = "Addresses" address_line = models.CharField(max_length=256) postcode = mo...
0
2016-07-26T23:46:23Z
38,602,102
<p>There's no point in writing a docstring for Meta. It's a standard name that every model defines, and means the same thing in every model. Just don't write a docstring.</p>
1
2016-07-27T00:58:29Z
[ "python", "django", "metaclass", "pep" ]
Butterworth filter applied on a column of a pandas dataframe
38,601,628
<p>I have a dataframe like this (just much bigger, with smaller step of x):</p> <pre><code> x val1 val2 val3 0 0.0 10.0 NaN NaN 1 0.5 10.5 NaN NaN 2 1.0 11.0 NaN NaN 3 1.5 11.5 NaN 11.60 4 2.0 12.0 NaN 12.08 5 2.5 12.5 12.2 12.56 6 3.0 13.0 19.8 13.04 7 ...
1
2016-07-26T23:50:59Z
38,691,551
<p>The error you are seeing is because you are trying to call the method <code>.diff()</code> on the result of <code>filtfilt</code>, which is a numpy array which doesn't have that method. If you really want to use a first order difference, you can just use <code>np.gradient(smoothed)</code></p> <p>Now, it appears tha...
1
2016-08-01T05:25:47Z
[ "python", "numpy", "pandas", "scipy" ]
Match up/overlap arrays in python
38,601,653
<p>I have two lists, one of integers and one of tuples containing integers as follows (this is an example)</p> <pre><code>firstList = [4, 8, 20, 25, 60, 123] secondList = [(0, 3), (4, 5), (7, 14), (19, 22), (40, 90), (100, 140)] </code></pre> <p>I am wanting to match up (overlap) the first array onto the second array...
-1
2016-07-26T23:54:46Z
38,601,792
<p>Your question isn't fully defined, but here's something that makes sense to me:</p> <pre><code>def binSearch(x, L, low=None, high=None): if low is None: low = 0 if high is None: high = len(L) if low==high: return None mid = int((upper+lower)/2) lower, upper = L[mid] if lower &lt;= x &lt;= ...
0
2016-07-27T00:11:50Z
[ "python", "arrays", "python-3.x" ]
Is there a better way to structure these function calls?
38,601,671
<p>I have a class that needs one of a number of helper classes. It will only ever use one of these helpers, and all of them have the same interface. So I'm writing code like this:</p> <pre><code>if self.type == Class.Type.a: helper = A() elif self.type == Class.Type.b: helper = B() elif self.type == Class.Type...
0
2016-07-26T23:56:12Z
38,601,690
<p>You can indeed use a dictionary:</p> <pre><code>my_dict = {Class.Type.a:A, Class.Type.b:B, Class.Type.c:C} helper = my_dict[self.type]() helper.do_stuff() </code></pre>
1
2016-07-26T23:58:24Z
[ "python" ]
parsing through dict to separate keys and values
38,601,673
<p>I have code that looks through a folder full of tsv files and grabs the name of the file as the key and the column headers as the values in the dict.</p> <pre><code>row1 =[] listdict=[] for f in files: with open(dir_path +'/'+f, 'rU') as file: reader = csv.reader(file) row1 = next(reader) ...
0
2016-07-26T23:56:23Z
38,601,722
<p>You've created a list by doing <code>listdicts = []</code>.</p> <p>Create a dictionary instead: <code>listdicts = {}</code>.</p> <pre><code> listdict={} for f in files: with open(dir_path +'/'+f, 'r') as file: reader = csv.reader(file) listdict[f] = next(reader).split() # split will spl...
0
2016-07-27T00:02:21Z
[ "python" ]
parsing through dict to separate keys and values
38,601,673
<p>I have code that looks through a folder full of tsv files and grabs the name of the file as the key and the column headers as the values in the dict.</p> <pre><code>row1 =[] listdict=[] for f in files: with open(dir_path +'/'+f, 'rU') as file: reader = csv.reader(file) row1 = next(reader) ...
0
2016-07-26T23:56:23Z
38,601,726
<p>You probably want this</p> <pre><code>filedict={} for f in files: with open(dir_path +'/'+f, 'rU') as file: reader = csv.reader(file) row1 = next(reader) filedict[f] = row1 </code></pre>
0
2016-07-27T00:02:51Z
[ "python" ]
parsing through dict to separate keys and values
38,601,673
<p>I have code that looks through a folder full of tsv files and grabs the name of the file as the key and the column headers as the values in the dict.</p> <pre><code>row1 =[] listdict=[] for f in files: with open(dir_path +'/'+f, 'rU') as file: reader = csv.reader(file) row1 = next(reader) ...
0
2016-07-26T23:56:23Z
38,602,036
<p>A <code>list</code> is used when you want an ordered list of elements.</p> <p>A <code>dict</code> is used when you want an unordered set of key-value pairs.</p> <p>If you want to query up file headers by filename (ex. <code>listdict['file_name.tsv']</code>) you will need to use a <code>dict</code>. Additionally, i...
4
2016-07-27T00:47:46Z
[ "python" ]
Maya: Defer a script until after VRay is registered?
38,601,706
<p>I'm trying to delay a part of my pipeline tool (which runs during the startup of Maya) to run after VRay has been registered. </p> <p>I'm currently delaying the initialization of the tool in a userSetup.py like so:</p> <pre><code>def run_my_tool(): import my_tool reload(my_tool) mc.evalDeferred("run_my_t...
0
2016-07-27T00:00:32Z
38,601,804
<p>Uiron over at tech-artists.com showed me how to do this properly. Here's a <a href="http://tech-artists.org/forum/showthread.php?3203-need-help-passing-second-argument-to-event-for-scriptJob-in-maya" rel="nofollow">link to the thread</a></p> <p>Here's the post by uiron:</p> <p>"don't pass the python code as strin...
0
2016-07-27T00:13:48Z
[ "python", "maya" ]
Flask - Cannot commit changes on view
38,601,812
<p>I have this Flask app deployed on a server.</p> <p>Everything works fine except for the views where I need to db.session.commit() anytihing. I've been looking for circular imports and db engine stuff but I can't seem to understand why it doesn't work.</p> <p>Below I post my <strong>init</strong>.py and one of the ...
0
2016-07-27T00:14:38Z
38,628,001
<p>In this case, unfortunately, the real cause of the error is being obscured by the <code>try: except</code> block which suppresses the error and just handles it by returning the failure result.</p> <p>Remove the <code>try: except</code> and you will see the cause of the session commit failure in the crash log that F...
0
2016-07-28T05:49:23Z
[ "python", "flask", "flask-sqlalchemy" ]
What is the quickest way to ensure a specific column is last (or first) in a dataframe
38,601,841
<p>given <code>df</code></p> <pre><code>df = pd.DataFrame(np.arange(8).reshape(2, 4), columns=list('abcd')) </code></pre> <p><a href="http://i.stack.imgur.com/UXlIN.png" rel="nofollow"><img src="http://i.stack.imgur.com/UXlIN.png" alt="enter image description here"></a></p> <p>Suppose I need column <code>'b'</code> ...
3
2016-07-27T00:18:38Z
38,601,975
<p>Well, the first (and, depending on your use case, most efficient) optimization is to ensure at first that you don't have to rearrange the DataSet. If the column you want to be the last one is already in its place, then you can just return the df unchanged. Try this one:</p> <pre><code>def put_me_last2(df, column): ...
3
2016-07-27T00:37:59Z
[ "python", "pandas" ]