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
Secret key is there though it is saying no secret key in django
39,217,362
<p>When i'm running python manage.py runserver or python manage.py migrate. I'm getting these errors</p> <pre><code>Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/mana...
0
2016-08-30T01:07:04Z
39,217,791
<p>From the vanilla <code>settings.py</code> you can specify what settings to do by setting an environment variable to tell settings which to use. For example.</p> <p>Suppose you have an env variable called DJANGO_ENV='prod' then in your settings.py</p> <pre><code>import os environment = os.environ.get('DJANGO_ENV',...
0
2016-08-30T02:13:45Z
[ "python", "django" ]
Secret key is there though it is saying no secret key in django
39,217,362
<p>When i'm running python manage.py runserver or python manage.py migrate. I'm getting these errors</p> <pre><code>Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/mana...
0
2016-08-30T01:07:04Z
39,240,194
<p>You <strong>misspelled</strong> the name of the file.</p> <p>change </p> <pre><code>devlopment.py </code></pre> <p>to </p> <pre><code>development.py </code></pre> <p>and everything should work with calling the file directly</p>
0
2016-08-31T03:17:22Z
[ "python", "django" ]
One out of four radio buttons hidden
39,217,462
<p>I have four sets of radio buttons, each set wrapped in a div called "choiceSet". On firefox for windows I see all four sets of radio buttons. My coworker only sees three sets in firefox. Both of us see only 3/4 sets in chrome. In linux I don't see the offending set of radio buttons regardless of the browser. </p> <...
1
2016-08-30T01:21:16Z
39,218,069
<p>This was pretty interesting :)</p> <p>I was able to reproduce this. The problem is that the second choiceSet has radio buttons with id "advertisement*", which triggers the AdBlockPlus Plugin in chrome and automatically hides that div, acting as a false positive!</p> <p>Here is a small proof:</p> <p><a href="http...
3
2016-08-30T02:52:20Z
[ "python", "html", "css", "django" ]
Updating a 3D graph every n minutes in Python
39,217,485
<p>I have the following code to plot a 3D graph in Python</p> <pre><code>data = # taken from an SQL query in (x, y, z) format # x, y, z = zip(*data) z = map(float, z) grid_x, grid_y = np.mgrid[min(x):max(x):100j, min(y):max(y):100j] grid_z = griddata((x, y), z, (grid_x, grid_y), method='cubic') fig = plt.figure() ax...
0
2016-08-30T01:23:49Z
39,218,368
<p>Try this</p> <pre><code>while True: plt.pause(1) x1,x2,x3=random.uniform(-10,0),random.uniform(0,10),random.uniform(0,0.5) y1,y2,y3=random.uniform(-10,0),random.uniform(0,10),random.uniform(0,0.5) X,Y=np.arange(x1,x2,x3),np.arange(y1,y2,y3) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) ...
0
2016-08-30T03:32:20Z
[ "python", "matplotlib", "plot" ]
Updating a 3D graph every n minutes in Python
39,217,485
<p>I have the following code to plot a 3D graph in Python</p> <pre><code>data = # taken from an SQL query in (x, y, z) format # x, y, z = zip(*data) z = map(float, z) grid_x, grid_y = np.mgrid[min(x):max(x):100j, min(y):max(y):100j] grid_z = griddata((x, y), z, (grid_x, grid_y), method='cubic') fig = plt.figure() ax...
0
2016-08-30T01:23:49Z
39,323,711
<p>After some research I found a way of doing this with matplotlib.animation.</p> <p>The below Youtube link was of great help.</p> <p><a href="https://www.youtube.com/watch?v=7w8jk0r4lxA" rel="nofollow">https://www.youtube.com/watch?v=7w8jk0r4lxA</a></p>
0
2016-09-05T03:55:19Z
[ "python", "matplotlib", "plot" ]
-bash: cd: Resources: No such file or directory
39,217,582
<p>the directory /Library/Frameworks/Python.framework/ contains the following four elements: Headers Python Resources Versions</p> <p>When I try to cd into either Headers, Python or Resources (e.g. cd Resources), I get an error message telling me that the element does not exist (e.g.: "-bash: cd: Resources: No such...
0
2016-08-30T01:39:52Z
39,286,424
<ol> <li>Try to use autocompletion on TAB key press &mdash; maybe names contain some whitespace (less probably)</li> <li>Check <code>ls -l</code> output &mdash; maybe these directories are just broken symbolic links</li> </ol>
0
2016-09-02T07:15:34Z
[ "python", "terminal", "directory" ]
Convert Python dict files into MATLAB struct
39,217,618
<p>I have a function in Python that outputs a dict. I run this function into MATLAB and save the output to a parameter (say <code>tmp</code>) which is a dict of nested other dicts itself. Now I want to convert this file into a useful format such as structure.</p> <p>To elaborate: <code>tmp</code> is a dict. <code>data...
0
2016-08-30T01:45:46Z
39,229,405
<p>So python -> MATLAB is a bit tricky with dictionaries/structs because the type of object that MATLAB is expecting is a dictionary object where each key is a single variable you want from python as a simple data type (array,int, etc). It doesn't like having nested dictionaries. </p> <p>I recommend 1: Store each d...
0
2016-08-30T13:52:06Z
[ "python", "matlab", "dictionary", "struct" ]
Problems with special characters (\r) when writing and reading csv files
39,217,629
<p>I'm using pandas to load csv files created by excel, do some analysis, and then save results to csv files. I've noticed the pandas to_csv and from_csv methods don't seem capable of handling special characters such as \r but don't raise any errors either.</p> <pre><code>In [7]: import pandas as pd In [8]: data = {...
0
2016-08-30T01:49:08Z
39,219,503
<p>Unless someone has a better suggestion, I'm dealing with the specific issue as follows - by pre-processing every csv file before loading with Pandas. It seems to work on my current system but not convinced it's fool proof.</p> <pre><code>In [30]: f = open("my_df.csv") In [31]: content = f.read().replace('\r',' ')...
1
2016-08-30T05:40:48Z
[ "python", "pandas", "special-characters", "export-to-csv" ]
Problems with special characters (\r) when writing and reading csv files
39,217,629
<p>I'm using pandas to load csv files created by excel, do some analysis, and then save results to csv files. I've noticed the pandas to_csv and from_csv methods don't seem capable of handling special characters such as \r but don't raise any errors either.</p> <pre><code>In [7]: import pandas as pd In [8]: data = {...
0
2016-08-30T01:49:08Z
39,233,080
<p>Preprocessing may be the best option. But if you're looking for something else, you may try <code>lineterminator</code> argument in <code>read_csv</code>:</p> <pre><code>df = pd.read_csv("my_df.csv", index_col=0, lineterminator='\n') </code></pre> <p>(Works for me on linux but can't guarantee for other platforms.)...
0
2016-08-30T16:53:05Z
[ "python", "pandas", "special-characters", "export-to-csv" ]
How to run python script on a web server?
39,217,637
<p>I have been learning Django, the python webframework, so that I can use python scripts in my website. While I've learned the basics, I'm still a little unsure as to how to actually implement my own scripts into the website. </p> <p>When I run the script on my computer, it spits out a small graph. Can somebody pleas...
-1
2016-08-30T01:50:18Z
39,217,657
<p>Python script can be run on web servers using the Flask framework. Flask is a micro web framework written in Python. Also Django can be used alongside Flask for building REST API.</p>
-1
2016-08-30T01:54:19Z
[ "python", "django" ]
How to run python script on a web server?
39,217,637
<p>I have been learning Django, the python webframework, so that I can use python scripts in my website. While I've learned the basics, I'm still a little unsure as to how to actually implement my own scripts into the website. </p> <p>When I run the script on my computer, it spits out a small graph. Can somebody pleas...
-1
2016-08-30T01:50:18Z
39,217,686
<p>You can either implement your scripts in your or call the already existing ones in <code>views.py</code>. At any rate, I highly recommend that you read the <a href="https://docs.djangoproject.com/en/1.10/" rel="nofollow">official docs</a>, they are a amazing source of high quality materials, including a highly in-de...
1
2016-08-30T01:58:08Z
[ "python", "django" ]
How to convert a list by mapping an element into multiple elements in python?
39,217,639
<p>For example, how to convert [1, 5, 7] into [1,2,5,6,7,8] into python? [x, x+1 for x in [1,5,7]] can't work for sure...</p>
5
2016-08-30T01:50:27Z
39,217,666
<p>Not sure if this is the best way, but I would do:</p> <pre><code>l = [1, 5, 7] print([y for x in l for y in (x, x + 1)]) </code></pre> <p>Another way using <a href="https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable" rel="nofollow"><code>itertools.chain.from_iterable</code></a>:</p> <p...
3
2016-08-30T01:55:37Z
[ "python" ]
How to convert a list by mapping an element into multiple elements in python?
39,217,639
<p>For example, how to convert [1, 5, 7] into [1,2,5,6,7,8] into python? [x, x+1 for x in [1,5,7]] can't work for sure...</p>
5
2016-08-30T01:50:27Z
39,217,670
<p>You can do your list comprehension logic with tuples and then flatten the resulting list:</p> <p><code>[n for pair in [(x, x+1) for x in [1,5,7]] for n in pair]</code></p>
1
2016-08-30T01:56:10Z
[ "python" ]
How to convert a list by mapping an element into multiple elements in python?
39,217,639
<p>For example, how to convert [1, 5, 7] into [1,2,5,6,7,8] into python? [x, x+1 for x in [1,5,7]] can't work for sure...</p>
5
2016-08-30T01:50:27Z
39,217,679
<p>If you just want to fill the list with the numbers between the min and max+1 values you can use <code>[i for i in range (min(x),max(x)+2)]</code> assuming <code>x</code> is your list.</p>
0
2016-08-30T01:56:58Z
[ "python" ]
How to convert a list by mapping an element into multiple elements in python?
39,217,639
<p>For example, how to convert [1, 5, 7] into [1,2,5,6,7,8] into python? [x, x+1 for x in [1,5,7]] can't work for sure...</p>
5
2016-08-30T01:50:27Z
39,217,730
<p>And you can always overcomplicate the problem with <a href="https://docs.python.org/2/library/operator.html" rel="nofollow"><code>operator</code></a>, <a href="https://docs.python.org/2/library/itertools.html#itertools.imap" rel="nofollow"><code>imap()</code></a>, <a href="https://docs.python.org/2/library/functools...
2
2016-08-30T02:04:14Z
[ "python" ]
How to convert a list by mapping an element into multiple elements in python?
39,217,639
<p>For example, how to convert [1, 5, 7] into [1,2,5,6,7,8] into python? [x, x+1 for x in [1,5,7]] can't work for sure...</p>
5
2016-08-30T01:50:27Z
39,217,895
<p>A simple way to think about the problem is to make a second list of incremented values and add it to the original list, then sort it:</p> <pre><code>l = [1, 5, 7] m = l + [i+1 for i in l] m.sort() print m # [1, 2, 5, 6, 7, 8] </code></pre>
2
2016-08-30T02:27:37Z
[ "python" ]
How to convert a list by mapping an element into multiple elements in python?
39,217,639
<p>For example, how to convert [1, 5, 7] into [1,2,5,6,7,8] into python? [x, x+1 for x in [1,5,7]] can't work for sure...</p>
5
2016-08-30T01:50:27Z
39,218,076
<p>You can combine some ideas from alecxe's answer and what you already had:</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; &gt;&gt;&gt; a = [1, 5, 7] &gt;&gt;&gt; b = ((x, x+1) for x in a) &gt;&gt;&gt; &gt;&gt;&gt; list(itertools.chain(*b)) [1, 2, 5, 6, 7, 8] </code></pre> <p>What I have done is :</p> ...
2
2016-08-30T02:53:10Z
[ "python" ]
How to convert a list by mapping an element into multiple elements in python?
39,217,639
<p>For example, how to convert [1, 5, 7] into [1,2,5,6,7,8] into python? [x, x+1 for x in [1,5,7]] can't work for sure...</p>
5
2016-08-30T01:50:27Z
39,218,319
<p>Make a generator function that iterates over the list and yields, in turn, each element and that element plus one. Iterate over your generator.</p> <pre><code>def foo(lyst): for element in lyst: yield element yield element + 1 &gt;&gt;&gt; print(list(foo([1, 5, 7]))) [1, 2, 5, 6, 7, 8] &gt;&gt...
2
2016-08-30T03:25:19Z
[ "python" ]
Load URL without graphical interface
39,217,787
<p>In Python3, I need to load a URL every set interval of time, but without a graphical interface / browser window. There is no JavaScript, all it needs to do is load the page, and then quit it. This needs to run as a console application.</p> <p>Is there any way to do this?</p>
0
2016-08-30T02:13:15Z
39,217,960
<p>You could use <code>threading</code> and create a <code>Timer</code> that calls your function after every specified interval of time.</p> <pre><code>import time, threading, urllib.request def fetch_url(): threading.Timer(10, fetch_url).start() req = urllib.request.Request('http://www.stackoverflow.com') ...
0
2016-08-30T02:36:41Z
[ "python", "python-3.x", "web" ]
Load URL without graphical interface
39,217,787
<p>In Python3, I need to load a URL every set interval of time, but without a graphical interface / browser window. There is no JavaScript, all it needs to do is load the page, and then quit it. This needs to run as a console application.</p> <p>Is there any way to do this?</p>
0
2016-08-30T02:13:15Z
39,217,986
<p>The requests library may have what you're looking for.</p> <pre><code>import requests, time url = "url.you.need" website_object = requests.get(url) # Repeat as necessary </code></pre>
0
2016-08-30T02:42:05Z
[ "python", "python-3.x", "web" ]
How to convert to Python list comprehension
39,217,882
<pre><code>ls = ['abc', 56, 49, 63, 66, 80] for i in ls: if(isinstance(i, int) or isinstance(i, float)): for i in range(len(ls)): ls[i] = str(ls[i]) </code></pre> <p>May I know how to create the list comprehension of above code?</p> <p>I am trying the following but not working</p> <pre><code...
1
2016-08-30T02:25:31Z
39,217,897
<p>For your example where you have either strings or integers or floats, you can use a simple list comprehension:</p> <pre><code>ls = ['abc', 56, 49, 63, 66, 80] print([str(l) for l in ls]) </code></pre> <p>Or alternatively, you can use <a href="https://docs.python.org/3/library/functions.html#map"><code>map</code></...
6
2016-08-30T02:27:48Z
[ "python", "list", "python-3.x", "for-comprehension" ]
Regex to parse out a part of URL using python
39,217,906
<p>I am having data as follows,</p> <pre><code>data['url'] http://hostname.com/aaa/uploads/2013/11/a-b-c-d.jpg https://www.aaa.com/ http://hostname.com/bbb/uploads/2013/11/e-f-g-h.gif https://www.aaa.com/ http://hostname.com/ccc/uploads/2013/11/e-f-g-h.png http://hostname.com/ccc/uploads/2013/11/a-a-a-a.html http://h...
-1
2016-08-30T02:29:00Z
39,217,977
<p>this builds a list of name to extension pairs</p> <pre><code>import re results = [] for link in data: matches = re.search(r'/(\w-\w-\w-\w)\.(\w{2,})\b', link) results.append((matches.group(1), matches.group(2))) </code></pre>
1
2016-08-30T02:41:06Z
[ "python", "regex", "python-2.7", "python-3.x", "regex-negation" ]
Regex to parse out a part of URL using python
39,217,906
<p>I am having data as follows,</p> <pre><code>data['url'] http://hostname.com/aaa/uploads/2013/11/a-b-c-d.jpg https://www.aaa.com/ http://hostname.com/bbb/uploads/2013/11/e-f-g-h.gif https://www.aaa.com/ http://hostname.com/ccc/uploads/2013/11/e-f-g-h.png http://hostname.com/ccc/uploads/2013/11/a-a-a-a.html http://h...
-1
2016-08-30T02:29:00Z
39,218,096
<p>This pattern returns the file names. I have just used one of your urls to demonstrate, for more, you could simply append the matches to a list of results:</p> <pre><code>import re url = "http://hostname.com/ccc/uploads/2013/11/e-f-g-h.png http://hostname.com/ccc/uploads/2013/11/a-a-a-a.html" p = r'((?:[a-z]-){3}[...
1
2016-08-30T02:55:26Z
[ "python", "regex", "python-2.7", "python-3.x", "regex-negation" ]
Regex to parse out a part of URL using python
39,217,906
<p>I am having data as follows,</p> <pre><code>data['url'] http://hostname.com/aaa/uploads/2013/11/a-b-c-d.jpg https://www.aaa.com/ http://hostname.com/bbb/uploads/2013/11/e-f-g-h.gif https://www.aaa.com/ http://hostname.com/ccc/uploads/2013/11/e-f-g-h.png http://hostname.com/ccc/uploads/2013/11/a-a-a-a.html http://h...
-1
2016-08-30T02:29:00Z
39,218,184
<p>You might try this:</p> <pre><code>data['parse'] = re.findall(r'[^/]+\.[a-z]+ ',data['url']) </code></pre> <p>That will pick out all of the file names with their extensions. If you want to remove the extensions, the code above returns a list which you can then process with list comprehension and re.sub like so:</p...
0
2016-08-30T03:10:13Z
[ "python", "regex", "python-2.7", "python-3.x", "regex-negation" ]
split string on commas but ignore commas with in single quotes and create a dictionary after string split in python
39,217,929
<p>I have a string as shown below,</p> <pre><code>someVariable1='9',someVariable2='some , value, comma,present',somevariable5='N/A',someVariable6='some text,comma,= present,' </code></pre> <p>I have to split above string on commas but ignore commas within quotes in python and i have to create a dictionary to get the...
0
2016-08-30T02:32:41Z
39,218,090
<p>Build a copy of the string, looping through each character of the original string, and keeping track of the number of single-quotes you've encountered.</p> <p>Whenever you see a comma, refer to the single-quote count. If it's odd (meaning you're currently inside a quoted string), don't add the comma onto the strin...
0
2016-08-30T02:54:49Z
[ "python", "string", "python-3.x", "python-2.x" ]
split string on commas but ignore commas with in single quotes and create a dictionary after string split in python
39,217,929
<p>I have a string as shown below,</p> <pre><code>someVariable1='9',someVariable2='some , value, comma,present',somevariable5='N/A',someVariable6='some text,comma,= present,' </code></pre> <p>I have to split above string on commas but ignore commas within quotes in python and i have to create a dictionary to get the...
0
2016-08-30T02:32:41Z
39,218,097
<p>Try this regular expression <code>,(?=(?:[^']*\'[^']*\')*[^']*$)</code> for splitting:</p> <pre><code>import re re.split(",(?=(?:[^']*\'[^']*\')*[^']*$)",s) # ["someVariable1='9'", # "someVariable2='some , value, comma,present'", # "somevariable5='N/A'", # "someVariable6='some text,comma,= present,'"] </code></...
1
2016-08-30T02:55:41Z
[ "python", "string", "python-3.x", "python-2.x" ]
pandas: 'join' failing to compile
39,217,985
<p>I'm having a bit of a problem trying to get my code to compile. Looks like the line with <code>main_df = df</code> is causing a failure, and I don't quite understand why.</p> <p>Any help is much appreciated.</p> <pre><code>import quandl import pandas as pd # API key was removed api_key = 'X' fiddy_states = pd.rea...
0
2016-08-30T02:42:00Z
39,218,220
<p>You can pass a list of codes to the <code>quandl.get</code> function, then you get a dataframe back with data for each code in a column. Code: </p> <pre><code>import quandl import pandas as pd fiddy_states = pd.read_html('https://simple.wikipedia.org/wiki/List_of_U.S._states', flavor='html5lib') data = quandl.get(...
1
2016-08-30T03:15:06Z
[ "python", "pandas", "join", "quandl" ]
How to focus on pydev console prompt with keyboard?
39,217,997
<p>It seems there is no way to focus pydev console prompt even with window switch. Does anyone know how?</p> <p><a href="http://i.stack.imgur.com/wDc0B.png" rel="nofollow"><img src="http://i.stack.imgur.com/wDc0B.png" alt=""></a></p>
0
2016-08-30T02:43:16Z
39,218,688
<p>I think i had to hack this by using a windows macro program to put a mouse click there :) I used Macro Express</p>
0
2016-08-30T04:16:47Z
[ "python", "eclipse", "eclipse-plugin", "console", "pydev" ]
How to pass string parameters to C++ function using ctypes, python
39,218,021
<p>I have a C++ DLL library. One function is shown as below.</p> <p>The DLL import in Python is correct.</p> <pre><code>int _ParseLogin2Resp(const std::string&amp; username, const std::string&amp; password, char szErr[1024]); </code></pre> <p>In fact, I have tried many ways ...
0
2016-08-30T02:46:12Z
39,218,723
<p>Python doc says ctypes provides C compatible data types, it is better to use c style API interface in your DLL.</p>
0
2016-08-30T04:20:37Z
[ "python", "c++", "dll", "ctypes" ]
Python dictionary converting to json or yaml
39,218,060
<p>I have parsed a string and converted into a dictionary. however I would like to be able to get more information from my dictionary and I was thinking creating a son file or yaml file would be more useful. please feel free to comment on another way of solving this problem.</p> <pre><code>import re regex = '(\w+) \[(...
0
2016-08-30T02:51:34Z
39,218,085
<p>The question of json vs yaml boils down to what are you doing with the data you are saving? If you are reusing the data in JS or in another python script then you could use JSON. If you were using it in something that uses YAML then use YAML. But in terms of your question, unless there is a particular end game or us...
0
2016-08-30T02:54:12Z
[ "python", "json", "dictionary" ]
Reading text from image
39,218,106
<p>Any suggestions on converting these images to text? I'm using pytesseract and it's working wonderfully in most cases except this. Ideally I'd read these numbers exactly. Worst case I can just try to use PIL to determine if the number to the left of the '/' is a zero. Start from the left and find the first white ...
3
2016-08-30T02:56:51Z
39,234,595
<p>Generally speaking, most OCR tools (like Tesseract) are tuned for working with high-resolution scans of printed text. They do not perform well on low-resolution or pixellated images.</p> <p>Two possible approaches here are:</p> <ol> <li><p>If the font, background, and layout of your images are completely predictab...
0
2016-08-30T18:24:39Z
[ "python", "image-processing", "pytesser" ]
What are valid values for platforms in python setup.py?
39,218,107
<p>The official documentation <a href="http://docs.python.org/2/distutils/apiref.html" rel="nofollow">mentions this parameter</a> but says nothing about possible values.</p> <p>Is it necessary to use <code>Operating System</code> key in <code>classifiers</code> ?</p>
3
2016-08-30T02:56:54Z
39,220,097
<p>Well its not needed every time. But if you are doing something w.r.t platform and you don't intend to support all platforms in your program, then you need to base your program on platform.</p> <p>Following are the os names that are currently registered in python</p> <pre><code>'posix', 'nt', 'os2', 'ce', 'java', '...
0
2016-08-30T06:18:34Z
[ "python", "distutils" ]
Import files not in the current working directory
39,218,109
<p>Let's say the program asks the user for a file name to read and then a file to write the processed data into. </p> <p>Is there a way to get the directory of the needed file so the program can alter the current directory to use it? Or is there another way to access that file?</p>
0
2016-08-30T02:57:23Z
39,218,124
<p>If the user enters the complete file path with the directory, you can parse it (using sys.path) and then os.chdir() there.</p>
0
2016-08-30T02:59:50Z
[ "python", "directory", "cwd" ]
Import files not in the current working directory
39,218,109
<p>Let's say the program asks the user for a file name to read and then a file to write the processed data into. </p> <p>Is there a way to get the directory of the needed file so the program can alter the current directory to use it? Or is there another way to access that file?</p>
0
2016-08-30T02:57:23Z
39,218,226
<p>You could make it even easier for the user by using Tkinter to prompt them with a file upload box rather than asking them to type it in. When they select a file it will give you the full file path.</p> <pre><code>from tkinter import filedialog # this gives you the full file path filepath = askopenfilename() print...
0
2016-08-30T03:15:58Z
[ "python", "directory", "cwd" ]
Import files not in the current working directory
39,218,109
<p>Let's say the program asks the user for a file name to read and then a file to write the processed data into. </p> <p>Is there a way to get the directory of the needed file so the program can alter the current directory to use it? Or is there another way to access that file?</p>
0
2016-08-30T02:57:23Z
39,218,707
<p>Welp, this is my first answer on SO, so hopefully I don't misunderstand the question and get off to a bad start. Here goes nothing...</p> <p>Quite frankly, there isn't too much more to be said than what prior comments and answers have provided. While there are <a href="http://stackoverflow.com/questions/10174211/ma...
0
2016-08-30T04:18:50Z
[ "python", "directory", "cwd" ]
How to output all unassigned strings in a python file
39,218,253
<p>I have a python file (a script) that looks like this:</p> <h3>script.py</h3> <pre><code>""" Multiline comment with unique text pertaining to the Foo class """ class Foo(): pass """ Multiline comment with unique text pertaining to the Bar class """ class Bar(): pass """ Multiline comment with unique tex...
0
2016-08-30T03:19:17Z
39,218,416
<p>Assuming the formatting you indicated in your question, something like this should do it:</p> <pre><code>class Show_Script(): def construct(self): with open(os.path.abspath(__file__)) as f: my_lines = f.readlines() comments = [] in_comment = 0 for line in my_lines: ...
1
2016-08-30T03:40:35Z
[ "python", "string", "unassigned-variable" ]
How to output all unassigned strings in a python file
39,218,253
<p>I have a python file (a script) that looks like this:</p> <h3>script.py</h3> <pre><code>""" Multiline comment with unique text pertaining to the Foo class """ class Foo(): pass """ Multiline comment with unique text pertaining to the Bar class """ class Bar(): pass """ Multiline comment with unique tex...
0
2016-08-30T03:19:17Z
39,218,573
<p>Using regex:</p> <pre><code>$ cat script.py from __future__ import print_function import sys, re """ Multiline comment with unique text pertaining to the Foo class """ class Foo(): pass """ Multiline comment with unique text pertaining to the Bar class """ class Bar(): pass """ Multiline comment with u...
1
2016-08-30T04:01:48Z
[ "python", "string", "unassigned-variable" ]
python pandas: merge two data frame but didn't merge the repeat rows
39,218,298
<p>I have two dataframe: df1 and df2.</p> <p>df1 is following:</p> <pre><code> name exist a 1 b 1 c 1 d 1 e 1 </code></pre> <p>df2 (just have one column:name)is following:</p> <pre><code> name e f g a h ...
0
2016-08-30T03:23:24Z
39,218,344
<p>As indicated by your title, you can use <code>merge</code> instead of <code>concat</code> and specify <code>how</code> parameter as <code>outer</code> since you want to keep all records from <code>df1</code> and <code>df2</code> which defines an outer join:</p> <pre><code>import pandas as pd pd.merge(df1, df2, on =...
1
2016-08-30T03:28:32Z
[ "python", "pandas", "merge", "concat" ]
Python -- Curl works, requests lib doesn't
39,218,313
<p>This works from the command line:</p> <pre><code> curl -H "Content-Type: application/json" -X POST -d '&lt;my data&gt;' http://my_user:my_pass@my_url </code></pre> <p>This doesn't work from a python script:</p> <pre><code> res=requests.post( 'http://my_user:my_pass@my_url', json='&lt;my data&gt;') </code></...
0
2016-08-30T03:24:57Z
39,218,395
<p>You need to try setting the authentication using <code>requests</code> library like this:</p> <pre><code>from requests.auth import HTTPBasicAuth response = requests.post(url, json=payload, auth=HTTPBasicAuth('user', 'pass')) </code></pre> <p><a href="http://docs.python-requests.org/en/master/user/authentication/#...
2
2016-08-30T03:36:03Z
[ "python", "curl", "django-rest-framework", "python-requests", "pycurl" ]
Python -- Curl works, requests lib doesn't
39,218,313
<p>This works from the command line:</p> <pre><code> curl -H "Content-Type: application/json" -X POST -d '&lt;my data&gt;' http://my_user:my_pass@my_url </code></pre> <p>This doesn't work from a python script:</p> <pre><code> res=requests.post( 'http://my_user:my_pass@my_url', json='&lt;my data&gt;') </code></...
0
2016-08-30T03:24:57Z
39,226,684
<blockquote> <p>I escaped \ , so it's a double backslash. I also tried with r in front of string, and 4 backslashes.</p> </blockquote> <p>The \ in the curl command was to escape a parenthesis. It wasn't part of the password.</p> <p>I removed it and now it works.</p>
0
2016-08-30T11:47:41Z
[ "python", "curl", "django-rest-framework", "python-requests", "pycurl" ]
How can I search and parse multiple, session-specific search results with Scrapy?
39,218,466
<p>[EDIT: Code is revised to show my attempt at doing Granitosaurus' suggestion]</p> <p>I need to execute some predefined searches and crawl the results 1 level deep, then parse those pages. This has to be done sequentially because the site will not allow results to be crawled unless those results were just retrieved ...
0
2016-08-30T03:48:16Z
39,220,261
<p>Seems like you are being restricted by the website session. What you could try is to spawn multiple sessions in <code>start_requests()</code> and then for each session yield unique search query.</p> <p>Something like: </p> <pre><code>class MySpider(scrapy.Spider): name = "myspider" start_url = "http://scra...
0
2016-08-30T06:29:16Z
[ "python", "asp.net", "scrapy" ]
Towers of Hanoi recursive calls
39,218,491
<pre><code>1 2 def printMove (to, fr): 3 '''Prints the moves to be executed''' 4 print 'move from ' + str (fr) + ' to ' + str (to) 5 6 def towers (n, fr, to, sp): 7 if n == 1: 8 9 printMove (to, fr) # 10 11 else: 12 towers (n-1, fr, sp, to) 13 ...
1
2016-08-30T03:51:43Z
39,218,717
<p>First, an aside: the code you show contains an error on line 9, which is not indented legally.</p> <p>Execution begins with line 19, which calls towers(3,...), which proceeds up to line 12, where it calls towers(2,...), which proceeds up to line 12, where it calls towers(1,...), which prints something and returns. ...
1
2016-08-30T04:19:39Z
[ "python", "algorithm", "recursion", "towers-of-hanoi" ]
Towers of Hanoi recursive calls
39,218,491
<pre><code>1 2 def printMove (to, fr): 3 '''Prints the moves to be executed''' 4 print 'move from ' + str (fr) + ' to ' + str (to) 5 6 def towers (n, fr, to, sp): 7 if n == 1: 8 9 printMove (to, fr) # 10 11 else: 12 towers (n-1, fr, sp, to) 13 ...
1
2016-08-30T03:51:43Z
39,219,204
<p>First of all, your code is not perfectly alright. Here is the changed <code>towers</code> function for you -></p> <pre><code>def towers (n, fr, to, sp): if n == 1: printMove (to, fr) else: towers (n-1, fr, sp, to) printMove (to,fr) towers (n-1, sp, to, fr) </code>...
5
2016-08-30T05:14:51Z
[ "python", "algorithm", "recursion", "towers-of-hanoi" ]
create 3D binary image
39,218,556
<p>I have a 2D array, <code>a</code>, comprising a set of 100 x,y,z coordinates: </p> <pre><code>[[ 0.81 0.23 0.52] [ 0.63 0.45 0.13] ... [ 0.51 0.41 0.65]] </code></pre> <p>I would like to create a 3D binary image, <code>b</code>, with 101 pixels in each of the x,y,z dimensions, of coordinates ranging betw...
4
2016-08-30T04:00:34Z
39,219,766
<p>You could do something like this -</p> <pre><code># Get the XYZ indices idx = np.round(100 * a).astype(int) # Initialize o/p array b = np.zeros((101,101,101)) # Assign into o/p array based on linear index equivalents from indices array np.put(b,np.ravel_multi_index(idx.T,b.shape),1) </code></pre> <hr> <p>Runtim...
4
2016-08-30T05:58:42Z
[ "python", "numpy", "indexing", "binary", "ndimage" ]
create 3D binary image
39,218,556
<p>I have a 2D array, <code>a</code>, comprising a set of 100 x,y,z coordinates: </p> <pre><code>[[ 0.81 0.23 0.52] [ 0.63 0.45 0.13] ... [ 0.51 0.41 0.65]] </code></pre> <p>I would like to create a 3D binary image, <code>b</code>, with 101 pixels in each of the x,y,z dimensions, of coordinates ranging betw...
4
2016-08-30T04:00:34Z
39,219,890
<p>First, start off by safely rounding your floats to ints. In context, see <a href="http://stackoverflow.com/q/3387655/525169">this</a> question.</p> <pre><code>a_indices = np.rint(a * 100).astype(int) </code></pre> <p>Next, assign those indices in <code>b</code> to 1. But be careful to use an ordinary <code>list</c...
4
2016-08-30T06:07:10Z
[ "python", "numpy", "indexing", "binary", "ndimage" ]
Using BeautifulSoup to Search Through Yahoo Finance
39,218,742
<p>I'm trying to pull information from the 'Key Statistics' page for a ticker in Yahoo (since this isn't supported in the Pandas library). </p> <p>Example for AAPL:</p> <pre><code>from bs4 import BeautifulSoup import requests url = 'http://finance.yahoo.com/quote/AAPL/key-statistics?p=AAPL' page = requests.get(url) ...
4
2016-08-30T04:23:53Z
39,218,917
<p>Well, the reason the list that <code>find_all</code> returns is empty is because that data is generated with a separate call that isn't completed by just sending a <code>GET</code> request to that URL. If you look through the Network tab on Chrome/Firefox and filter by XHR, by examining the requests and responses o...
3
2016-08-30T04:46:07Z
[ "python", "beautifulsoup", "yahoo-finance" ]
Find numpy vectors in a set quickly
39,218,768
<p>I have a numpy array, for example:</p> <pre><code>a = np.array([[1,2], [3,4], [6,4], [5,3], [3,5]]) </code></pre> <p>and I also have a set</p> <pre><code>b = set((1,2),(6,4),(9,9)) </code></pre> <p>I want to find the index of vectors that exist in set b, he...
1
2016-08-30T04:26:16Z
39,218,831
<p>You can use filter:</p> <pre><code>In [8]: a = np.array([[1,2], [3,4], [6,4], [5,3], [3,5]]) In [9]: b = {(1,2),(6,4)} In [10]: filter(lambda x: tuple(a[x]) in b, range(len(a))) Out[10]: [0, 2] </code></pre>
1
2016-08-30T04:35:08Z
[ "python", "numpy", "set", "vectorization", "lookup" ]
Find numpy vectors in a set quickly
39,218,768
<p>I have a numpy array, for example:</p> <pre><code>a = np.array([[1,2], [3,4], [6,4], [5,3], [3,5]]) </code></pre> <p>and I also have a set</p> <pre><code>b = set((1,2),(6,4),(9,9)) </code></pre> <p>I want to find the index of vectors that exist in set b, he...
1
2016-08-30T04:26:16Z
39,219,030
<p>First off, convert the set to a NumPy array -</p> <pre><code>b_arr = np.array(list(b)) </code></pre> <p>Then, based on <a href="http://stackoverflow.com/a/38674038/3293881"><code>this post</code></a>, you would have three approaches. Let's use the second approach for efficiency -</p> <pre><code>dims = np.maximum(...
1
2016-08-30T04:58:33Z
[ "python", "numpy", "set", "vectorization", "lookup" ]
Find numpy vectors in a set quickly
39,218,768
<p>I have a numpy array, for example:</p> <pre><code>a = np.array([[1,2], [3,4], [6,4], [5,3], [3,5]]) </code></pre> <p>and I also have a set</p> <pre><code>b = set((1,2),(6,4),(9,9)) </code></pre> <p>I want to find the index of vectors that exist in set b, he...
1
2016-08-30T04:26:16Z
39,220,519
<p>For reference, a straight forward list comprehension (loop) answer:</p> <pre><code>In [108]: [i for i,v in enumerate(a) if tuple(v) in b] Out[108]: [0, 2] </code></pre> <p>basically the same speed as the <code>filter</code> approach:</p> <pre><code>In [111]: timeit [i for i,v in enumerate(a) if tuple(v) in b] 100...
0
2016-08-30T06:45:20Z
[ "python", "numpy", "set", "vectorization", "lookup" ]
Find numpy vectors in a set quickly
39,218,768
<p>I have a numpy array, for example:</p> <pre><code>a = np.array([[1,2], [3,4], [6,4], [5,3], [3,5]]) </code></pre> <p>and I also have a set</p> <pre><code>b = set((1,2),(6,4),(9,9)) </code></pre> <p>I want to find the index of vectors that exist in set b, he...
1
2016-08-30T04:26:16Z
39,222,152
<p>A one line solution using a list comprehension:</p> <pre><code>In [62]: a = np.array([[1,2], ...: [3,4], ...: [6,4], ...: [5,3], ...: [3,5]]) In [63]: b = set(((1,2),(6,4),(9,9))) In [64]: where([tuple(e) in b for e in a])[0] Out[64]: array([0...
0
2016-08-30T08:12:46Z
[ "python", "numpy", "set", "vectorization", "lookup" ]
Improving performance for SQLAlchemy?
39,218,781
<p>I am currently running a Flask + SQLAlchemy + uWSGI + nginx stack for an API backend that I am developing for my application. I was attempting to see what is the maximum amount of concurrent connection I can have on my server by using ApacheBench and sending different amounts of concurrent requests to an endpoint o...
0
2016-08-30T04:28:05Z
39,238,424
<p>The linear increase is very much normal, if the database has to process your queries sequentially. Essentially, all concurrent requests get started at the same time, but finish one after another, so, assuming a pool with a single connection, 60ms per request, and 10 concurrent requests, you're going to see requests ...
0
2016-08-30T23:12:04Z
[ "python", "performance", "sqlalchemy", "database-connection" ]
Allow only editing the current selected Foreign Key in Django Admin
39,218,783
<p>So currently I have something like this:</p> <p>Model:</p> <pre><code>class ConfirmEmail(models.Model): report = models.ForeignKey(Report) owner = models.CharField(max_length = 100) emails = models.ManyToManyField(Sdm) </code></pre> <p>Admin: </p> <pre><code>@admin.register(ConfirmEmail) class...
1
2016-08-30T04:28:12Z
39,220,140
<p>You should first introduce a model admin for your Report model, then override the <strong>has_add_permission</strong> function of your ReportAdmin.</p> <pre><code>@admin.register(Report) class ReportAdmin(admin.ModelAdmin): # whatever you want here def has_add_permission(self, request): return F...
0
2016-08-30T06:22:05Z
[ "python", "django", "django-admin" ]
Is there an attribute called rect.center in pygame?
39,218,842
<p>I was looking through a pygame tutorial and encountered the following part of a script: </p> <pre><code>fontObj = pygame.font.Font('freesansbold.ttf', 32) textSurfaceObj = fontObj.render('hellow world', True, Green, Blue) textRectObj = textSurfaceObj.get_rect() textRectObj.center = (200,150) </code></pre> <p>The l...
0
2016-08-30T04:36:15Z
39,219,038
<p>According to the <a href="http://www.pygame.org/docs/ref/rect.html" rel="nofollow">docs on rect</a>:</p> <blockquote> <p>The Rect object has several virtual attributes which can be used to move and align the Rect:</p> <p>x,y</p> <p>top, left, bottom, right</p> <p>topleft, bottomleft, topright, bott...
0
2016-08-30T04:59:29Z
[ "python", "pygame" ]
Please explain the output of this python code
39,218,862
<p>Here the code.</p> <pre><code>a = False if a == True or True: print "Hell yeah,I'm genius" else: print "shit,I am a fool" </code></pre> <p>Output is '<code>Hell yeah,I'm genius</code>'</p>
-2
2016-08-30T04:38:36Z
39,219,006
<p>Anything True , it will run that section ...</p> <pre><code>if True: print "Hell yeah,I'm genius" else: print "shit,I am a fool" </code></pre> <p>This one also returns <code>"Hell yeah,I'm genius"</code></p>
-1
2016-08-30T04:56:09Z
[ "python" ]
Please explain the output of this python code
39,218,862
<p>Here the code.</p> <pre><code>a = False if a == True or True: print "Hell yeah,I'm genius" else: print "shit,I am a fool" </code></pre> <p>Output is '<code>Hell yeah,I'm genius</code>'</p>
-2
2016-08-30T04:38:36Z
39,219,168
<pre><code>a ==True or True </code></pre> <p>Consider True is 1 and 0 is False.</p> <p>Since a is set to False (a=False in first statement of code), the first part 'a==True' i.e. 0 ==1 will return 0 (False).</p> <p>Then remaining will be False or True since 'a==True' is False. So it will be like 0 or 1 (False or T...
2
2016-08-30T05:11:43Z
[ "python" ]
Python ttk notebook showing selected tab wrongly
39,218,863
<pre><code>from tkinter import * from tkinter import ttk class MainGame(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def tab_change(self, event): tab_id = self.page.index('current') print(tab_id, self.pag...
0
2016-08-30T04:38:49Z
39,219,156
<p>Change:</p> <pre><code>self.page.bind('&lt;ButtonPress-1&gt;', self.tab_change) </code></pre> <p>To:</p> <pre><code>self.page.bind('&lt;ButtonRelease-1&gt;', self.tab_change) </code></pre> <p>Because unless you have released the pressed button, the tab hasn't changed!</p> <p><a href="http://i.stack.imgur.com/xL...
0
2016-08-30T05:10:46Z
[ "python", "tkinter", "tabs", "ttk" ]
django registration redux ignoring changes in templates
39,218,872
<p>I've been struggling with django registration redux over the past two weeks.. I'm using the templates the were provided in the documentation but I've made a couple of changes like adding crispy forms and changing the button and some other stuff but the problem is that none of these changes are being shown on <a href...
0
2016-08-30T04:40:12Z
39,231,115
<p>Putting your customized templates in <code>templates/registration</code> (not register) should work.</p> <p>At least if your <code>TEMPLATES</code> setting is correctly configured: <a href="https://docs.djangoproject.com/en/1.8/ref/templates/upgrading/" rel="nofollow">https://docs.djangoproject.com/en/1.8/ref/templ...
0
2016-08-30T15:06:45Z
[ "python", "django", "html5", "twitter-bootstrap-3", "django-registration" ]
how to convert print output into variable/string with "more than 3 arguments"? (python 3)
39,218,880
<p>Basically I'm trying to take the print output for my code and make it into a variable. I tried to do this by converting it to a string but it gave me an error saying "TypeError: str() takes at most 3 arguments (6 given)"</p> <p>my code:</p> <pre><code>x = [1,2,3,4,5] print(*x, sep='_') ##gives me the output "1_2...
0
2016-08-30T04:41:09Z
39,218,909
<p>You can convert the list of ints to a list of strings using <a href="https://docs.python.org/3/library/functions.html#map" rel="nofollow"><code>map</code></a>, then use <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow"><code>join</code></a> to bind them together:</p> <pre><code>x = [...
4
2016-08-30T04:44:56Z
[ "python", "string", "python-3.x", "printing", "arguments" ]
how to convert print output into variable/string with "more than 3 arguments"? (python 3)
39,218,880
<p>Basically I'm trying to take the print output for my code and make it into a variable. I tried to do this by converting it to a string but it gave me an error saying "TypeError: str() takes at most 3 arguments (6 given)"</p> <p>my code:</p> <pre><code>x = [1,2,3,4,5] print(*x, sep='_') ##gives me the output "1_2...
0
2016-08-30T04:41:09Z
39,218,945
<p><code>*x</code> supplies much too many arguments to <code>str()</code> causing the error, and <code>sep</code> isn't an argument of <code>str()</code>. <code>str()</code> expects one object to be converted, and <code>*x</code> gives 5. Try this:</p> <pre><code>x = [1, 2, 3, 4, 5] a = '_'.join(str(i) for i in x) pri...
3
2016-08-30T04:49:05Z
[ "python", "string", "python-3.x", "printing", "arguments" ]
Close all browser instance in one go
39,218,979
<p>I am trying to close all browser instance opened by a test case in one go that is immediately when the test fails. I have opened more than one instance of same kind that is i am trying to automate chat application so i need to open two instance of same browser kind. But once the test fails, both the instance needs t...
0
2016-08-30T04:53:17Z
39,219,188
<p>What about calling <code>quit()</code> for both of them</p> <pre><code>brow1.quit(); brow2.quit(); </code></pre> <p>Or for more generic way keep them in list and iterate over it.</p> <pre><code>browsers = [] browsers.append(brow1) browsers.append(brow2) for browser in browsers: browser.quit() </code></pre>
2
2016-08-30T05:13:47Z
[ "python", "python-2.7", "selenium", "selenium-webdriver" ]
Is there a way to prevent dtype from changing from Int64 to float64 when reindexing/upsampling a time-series?
39,219,023
<p>I am using pandas 0.17.0 and have a <code>df</code> similar to this one:</p> <pre><code>df.head() Out[339]: A B C DATE_TIME 2016-10-08 13:57:00 in 5.61 1 2016-10-08 14:02:00 in 8.05 1 2016-10-08 14:07:00 in 7.92 0 2016-10-08 14:12:00 in 7.98 0 201...
2
2016-08-30T04:57:42Z
39,219,097
<p>It is <a href="http://pandas.pydata.org/pandas-docs/stable/gotchas.html#na-type-promotions" rel="nofollow">impossible</a>, because if you get at least one <code>NaN</code> value in some column, <code>int</code> is converted to <code>float</code>.</p> <pre><code>index = pd.date_range(df.index[0], df.index[-1], freq=...
3
2016-08-30T05:05:27Z
[ "python", "pandas", "types", "resampling", "reindex" ]
What is the time complexity of dict.keys() in Python?
39,219,065
<p>I came across a question when I solve <a href="https://leetcode.com/problems/insert-delete-getrandom-o1/">this LeetCode problem</a>. Although my solution got accepted by the system, I still do not have any idea after searching online for the following question: <code>What is the time complexity of dict.keys() operat...
9
2016-08-30T05:01:33Z
39,219,129
<p>In Python 2, it's O(n), and it builds a new list. In Python 3, it's O(1), but it doesn't return a list. To draw a random element from a dict's <code>keys</code>, you'd need to convert it to a list.</p> <p>It sounds like you were probably using <code>random.choice(d.keys())</code> for part 3 of that problem. If so, ...
3
2016-08-30T05:08:22Z
[ "python" ]
how to take exact matched phrases using regular expression when multiple braces are present
39,219,302
<p>I have texts like</p> <pre><code>1) &lt;img="" id=""&gt;data&lt;/img&gt; 2) (hi "hello") data (some text) </code></pre> <p>I want to remove only the text with braces and angular brackets and extract in between data. I tried</p> <pre><code>re.compile(r"\(.*\)") re.compile(r"&lt;.*&gt;") </code></pre> <p>but since...
1
2016-08-30T05:24:49Z
39,219,346
<p>Try non-greedy regular expressions, i.e.</p> <pre><code>re.compile(r"\(.*?\)") re.compile(r"&lt;.*?&gt;") </code></pre>
2
2016-08-30T05:28:47Z
[ "python", "regex", "text-processing" ]
how to take exact matched phrases using regular expression when multiple braces are present
39,219,302
<p>I have texts like</p> <pre><code>1) &lt;img="" id=""&gt;data&lt;/img&gt; 2) (hi "hello") data (some text) </code></pre> <p>I want to remove only the text with braces and angular brackets and extract in between data. I tried</p> <pre><code>re.compile(r"\(.*\)") re.compile(r"&lt;.*&gt;") </code></pre> <p>but since...
1
2016-08-30T05:24:49Z
39,219,353
<pre><code>In [68]: re.sub(r'&lt;(.+?)&gt;', '', '&lt;img="" id=""&gt;data&lt;/img&gt;') Out[68]: 'data' </code></pre> <p>Regex explanation:</p> <pre><code>&lt;(.+?)&gt; </code></pre> <p><img src="https://www.debuggex.com/i/dRCzoEj0k9pnANPt.png" alt="Regular expression visualization"></p> <p><a href="https://www.de...
1
2016-08-30T05:29:16Z
[ "python", "regex", "text-processing" ]
In TensorFlow, how can I get nonzero values and their indices from a tensor with python?
39,219,414
<p>I want to do something like this.<br> Let's say we have a tensor A. </p> <pre><code>A = [[1,0],[0,4]] </code></pre> <p>And I want to get nonzero values and their indices from it. </p> <pre><code>Nonzero values: [1,4] Nonzero indices: [[0,0],[1,1]] </code></pre> <p>There are similar operations in Numpy.<br> <...
0
2016-08-30T05:34:07Z
39,223,400
<p>You can achieve same result in Tensorflow using <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/control_flow_ops.html#not_equal" rel="nofollow">not_equal</a> and <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/control_flow_ops.html#where" rel="nofollow">where</a> methods. </p> ...
2
2016-08-30T09:15:53Z
[ "python", "tensorflow", "indices" ]
Failing to export to CSV in Python, multiple formats
39,219,424
<p>I am trying to export to CSV files from a Jupyter notebook. Even when I test examples copy-pasted from the documentation (see below), I get a "'str' object is not callable" error message. I have fiddled endlessly with the parameters. The same thing happens with a Pandas dataframe and I try to use to_csv.</p> <p>Bas...
0
2016-08-30T05:34:51Z
39,219,596
<p>The error you are seeing can only be explained if <code>csv.writer</code> is a string. This recreates your error:</p> <pre><code>In [1]: import csv In [2]: csv.writer = 'test' # &lt;- cause error In [3]: %paste import csv with open('eggs.csv', 'w', newline='') as csvfile: spamwriter = csv.writer(csvfile) #...
0
2016-08-30T05:47:30Z
[ "python", "python-3.x", "csv", "pandas", "jupyter" ]
Can't use the import os command in python
39,219,509
<p>I'm using the python compiler in java and I tried <code>import os</code> .</p> <p>My problem is when I couldn't input it to continue the next line while it just sent back this message <code>os is not yet implemented in skulpt on line 1</code> .</p> <p>I already tried with another app and still get a same result. I...
-3
2016-08-30T05:41:22Z
39,219,820
<p>To find which standard modules the most recent version of <code>skulpt</code> supports and which it doesn't, get a copy of the source code:</p> <pre><code>git clone https://github.com/skulpt/skulpt.git </code></pre> <p>And, look through the <code>src/lib</code> directory. Every successfully implemented module wil...
0
2016-08-30T06:02:19Z
[ "python", "python-2.7", "python-3.x", "ipython" ]
how to access character pointer value using ctypes?
39,219,526
<p>I have a written a DLL in which I'm getting one of the paths:</p> <pre><code>//demo.h __declspec(dllexport) void pathinfo(char * path); </code></pre> <p>Something is being done in the code to get this path. And now, the python script that I have written to retrieve this path from the DLL is as shown:</p> <pre><co...
0
2016-08-30T05:43:05Z
39,219,960
<p>Haven't done it, but have done the following:</p> <p>To pass an array of <code>ints</code>, for example, use this:</p> <p>Create a type of, say, 20 ints:</p> <pre><code>Ints20 = c_int * 20 </code></pre> <p>Create an instance:</p> <pre><code>data = Ints20() </code></pre> <p>And then you can pass <code>data</cod...
0
2016-08-30T06:11:02Z
[ "python", "dll", "ctypes" ]
how to access character pointer value using ctypes?
39,219,526
<p>I have a written a DLL in which I'm getting one of the paths:</p> <pre><code>//demo.h __declspec(dllexport) void pathinfo(char * path); </code></pre> <p>Something is being done in the code to get this path. And now, the python script that I have written to retrieve this path from the DLL is as shown:</p> <pre><co...
0
2016-08-30T05:43:05Z
39,220,458
<p>The reason you see only the first character is that by calling <code>c_char()</code> you create a single <code>char</code> value that Python treats like a <code>str</code> (Python 2) object or <code>bytes</code> (Python 3) object of length 1. You are probably lucky that you do not get a segmentation fault. By writin...
1
2016-08-30T06:41:17Z
[ "python", "dll", "ctypes" ]
Regex Matching - A letter not preceded by another letter
39,219,532
<p>What could be regex which match <code>anystring</code> followed by <code>daily</code> but it must not match <code>daily</code> preceded by <code>m</code>?</p> <p>For example it should match following string </p> <ul> <li><code>beta.daily</code></li> <li><code>abcdaily</code></li> <li><code>dailyabc</code></li> <li...
1
2016-08-30T05:43:26Z
39,219,598
<p>Just add a negative lookbehind, <code>(?&lt;!m)d</code>, before <code>daily</code>:</p> <pre><code>(?&lt;!m)daily </code></pre> <p>The zero width negative lookbehind, <code>(?&lt;!m)</code>, makes sure <code>daily</code> is not preceded by <code>m</code>.</p> <p><a href="https://regex101.com/r/wJ8mV5/1">Demo</a><...
6
2016-08-30T05:47:34Z
[ "python", "regex" ]
Regex Matching - A letter not preceded by another letter
39,219,532
<p>What could be regex which match <code>anystring</code> followed by <code>daily</code> but it must not match <code>daily</code> preceded by <code>m</code>?</p> <p>For example it should match following string </p> <ul> <li><code>beta.daily</code></li> <li><code>abcdaily</code></li> <li><code>dailyabc</code></li> <li...
1
2016-08-30T05:43:26Z
39,219,634
<pre><code>re.match(r"[^m]*daily.*",yourstring) </code></pre> <p>Try this regex.</p>
-1
2016-08-30T05:49:28Z
[ "python", "regex" ]
how to download images using google earth engine's python API
39,219,705
<p>I am using Google's Earth Engine API to access LandSat images. The program is as given below,</p> <pre><code>import ee ee.Initialize() </code></pre> <p><strong>Load a landsat image and select three bands.</strong></p> <pre><code>landsat = ee.Image('LANDSAT/LC8_L1T_TOA /LC81230322014135LGN00').select(['B4', 'B3',...
0
2016-08-30T05:54:05Z
39,220,017
<p>There is a typo in your code, <code>Export</code> should start from the capital letter. See <a href="https://developers.google.com/earth-engine/exporting" rel="nofollow">documentation</a>.</p>
0
2016-08-30T06:14:08Z
[ "python", "google-earth-engine" ]
Python namespace change of `import package.sub_module; from package import *`
39,219,722
<p>The <a href="https://docs.python.org/3/tutorial/modules.html#importing-from-a-package" rel="nofollow">Python documentation</a> says</p> <blockquote> <p>Consider this code:</p> </blockquote> <pre><code>import sound.effects.echo import sound.effects.surround from sound.effects import * </code></pre> <blockquote> ...
1
2016-08-30T05:55:43Z
39,220,664
<p>If a module <code>package</code> defines <code>__all__</code>, it is the list of module names that are imported by <code>from package import *</code></p> <p>So if you define <code>__all__</code> as empty list, <code>from package import *</code> will import nothing.</p> <p>Try defining it like this:</p> <pre><code...
2
2016-08-30T06:53:25Z
[ "python" ]
Python namespace change of `import package.sub_module; from package import *`
39,219,722
<p>The <a href="https://docs.python.org/3/tutorial/modules.html#importing-from-a-package" rel="nofollow">Python documentation</a> says</p> <blockquote> <p>Consider this code:</p> </blockquote> <pre><code>import sound.effects.echo import sound.effects.surround from sound.effects import * </code></pre> <blockquote> ...
1
2016-08-30T05:55:43Z
39,220,672
<p>If you define <code>__all__</code>, then <em>only</em> the attributes mentioned there will be imported via <code>*</code>, while the excluded ones have to be imported <em>explicitly</em>. So either use</p> <pre><code>from package import submodule </code></pre> <p>or if you <em>really</em> want to use the (discoura...
0
2016-08-30T06:53:48Z
[ "python" ]
Python namespace change of `import package.sub_module; from package import *`
39,219,722
<p>The <a href="https://docs.python.org/3/tutorial/modules.html#importing-from-a-package" rel="nofollow">Python documentation</a> says</p> <blockquote> <p>Consider this code:</p> </blockquote> <pre><code>import sound.effects.echo import sound.effects.surround from sound.effects import * </code></pre> <blockquote> ...
1
2016-08-30T05:55:43Z
39,221,462
<p><strong>Solution</strong>: you have <code>__all__</code> set to empty list i.e. <code>from package import *</code> basically imports nothing</p> <p>set it to <code>__all__ = ['submodule']</code> in <code>__init__.py</code></p> <hr> <blockquote> <p>What exactly is <strong>__all__</strong> ?</p> </blockquote> <p...
0
2016-08-30T07:34:53Z
[ "python" ]
Reverse for 'registration_register' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
39,219,732
<p>I am trying to make a link in the sidebar of my Person model as persons. For that I made a templatetags folder where my member_template_tags.py:</p> <pre><code>from django import template from member.models import Person register = template.Library() @register.inclusion_tag('member/person_list.html') def get_perso...
0
2016-08-30T05:56:22Z
39,220,774
<p>There are too many issues with your code to correctly identify what is the problem.</p> <ol> <li><p>You have an extra comma in your custom tag:</p> <pre><code>@register.inclusion_tag('member/person_list.html') def get_person_list(): persons= Person.objects.all(), # &lt;-- remove this comma return {'persons...
0
2016-08-30T06:58:41Z
[ "python", "django" ]
Import error with remote interpreter in pycharm
39,219,761
<p>I am trying to run my code in the server using ssh remote interpreter. </p> <p>The connection and the deployment work but when I want to import libraries located in the server it gives an import error </p> <blockquote> <p>ssh://nour@****.com:22/usr/bin/python -u</p> <p>/home/nour/myProject/main.py Traceback...
0
2016-08-30T05:58:25Z
39,244,970
<p>I've found a solution, the environment variables (including python path) should be defined from pycharm: Run/Debug configurations-> Environment variables. Pycharm won't use bashrc paths.</p>
0
2016-08-31T08:52:03Z
[ "python", "ssh", "pycharm", "interpreter" ]
Creating a shallow copy of an instance of a class inheriting from collections.OrderedDict
39,219,821
<p>I have a class inheriting from <code>collections.OrderedDict</code> with an initializer that takes a positional argument <em>without default</em>. My goal is to create a <em>shallow</em> copy of the instance. However, my initial naive approach below does not work and raises a type error as the positional argument mu...
0
2016-08-30T06:02:21Z
39,219,882
<p>you can use python <a href="https://docs.python.org/2/library/copy.html" rel="nofollow">copy</a> library:</p> <pre><code>copied_object = copy.copy(b) </code></pre>
0
2016-08-30T06:06:45Z
[ "python" ]
Handling null inputs for countdown timer: invalid literal for int() with base 10: ''
39,219,944
<p>I've just started out Python and was trying to make a countdown timer and make it unbreakable as possible, however when I enter blank inputs, the while loop won't handle it, and this message would show up instead: invalid literal for int() with base 10: ''. It also pointed the error occurring at the line where it as...
0
2016-08-30T06:10:02Z
39,220,112
<p>A bad string that can not be converted to an int, will raise a ValueError. You catch that exception and just repeat the prompt like this:</p> <pre><code>countdown = 0 while countdown &lt;= 0: try: countdown = int(input("How many seconds would you like the countdown to be?: ")) except ValueError: ...
1
2016-08-30T06:19:43Z
[ "python", "input", "while-loop", "countdown" ]
Permanently changing an outside variable inside a function
39,219,957
<p>I am a huge beginner, but I have a variable that has a value, and I'd like to change it within a function, so that outside of the function the variable is permanently changed. Searching around I've found some information on how to access outside variables (I think their called global variables), but not permanently ...
-1
2016-08-30T06:10:54Z
39,220,008
<p>This is because <em>you do</em> re-assign <code>x</code> every time. <code>x =+ 1 != x += 1</code>. <code>x =+ 1</code> assigns <code>x</code> to <code>1</code>; <code>x += 1</code>, the <em><a href="https://docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements" rel="nofollow">augmented assig...
2
2016-08-30T06:13:39Z
[ "python", "python-3.x", "global-variables" ]
Permanently changing an outside variable inside a function
39,219,957
<p>I am a huge beginner, but I have a variable that has a value, and I'd like to change it within a function, so that outside of the function the variable is permanently changed. Searching around I've found some information on how to access outside variables (I think their called global variables), but not permanently ...
-1
2016-08-30T06:10:54Z
39,220,372
<p>The + sign in the assignment operator is on the wrong side. It should be on the left like this:</p> <pre><code>def variableChanger(): global x x += 1 </code></pre> <p>What you're doing is simply assigning x to the value of +1 over and over; it will just keep getting assigned to 1.</p>
0
2016-08-30T06:36:21Z
[ "python", "python-3.x", "global-variables" ]
Python: Getting Traceback error while executing the code
39,220,086
<p>When I run the code as <code>bzt test.yml</code> I am getting the error. Before it was working fine.</p> <pre><code>C:\etc\tmp\my-test&gt;more test.yml --- execution: concurrency: 50 hold-for: 2m30s ramp-up: 1m scenario: requests: - url: http://server12:12012/ C:\etc\tmp\my-test&gt;b...
0
2016-08-30T06:18:03Z
39,220,862
<pre><code>ImportError: No module named elementtree.ElementTree </code></pre> <p>Are you sure it shouldn't be </p> <pre><code>import xml.etree.ElementTree as etree </code></pre> <p>Otherwise check if you have this dependency installed or if you have a <strong>"elementtree" folder</strong> in your current project tha...
0
2016-08-30T07:02:46Z
[ "python", "elementtree", "bzt" ]
Python: Getting Traceback error while executing the code
39,220,086
<p>When I run the code as <code>bzt test.yml</code> I am getting the error. Before it was working fine.</p> <pre><code>C:\etc\tmp\my-test&gt;more test.yml --- execution: concurrency: 50 hold-for: 2m30s ramp-up: 1m scenario: requests: - url: http://server12:12012/ C:\etc\tmp\my-test&gt;b...
0
2016-08-30T06:18:03Z
39,233,309
<p>Sounds like missing or corrupt <a href="http://lxml.de/" rel="nofollow">lxml</a> package to me. </p> <p>Workarounds are in:</p> <ol> <li>Try out <a href="http://gettaurus.org/msi/" rel="nofollow">Taurus Installer</a></li> <li>Reinstall <code>lxml</code> and/or <code>bzt</code> packages via pip. </li> </ol> <p>Che...
0
2016-08-30T17:07:18Z
[ "python", "elementtree", "bzt" ]
Error Import Impyla library on Windows
39,220,102
<p>I'm having trouble with using impyla library on windows</p> <p>I installed impyla library </p> <p><code>pip install impyla</code></p> <p>Error occured when I tried to import impyla libary in python code</p> <pre><code>from impala.dbapi import connect # error occured from impala.util import as_pandas conn = conn...
1
2016-08-30T06:18:56Z
39,291,522
<p>I had the same problem with thriftpy, the problem on windows is an absolute path is like <strong>C:\foo\bar.thrift</strong> </p> <p>But, the way the thrift library parses the file, it detects the <strong>C:</strong> as if it were a protocol like <strong>http:</strong> or <strong>https:</strong> </p> <p>Its pretty...
0
2016-09-02T11:40:42Z
[ "python", "windows", "impyla" ]
Grouping of documents having the same phone number
39,220,120
<p>My database consists of collection of a large no. of hotels (approx 121,000). </p> <p>This is how my collection looks like :</p> <pre><code>{ "_id" : ObjectId("57bd5108f4733211b61217fa"), "autoid" : 1, "parentid" : "P01982.01982.110601173548.N2C5", "companyname" : "Sheldan Holiday Home", "latit...
0
2016-08-30T06:20:16Z
39,223,350
<p>The easiest answer to any Python in-memory search-for question is "use a dict". Dicts give O(ln N) key-access speed, lists give O(N).</p> <p>Also remember that you can put a Python object into as many dicts (or lists), and as many times into one dict or list, as it takes. They are not copied. It's just a reference....
0
2016-08-30T09:14:03Z
[ "python", "mongodb", "real-time", "aggregation-framework", "mongodb-aggregation" ]
comparision between django model version control packages
39,220,205
<p>I need to implement Django model history version &amp; compare view. </p> <p>I found there are packages like <strong>django-reversion</strong>, <strong>django-simple-history</strong>, <strong>django-revisions</strong> to implement model history version and <strong>django-reversion-compare</strong> for compare view....
-2
2016-08-30T06:26:16Z
39,222,778
<p>You need <code>django-reversion</code> + <code>django-reversion-compare</code>. I have been using <code>django-reversion</code> for at least 5 years and <code>django-reversion-compare</code> is just an add-on for <code>django-reversion</code>, which makes it possible to compare different revisions of the same object...
0
2016-08-30T08:47:10Z
[ "python", "django" ]
Summing List Elements
39,220,215
<p>I'm trying to do this question for this online coding course I'm part of, and one of the questions requires me to add together integers in a list. I've tried to find the answer (and visited a few other pages on this site), but I can't think of anything. Help please!</p> <p>Here's my code so far:</p> <pre><code>tot...
0
2016-08-30T06:26:37Z
39,220,287
<p>Your error is caused because you provide sum with an integer value (<code>iatt = int(i)</code>) when you should be providing it with the contents of the list which is split on <code>','</code>.</p> <p>You have a couple of options for this. Either provide a comprehension to <code>sum</code> and cast every element to...
6
2016-08-30T06:31:12Z
[ "python", "list", "python-3.x" ]
some bug of scikit learn auc function?
39,220,293
<p>Here is the code and output, I think from the output, it mean when fpr is 0, tpr is 0, this is correct as the prediction results marks everything to be 0.</p> <p>But the output also said, when fpr is 1, tpr is also 1. I think it is not correct, since the predictor never predict something to be positive (label to be...
1
2016-08-30T06:31:37Z
39,222,863
<p>These two illustrations would give you a better understanding of how the <em>FPR</em> and <em>TPR</em> get computed.</p> <p><strong><em>Case-1:</em></strong></p> <pre><code>y = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) pred = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) # -^-...
2
2016-08-30T08:52:03Z
[ "python", "machine-learning", "scikit-learn", "roc", "auc" ]
Error:list index out of range
39,220,365
<p>I am a beginner in Python and programming in general and I'm trying to solve a problem on codingbat.com (the problem is called "array_front9" under the section "Warmup-2"). </p> <p>The problem is: "Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less t...
2
2016-08-30T06:35:57Z
39,220,413
<p>The problem states "The array length may be less than 4." Your code currently assumes the array is at least length 4. However, if <code>i</code> is greater than the last index of the list, an <code>IndexError</code> will be thrown.</p> <p>You should first check if <code>len(arr) &lt; 4</code> and return <code>False...
1
2016-08-30T06:38:58Z
[ "python", "arrays", "list" ]
Error:list index out of range
39,220,365
<p>I am a beginner in Python and programming in general and I'm trying to solve a problem on codingbat.com (the problem is called "array_front9" under the section "Warmup-2"). </p> <p>The problem is: "Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less t...
2
2016-08-30T06:35:57Z
39,220,420
<p>You use <code>range(4)</code>. So it will always look for 4 numbers. So when there are only three numbers it will still look for a fourth one. The fourth one doesn't exist so it throws an error. </p> <p>Instead you need to see what the lenght of the list is and then iterate over that lenght.</p> <p>Like this:</p> ...
0
2016-08-30T06:39:18Z
[ "python", "arrays", "list" ]
Error:list index out of range
39,220,365
<p>I am a beginner in Python and programming in general and I'm trying to solve a problem on codingbat.com (the problem is called "array_front9" under the section "Warmup-2"). </p> <p>The problem is: "Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less t...
2
2016-08-30T06:35:57Z
39,220,467
<p>It is given in the problem that the array length may be less than 4. Your are just iterating over an array. You should first check whether the <code>array</code> is at least of <code>length 4</code>. If the <code>array</code> is less than 4 then only iterate through the length of the <code>array</code>.</p> <pre><c...
1
2016-08-30T06:41:57Z
[ "python", "arrays", "list" ]
Error:list index out of range
39,220,365
<p>I am a beginner in Python and programming in general and I'm trying to solve a problem on codingbat.com (the problem is called "array_front9" under the section "Warmup-2"). </p> <p>The problem is: "Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less t...
2
2016-08-30T06:35:57Z
39,220,686
<p>Simply test this expression:</p> <pre><code>9 in arr[:4] </code></pre> <p>I explain:</p> <p>As others have pointed out, your array might be shorter than 4 items, in which case indexing at, say <code>3</code>, the fourth number, will raise an <code>IndexError</code>.</p> <p>But let's use the feature that <code>sl...
1
2016-08-30T06:54:30Z
[ "python", "arrays", "list" ]
Error:list index out of range
39,220,365
<p>I am a beginner in Python and programming in general and I'm trying to solve a problem on codingbat.com (the problem is called "array_front9" under the section "Warmup-2"). </p> <p>The problem is: "Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less t...
2
2016-08-30T06:35:57Z
39,220,778
<p>Easier solution for this problem would be:</p> <pre><code>if len(arr) &gt; 4: if 9 in arr[0:4]: return True else: return False else: print('Array length is shorter than 4') return False </code></pre> <p>If you want to check for 9, even if the list length is less than 4, then below i...
0
2016-08-30T06:58:45Z
[ "python", "arrays", "list" ]
Error:list index out of range
39,220,365
<p>I am a beginner in Python and programming in general and I'm trying to solve a problem on codingbat.com (the problem is called "array_front9" under the section "Warmup-2"). </p> <p>The problem is: "Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less t...
2
2016-08-30T06:35:57Z
39,220,846
<p>You have to get the minimum checking length of the input list:</p> <pre><code>def array_front9(nums): return 9 in nums[:min(4,len(nums))] </code></pre>
0
2016-08-30T07:01:39Z
[ "python", "arrays", "list" ]
Error:list index out of range
39,220,365
<p>I am a beginner in Python and programming in general and I'm trying to solve a problem on codingbat.com (the problem is called "array_front9" under the section "Warmup-2"). </p> <p>The problem is: "Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less t...
2
2016-08-30T06:35:57Z
39,221,060
<p>The problem is <em>"check the first four numbers of a list, to see if any of them is a 9"</em>.</p> <p>Now, if the list is less than 4, then automatically the check will fail:</p> <pre><code>if len(arr) &lt; 4: return false </code></pre> <p>Next, you need to check if the first four items contain nine. There are...
0
2016-08-30T07:12:56Z
[ "python", "arrays", "list" ]
Error:list index out of range
39,220,365
<p>I am a beginner in Python and programming in general and I'm trying to solve a problem on codingbat.com (the problem is called "array_front9" under the section "Warmup-2"). </p> <p>The problem is: "Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less t...
2
2016-08-30T06:35:57Z
39,221,110
<p>Thank you for all your answers, they have been really helpful!</p> <p>I decided to use the IF loop instead of the FOR loop, like this:</p> <pre><code>def array_front9(arr): if 9 in arr[0:4]: return True return False </code></pre> <p>As much as I can see, this solution works no matter what the l...
0
2016-08-30T07:15:31Z
[ "python", "arrays", "list" ]
Rename defaultdict key in Python
39,220,428
<p>I have the following problem: I have a defaultdict called word_count containing words and the number how often they occur. I get this by counting the reply of the Google Speech API. However, this API gives me back things like '\303\266' for the German letter 'ö'. Now I want to go through this dict, test if one of t...
-2
2016-08-30T06:40:05Z
39,220,552
<p>You can do it like so:</p> <pre><code>word_count['ö'] = word_count[key] </code></pre> <p>and then:</p> <pre><code>del word_count[key] </code></pre>
0
2016-08-30T06:47:07Z
[ "python", "defaultdict", "google-speech-api" ]
Rename defaultdict key in Python
39,220,428
<p>I have the following problem: I have a defaultdict called word_count containing words and the number how often they occur. I get this by counting the reply of the Google Speech API. However, this API gives me back things like '\303\266' for the German letter 'ö'. Now I want to go through this dict, test if one of t...
-2
2016-08-30T06:40:05Z
39,220,887
<p>From the discussions get to know that you are treating with list of tuple instead of <code>dict</code>. So <code>list.pop</code> always expect a integer that's why you getting an error.</p> <pre><code>TypeError: list indices must be integers, not str </code></pre> <p>And <code>dict</code> expect it's key. So here ...
1
2016-08-30T07:03:48Z
[ "python", "defaultdict", "google-speech-api" ]
Applying an operation on multiple columns with a fixed column in pandas
39,220,504
<p>I have a dataframe as shown below. The last column shows the sum of values from all the columns i.e. <code>A</code>,<code>B</code>,<code>D</code>,<code>K</code> and <code>T</code>. Please note some of the columns have <code>NaN</code> as well.</p> <pre><code>word1,A,B,D,K,T,sum na,,63.0,,,870.0,933.0 sva,,1.0,,3.0,...
3
2016-08-30T06:44:16Z
39,220,888
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a> for selecting columns from <code>A</code> to <code>T</code>, then divide by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html" rel="no...
4
2016-08-30T07:03:51Z
[ "python", "pandas", "dataframe", "sum", "multiple-columns" ]
Applying an operation on multiple columns with a fixed column in pandas
39,220,504
<p>I have a dataframe as shown below. The last column shows the sum of values from all the columns i.e. <code>A</code>,<code>B</code>,<code>D</code>,<code>K</code> and <code>T</code>. Please note some of the columns have <code>NaN</code> as well.</p> <pre><code>word1,A,B,D,K,T,sum na,,63.0,,,870.0,933.0 sva,,1.0,,3.0,...
3
2016-08-30T06:44:16Z
39,221,210
<pre><code>df1 = df.iloc[:, :-1] df2 = df1.div(df1.sum(1), axis=0) df2.mul(np.log(df2)).sum(1) word1 na -0.247187 sva -0.038471 a -0.469774 sa -0.184881 su -0.958774 waw -0.464188 dtype: float64 </code></pre> <h3>Setup</h3> <pre><code>from StringIO import StringIO import pandas as pd text = """word...
2
2016-08-30T07:21:58Z
[ "python", "pandas", "dataframe", "sum", "multiple-columns" ]