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 |
|---|---|---|---|---|---|---|---|---|---|
Expression-combination of "A or B or both" | 37,997,114 | <p>Here is what I currently have:</p>
<pre><code>_filter_date_range = pp.Group(_keyword_date + pp.Group(
pp.Group(_function_before + _argument_string) & pp.Group(_function_after + _argument_string)
))
</code></pre>
<p>Since I use <code>Each</code>(<code>&</code>), both expressions are required. But I want... | 1 | 2016-06-23T16:28:56Z | 37,999,933 | <p>@Rob's third option of <code>EitherOrBoth</code> works very well in this case, I think, but pyparsing's <code>Each</code> really comes into its own when you have to deal with 3 or more expressions that can occur in any order:</p>
<pre><code>from pyparsing import Literal, Each
A = Literal("A")
B = Literal("B")
C = ... | 2 | 2016-06-23T19:12:52Z | [
"python",
"pyparsing"
] |
Pandas Dataframe, looking for way to speed up df.apply that uses math | 37,997,127 | <p>I am using a Pandas Dataframe that has 29M rows. I am doing a computation based on four columns which are all floats.</p>
<p>This call is taking over 1100 seconds:</p>
<pre><code>df['d_from_avg'] = df.apply(lambda row: \
math.sqrt((row.x - row.avg_x)**2 + (row.y - row.avg_y)**2),axis=1)
</code></pre>
<p>Woul... | 0 | 2016-06-23T16:29:24Z | 37,997,284 | <p>You can make use of the vectorized operations instead of calculating row by row. </p>
<p>Try this:</p>
<pre><code>import numpy as np
np.sqrt((df['x'] - df['avg_x'])**2 + (df['y'] - df['avg_y'])**2)
</code></pre>
<p>It will be much faster than apply (tried it on a dataframe with 1000 rows):</p>
<pre><code>%timei... | 2 | 2016-06-23T16:37:35Z | [
"python",
"performance",
"python-2.7",
"pandas",
"dataframe"
] |
Can enumerate be used to count the occurrence of some condition? | 37,997,203 | <p>I want to count how many times the item of a list satisfy one condition. For example a[i] > 1:</p>
<pre><code>a = [2,4,3,0]
counter = 0
for value in a:
if value > 1:
counter += 1
</code></pre>
<p>Is it possible to use the <code>enumerate</code> function to do it and avoid the counter += 1?</p>
<p>... | -1 | 2016-06-23T16:33:36Z | 37,997,240 | <p>You can use a list comprehension- bonus points because they're damn fast (list comps are implemented in C)</p>
<pre><code>a = [2,3,4,0]
count = len([i for i in a if i > 1])
# Or, to avoid a temporary list: (courtesy of John Kugelman)
count = sum(1 for i in a if i > 1)
</code></pre>
<p>Explain:</p>
<pre><cod... | 3 | 2016-06-23T16:35:12Z | [
"python",
"list",
"enumeration"
] |
Python: Accessing a particular cell in a data frame, change it, then save into a new version of the data frame | 37,997,300 | <p>Using Pandas, I have a data frame with a column containing a string that I am splitting when a ; or , is seen:</p>
<pre><code>import re
re.split(';|,',x)
</code></pre>
<p>I want to iterate through the column in the whole data frame and create a copy of the current data frame with the new splits.</p>
<p>This is wh... | 1 | 2016-06-23T16:38:25Z | 37,998,055 | <p>Let me first describe how indexing works for pandas dataframe. Assuming you have the following daframe:</p>
<pre><code>df = DataFrame(randn(5,2),index=range(0,10,2),columns=list('AB'))
In [12]: df
Out[12]:
A B
0 0.767612 0.322622
2 0.875476 2.819955
4 1.876320 -1.591170
6 0.645850 ... | 0 | 2016-06-23T17:22:09Z | [
"python",
"for-loop",
"pandas"
] |
Python readline not working with codecs | 37,997,312 | <p>I am trying to open, print, and read a text file that contains special characters such as §. Below is the code I am running:</p>
<pre><code> import codecs
f = codecs.open('sample_text.txt', mode='r', encoding='utf_8')
print f.readline()
</code></pre>
<p>The first two lines work, but the third does not.... | -1 | 2016-06-23T16:39:12Z | 37,997,589 | <p>To expand on what the commenters said, you need to find out the encoding of your file. The easiest way I know to do that is to:</p>
<ol>
<li>Open the file in Firefox.</li>
<li>Right-click on the page and select "View Page Info"</li>
<li>See what the "Text Encoding" is.</li>
<li>Then you can check the <a href="http... | 1 | 2016-06-23T16:55:57Z | [
"python",
"readline"
] |
Python readline not working with codecs | 37,997,312 | <p>I am trying to open, print, and read a text file that contains special characters such as §. Below is the code I am running:</p>
<pre><code> import codecs
f = codecs.open('sample_text.txt', mode='r', encoding='utf_8')
print f.readline()
</code></pre>
<p>The first two lines work, but the third does not.... | -1 | 2016-06-23T16:39:12Z | 37,997,975 | <p>It looks like you are on a windows machine where encoding for the text file might be different from UTF-8, you might want to try cp1252/ISO-8859-1 use for decoding the bytestring and then encode it again using utf-8. </p>
<p>You can also take a look here for an advice on a best-practice how to read files - <a href=... | 0 | 2016-06-23T17:17:11Z | [
"python",
"readline"
] |
Plotting results (scatter graph) from DataFrame issues. Python | 37,997,455 | <p>I am plotting a DataFrame as a scatter graph using this code:</p>
<p>My dataframe somewhat looks like this - </p>
<pre><code>Sector AvgDeg
0 1 52
1 2 52
2 3 52
3 4 54
4 5 52
... ... ...
df.plot.scatter(x='Sector', y='AvgDeg', s=df[... | 0 | 2016-06-23T16:48:09Z | 37,997,999 | <p>What you have to do is to use a list of the same size as the points in the <code>c</code> parameter of scatter plot. </p>
<pre><code>cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
txt = ["text1", "text2", "text3", "text4"]
fig, ax = plt.subplots()
x = np.arange(1, 5)
y = np.arange(1, 5)
#c will chan... | 1 | 2016-06-23T17:18:55Z | [
"python",
"pandas",
"plot",
"dataframe"
] |
Plotting results (scatter graph) from DataFrame issues. Python | 37,997,455 | <p>I am plotting a DataFrame as a scatter graph using this code:</p>
<p>My dataframe somewhat looks like this - </p>
<pre><code>Sector AvgDeg
0 1 52
1 2 52
2 3 52
3 4 54
4 5 52
... ... ...
df.plot.scatter(x='Sector', y='AvgDeg', s=df[... | 0 | 2016-06-23T16:48:09Z | 37,999,564 | <p>i would do it this way:</p>
<pre><code>import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.style.use('ggplot')
colorlist = list(mpl.colors.ColorConverter.colors.keys())
ax = df.plot.scatter(x='Sector', y='AvgDeg', s=df.AvgDeg*1.2,
c=(colorlist * len(df))[:len(df)])
df.apply(lambda x... | 0 | 2016-06-23T18:49:32Z | [
"python",
"pandas",
"plot",
"dataframe"
] |
Loop inside of a loop concurrency | 37,997,482 | <p>I have a program that calls info from a txt file. Each line in the text file corresponds to an entire file in a different directory. I want to read info from the txt file (line 1) and write it in an output file with info from corresponding file in directory (file 1). I need my code to work for multiple files. How ca... | 2 | 2016-06-23T16:49:52Z | 37,997,698 | <p>After running <code>files = glob.glob(path)</code>, <code>files</code> contains a list of filename strings. When you run <code>for file in files:</code>, the variable <code>file</code> will contain a string filename. Thus, you can modify the loop as follows:</p>
<pre><code>for file in files:
with open(file) as ... | 0 | 2016-06-23T17:01:02Z | [
"python",
"loops",
"concurrency",
"while-loop"
] |
Loop inside of a loop concurrency | 37,997,482 | <p>I have a program that calls info from a txt file. Each line in the text file corresponds to an entire file in a different directory. I want to read info from the txt file (line 1) and write it in an output file with info from corresponding file in directory (file 1). I need my code to work for multiple files. How ca... | 2 | 2016-06-23T16:49:52Z | 37,998,396 | <p>Based on the conversation, it appears that you do not need to have an inner loop at all. You have multiple nested loops that do not need to exist. I have rewritten portions of your code without them here.</p>
<p>Specifically, if you want to iterate over something and count it at the same time, do <strong><em>not</e... | 2 | 2016-06-23T17:39:59Z | [
"python",
"loops",
"concurrency",
"while-loop"
] |
When using Tornado with WTForms {{ form.field }} display "<input name='field'>" in place of input field? | 37,997,491 | <p>I am using Tornado on Python 2.7 along with wtforms_tornado and wtforms.
I have already developed an Project in Flask using WTForms.
I started to change that project from Flask to Tornado but got stuck at this point.</p>
<p>run.py</p>
<pre><code>class SignupForm(Form):
email=StringField('email',[
validator... | 1 | 2016-06-23T16:50:19Z | 37,998,539 | <p>You need to disable <a href="http://www.tornadoweb.org/en/stable/template.html" rel="nofollow">Tornado's auto-escape feature</a> for that part of your template:</p>
<pre><code>{% raw form.email %}
</code></pre>
| 0 | 2016-06-23T17:48:17Z | [
"python",
"tornado",
"wtforms"
] |
Python How to add numbers as much as user likes | 37,997,497 | <p>I'm learning python for 2 weeks.
So my question is let's say I created a calculator.
How can I add number as much as user likes?</p>
<pre><code>os.system("del *.pyc")
print "Hello %s!" % ad
print "---------------------------------------"
print " *Add"
print " *x Add (Dunno engli... | 0 | 2016-06-23T16:50:35Z | 37,997,659 | <p>I think you are looking for something like this.</p>
<p><strong>Python 2</strong></p>
<pre><code>num = '0'
total = 0
while True: #run loop until user enters something that is not a number
if not num.isdigit():
break #at this point break out of the loop
total += int(num) #else add the number to the ... | 0 | 2016-06-23T16:59:21Z | [
"python",
"python-2.7",
"variables",
"calculator"
] |
Python How to add numbers as much as user likes | 37,997,497 | <p>I'm learning python for 2 weeks.
So my question is let's say I created a calculator.
How can I add number as much as user likes?</p>
<pre><code>os.system("del *.pyc")
print "Hello %s!" % ad
print "---------------------------------------"
print " *Add"
print " *x Add (Dunno engli... | 0 | 2016-06-23T16:50:35Z | 37,997,848 | <p>Do you mean something like...</p>
<pre><code>def is_number(s):
try:
float(s)
return True
except ValueError:
return False
number = 0
input = raw_input('Number: ')
while input != None and input != "":
if not is_number(input):
print "NaN"
continue
number += floa... | 0 | 2016-06-23T17:08:55Z | [
"python",
"python-2.7",
"variables",
"calculator"
] |
Python How to add numbers as much as user likes | 37,997,497 | <p>I'm learning python for 2 weeks.
So my question is let's say I created a calculator.
How can I add number as much as user likes?</p>
<pre><code>os.system("del *.pyc")
print "Hello %s!" % ad
print "---------------------------------------"
print " *Add"
print " *x Add (Dunno engli... | 0 | 2016-06-23T16:50:35Z | 37,998,199 | <p>Try this:</p>
<pre><code>#! python3
# coding=utf-8
"""Add a lot of numbers."""
def add_everything():
""" """
numbers = []
while True:
print("Sum:", sum(numbers) )
s = input("Enter number(s) or just hit Return to quit:")
if not s:
break
for n in s.split():
... | 0 | 2016-06-23T17:29:16Z | [
"python",
"python-2.7",
"variables",
"calculator"
] |
Python Unable to reference a list in a calling class | 37,997,596 | <p>I have a class <code>foo</code> in which I have these two methods. <code>variableLevelDictionary</code> is a dictionary with strings as keys and lists as values. </p>
<pre><code>class foo:
levels = []
specificLevels = []
variableLevelDictionary = {}
def __init__(self):
self.createDictionaryOfVariableAndLevel... | 1 | 2016-06-23T16:56:20Z | 37,998,043 | <p>What I notice is 3 things that could go wrong: </p>
<p>1) In method getVariableLevelDictionary you are trying to return self.variableLevelDictionary when in fact your class "foo" does not have have an attribute of the same name, this means that when you call this function you will get this error: </p>
<p>Attribute... | 1 | 2016-06-23T17:21:30Z | [
"python",
"list",
"python-3.x",
"object",
"dictionary"
] |
When using pd.rolling_max, how can I assign a particular value within the data frame as the window value? | 37,997,627 | <p>the column max should be the max in a range.</p>
<pre><code>if df['y'] >= 1: #then use y as the window...
</code></pre>
<p>currently using:</p>
<pre><code>df['max'] = None
df['max'][df['y']>1] = pd.rolling_max(df['y'], window = df['y']
</code></pre>
<p>result is:</p>
<blockquote>
<p>TypeError: cannot co... | 1 | 2016-06-23T16:58:07Z | 37,998,311 | <p>What you're describing isn't a max over a rolling window. If it were, when <code>y</code> is <code>3</code> in row <code>D</code>, you'd be missing 2 more rows to include in the rolling window. I think you are just after a max of the elements in the row, when <code>df.y >= 1</code>. In this case:</p>
<pre><co... | 0 | 2016-06-23T17:35:22Z | [
"python",
"pandas"
] |
Python: Factory attributes | 37,997,645 | <p>Is <code>setup.inQ</code> different from <code>complete.inQ</code>?</p>
<p>If I put something in one queue, it wouldn't show up in the other queue, correct?</p>
<pre><code>import Queue
class Factory:
name = ""
inQ = Queue.Queue()
outQ = Queue.Queue()
def worker(self): pass
@staticmethod
... | 2 | 2016-06-23T16:58:43Z | 37,997,700 | <p>This is easy enough to test:</p>
<pre><code>>>> import Queue
>>> class A(object):
... q = Queue.Queue()
...
>>> class B(A):
... pass
...
>>> a = A()
>>> b = B()
>>> b.q is a.q
True
</code></pre>
<p>We see that the <code>q</code> attribute is indeed shared... | 2 | 2016-06-23T17:01:06Z | [
"python",
"factory"
] |
removing strings from a python list based on Hamming distance | 37,997,674 | <p>I have a list</p>
<pre><code>l = ['ATCGGG','CGGGAT,CGGGAA','ATGGCC,CTCCCT,CTCCGT,TTAAGG']
</code></pre>
<p>I want to compute the Hamming distance between strings in each element of the list and drop the strings which are less than or equal to a Hamming distance of 1 of another one. Example the expected output is</... | 2 | 2016-06-23T17:00:01Z | 37,998,471 | <p>This produces exactly the output you said you wanted:</p>
<pre><code>result = []
for group in l:
pieces = group.split(",")
thischunk = []
for piece in pieces:
if all(hamming(piece, base) > 1 for base in thischunk):
thischunk.append(piece)
result.append(",".join(thischunk))
pri... | 2 | 2016-06-23T17:44:35Z | [
"python"
] |
How to convert a String into a BeautifulSoup object? | 37,997,702 | <p>I'm trying to crawl a news website and I need to change one parameter. I changed it with replace with the next code:</p>
<pre><code>while i< len(links):
conn = urllib.urlopen(links[i])
html = conn.read()
soup = BeautifulSoup(html)
t = html.replace('class="row bigbox container mi-df-local locked-single"', 'class=... | 1 | 2016-06-23T17:01:19Z | 37,997,717 | <p>Just do the replacement <em>before parsing</em>:</p>
<pre><code>html = html.replace('class="row bigbox container mi-df-local locked-single"', 'class="row bigbox container mi-df-local single-local"')
soup = BeautifulSoup(html, "html.parser")
</code></pre>
<hr>
<p>Note that it would also be possible (I would even s... | 2 | 2016-06-23T17:02:10Z | [
"python",
"beautifulsoup",
"web-crawler"
] |
Python: trying to avoid using a global variable for a time_passed function | 37,997,703 | <p>I am new to Python and am using a method time_passed() for keeping track of how much time has passed.</p>
<p>I would prefer not to use a global variable. Is there a way to write this method so that it doesn't take any parameters and it doesn't use a global variable?</p>
<pre><code>import time
start_time=time.tim... | 0 | 2016-06-23T17:01:20Z | 37,997,880 | <p>The static variable equivalent in Python is similar to Javascript where assigning a variable under a particular object namespace gives it persistence outside of method scope it was assigned in. Just like in Javascript, Python functions are objects and can be assigned member variables.</p>
<p>So for this example you... | 2 | 2016-06-23T17:10:55Z | [
"python",
"python-2.7",
"time",
"global-variables"
] |
Python: trying to avoid using a global variable for a time_passed function | 37,997,703 | <p>I am new to Python and am using a method time_passed() for keeping track of how much time has passed.</p>
<p>I would prefer not to use a global variable. Is there a way to write this method so that it doesn't take any parameters and it doesn't use a global variable?</p>
<pre><code>import time
start_time=time.tim... | 0 | 2016-06-23T17:01:20Z | 37,997,981 | <p>You can write a simple class storing the start time:</p>
<pre><code>import time
class Timer:
def __init__(self):
self.start = time.time()
def __call__(self):
return time.time() - self.start
</code></pre>
<p>Then use it like:</p>
<pre><code>time_passed = Timer()
print time_passed()
</code... | 1 | 2016-06-23T17:17:30Z | [
"python",
"python-2.7",
"time",
"global-variables"
] |
Python: trying to avoid using a global variable for a time_passed function | 37,997,703 | <p>I am new to Python and am using a method time_passed() for keeping track of how much time has passed.</p>
<p>I would prefer not to use a global variable. Is there a way to write this method so that it doesn't take any parameters and it doesn't use a global variable?</p>
<pre><code>import time
start_time=time.tim... | 0 | 2016-06-23T17:01:20Z | 37,998,187 | <p>Generator should be used for functions that need to encapsulate state.</p>
<pre><code>import time
def time_passed_generator():
start_time = time.time()
while True:
yield time.time() - start_time
time_passed = time_passed_generator()
#start
next(time_passed) # should be about 0.0
# ... later ge... | 1 | 2016-06-23T17:28:47Z | [
"python",
"python-2.7",
"time",
"global-variables"
] |
IDLE's subprocess didn't make a connection. Either IDLE can't start or personal firewall software is blocking connection | 37,997,715 | <p>I have tried uninstalling it and have searched other answers. None of them have worked; IDLE opens, but I can't run anything I write.</p>
| 0 | 2016-06-23T17:02:02Z | 38,001,829 | <p>This question has been asked before. Based on previous answers, I compiled a list of possible causes and solution on CPython tracker <a href="https://bugs.python.org/issue25514" rel="nofollow">issue 25514</a>, post of 2016-01-18.</p>
<p><a href="https://stackoverflow.com/questions/15888186/cant-run-python-via-idle-... | 0 | 2016-06-23T21:03:17Z | [
"python",
"python-idle"
] |
Splitting DataFrame rows with pandas | 37,997,768 | <p>I am currently trying to figure out efficient way to split single panadas DataFrame rows into multiple, slightly changed rows. Imagine such structure:</p>
<pre><code> A C1 C2 C3 C4
1 a b c a
2 b a e b a
3 g c
4 d e
</code></pre>
<p>and I want to end up with structure like that:</p>... | 3 | 2016-06-23T17:05:13Z | 37,997,822 | <p>try this:</p>
<pre><code>In [10]: pd.melt(df, id_vars='A', value_vars=['C1','C2','C3','C4'])
Out[10]:
A variable value
0 a C1 b
1 b C1 a
2 g C1 c
3 d C1 e
4 a C2 c
5 b C2 e
6 g C2 NaN
7 d C2 NaN
8 a C3 a
9 ... | 3 | 2016-06-23T17:07:40Z | [
"python",
"pandas"
] |
How to undo sys.path.append(pathToModule) | 37,997,934 | <p>I have been trying to fix the python path on my cpu, and I originally was just trying to change my <code>.bash_profile</code>, but that wasn't working, so I used</p>
<pre><code>import sys
sys.pat.append(path/To/Module)
</code></pre>
<p>and now when I run my script, I get this error message </p>
<blockquote>
<p>... | 0 | 2016-06-23T17:14:01Z | 37,998,088 | <p>Note that if you add a path with sys.path.append() you do this only for the current session. No need to undo it.</p>
<p>Just remove the line from you python file.</p>
| 0 | 2016-06-23T17:23:53Z | [
"python",
"python-2.7",
"import",
"pythonpath",
"sys.path"
] |
How to undo sys.path.append(pathToModule) | 37,997,934 | <p>I have been trying to fix the python path on my cpu, and I originally was just trying to change my <code>.bash_profile</code>, but that wasn't working, so I used</p>
<pre><code>import sys
sys.pat.append(path/To/Module)
</code></pre>
<p>and now when I run my script, I get this error message </p>
<blockquote>
<p>... | 0 | 2016-06-23T17:14:01Z | 37,998,110 | <p>Have you tried <code>sys.path.pop()</code><br>
That will remove the last item that you added or indeed the last item on the PYTHONPATH, whatever that might be.</p>
| 0 | 2016-06-23T17:25:21Z | [
"python",
"python-2.7",
"import",
"pythonpath",
"sys.path"
] |
How to undo sys.path.append(pathToModule) | 37,997,934 | <p>I have been trying to fix the python path on my cpu, and I originally was just trying to change my <code>.bash_profile</code>, but that wasn't working, so I used</p>
<pre><code>import sys
sys.pat.append(path/To/Module)
</code></pre>
<p>and now when I run my script, I get this error message </p>
<blockquote>
<p>... | 0 | 2016-06-23T17:14:01Z | 37,998,180 | <blockquote>
<p>How can I either fix this issue or undo the >sys.path.append(path/To/Module)?</p>
</blockquote>
<p>To undo the <code>sys.path.append</code>, you just need to remove that line from your script. Since the path is only modified for your current script and not system wide until you edit the <code>PYTHONP... | 0 | 2016-06-23T17:28:26Z | [
"python",
"python-2.7",
"import",
"pythonpath",
"sys.path"
] |
How to input data within Jupyter Notebook | 37,997,946 | <p>I have searched for but have not found a solution to this:</p>
<p>Is there a way to create data <strong>within</strong> Jupyter Notebook, particularly tabular data in the form of a pandas DataFrame, via a spreadsheet-like interface as opposed to pd.DataFrame({a:[],b:[]})?</p>
<p>I don't mean read csv or XLwings as... | 0 | 2016-06-23T17:15:00Z | 37,998,735 | <p>I have not used it myself, but it seems that <a href="https://github.com/quantopian/qgrid" rel="nofollow">https://github.com/quantopian/qgrid</a> might fit the bill -- they say that the grid is editable as of v0.3.0.</p>
| 0 | 2016-06-23T18:01:05Z | [
"python",
"ipython-notebook",
"jupyter-notebook"
] |
Efficiently searching a large list of URLs | 37,998,013 | <p>I am building a web crawler which has to crawl hundreds of websites. My crawler keeps a list of urls already crawled. Whenever crawler is going to crawl a new page, it first searches the list of urls already crawled and if it is already listed the crawler skips to the next url and so on. Once the url has been crawle... | 0 | 2016-06-23T17:19:37Z | 37,998,220 | <p>You have to decide at some point just how large you want your crawled list to become. Up to a few tens of millions of items, you can probably just store the URLs in a hash map or dictionary, which gives you O(1) lookup.</p>
<p>In any case, with an average URL length of about 80 characters (that was my experience fi... | 3 | 2016-06-23T17:30:36Z | [
"python",
"c++",
"algorithm",
"search"
] |
Efficiently searching a large list of URLs | 37,998,013 | <p>I am building a web crawler which has to crawl hundreds of websites. My crawler keeps a list of urls already crawled. Whenever crawler is going to crawl a new page, it first searches the list of urls already crawled and if it is already listed the crawler skips to the next url and so on. Once the url has been crawle... | 0 | 2016-06-23T17:19:37Z | 37,998,279 | <p>I think hashing your values before putting them into your binary searched list- this will get rid of the probable bottleneck of string comparisons, swapping to int equality checks. It also keeps the O(log2(n)) binary search time- you may not get consistent results if you use python's builtin <code>hash()</code> betw... | -1 | 2016-06-23T17:33:48Z | [
"python",
"c++",
"algorithm",
"search"
] |
Python Matplotlib: plotting histogram with overlapping boundaries removed | 37,998,017 | <p>I am plotting a histogram using Matplotlib in Python with the <code>matplotlib.bar()</code> function. This gives me plots that look like this:</p>
<p><a href="http://i.stack.imgur.com/yj7Dm.png" rel="nofollow"><img src="http://i.stack.imgur.com/yj7Dm.png" alt="enter image description here"></a></p>
<p>I am trying... | 4 | 2016-06-23T17:19:55Z | 37,998,100 | <p>I guess the easiest way is to use the step function instead of bar:
<a href="http://matplotlib.org/examples/pylab_examples/step_demo.html" rel="nofollow">http://matplotlib.org/examples/pylab_examples/step_demo.html</a></p>
<p>Example:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as pp
# Simulate da... | 4 | 2016-06-23T17:24:34Z | [
"python",
"matplotlib",
"histogram"
] |
Parse non-homogeneous CSV file with Python | 37,998,077 | <p>I have a CSV file structured like this:</p>
<pre><code># Samples 1
1,58
2,995
3,585
# Samples 2
15,87
16,952
17,256
# Samples 1
4,89
5,63
6,27
</code></pre>
<p>Is there any way in Python 3.x, how to parse a file structured like this without having to manually go through it line-by-line?</p>
<p>I'd like to have ... | 0 | 2016-06-23T17:23:20Z | 37,998,258 | <p>Something like this?</p>
<pre><code>input="""# Samples 1
1,58
2,995
3,585
# Samples 2
15,87
16,952
17,256
# Samples 1
4,89
5,63
6,27"""
def parse(input):
parsed = {}
lines = input.split("\n")
key = "# Unknown"
for line in lines:
if line is None or line == "": # ignore empty line
... | 1 | 2016-06-23T17:32:46Z | [
"python",
"python-3.x",
"csv",
"parsing"
] |
Parse non-homogeneous CSV file with Python | 37,998,077 | <p>I have a CSV file structured like this:</p>
<pre><code># Samples 1
1,58
2,995
3,585
# Samples 2
15,87
16,952
17,256
# Samples 1
4,89
5,63
6,27
</code></pre>
<p>Is there any way in Python 3.x, how to parse a file structured like this without having to manually go through it line-by-line?</p>
<p>I'd like to have ... | 0 | 2016-06-23T17:23:20Z | 38,134,063 | <p>groupby will do all the iterating and grouping for you. In this case, you only care about those contiguous groups of lines that contain a ',' (or are composed only of ',' and digits, or whatever other filter predicate you care to define):</p>
<pre><code>input="""# Samples 1
1,58
2,995
3,585
# Samples 2
15,87
16,95... | 0 | 2016-06-30T22:10:43Z | [
"python",
"python-3.x",
"csv",
"parsing"
] |
Print just the sheetnames with Python | 37,998,101 | <p>How can I print just the sheet names. I using a loop that gets the sheets from range 2 to 9 and prints but I would like to remove the label around it and just print the name of the sheet.</p>
<pre><code>import glob
import openpyxl
path = 'C:/ExcelFolder/*.xlsx'
files = glob.glob(path)
for file in files:
wb = open... | -1 | 2016-06-23T17:24:41Z | 37,998,141 | <p>How about: <code>print(wb.sheetnames)</code></p>
| 1 | 2016-06-23T17:26:44Z | [
"python",
"excel",
"openpyxl"
] |
Print just the sheetnames with Python | 37,998,101 | <p>How can I print just the sheet names. I using a loop that gets the sheets from range 2 to 9 and prints but I would like to remove the label around it and just print the name of the sheet.</p>
<pre><code>import glob
import openpyxl
path = 'C:/ExcelFolder/*.xlsx'
files = glob.glob(path)
for file in files:
wb = open... | -1 | 2016-06-23T17:24:41Z | 37,998,759 | <pre><code>from openpyxl.reader.excel import load_workbook
import glob
path = '*.xlsx'
files = glob.iglob(path)
for fileName in files:
wb=load_workbook(fileName)
w = wb.sheetnames
for sheetname in w:
print sheetname
</code></pre>
| -1 | 2016-06-23T18:02:34Z | [
"python",
"excel",
"openpyxl"
] |
Error while re-opening sound file in python | 37,998,135 | <p>I was in the process of making a program that simply repeats any text you enter, and seemed to be working when I first tested it. The problem is that the second time I attempt to type anything, it crashes and says that permission was denied to the sound file I was recording it to. I believe it is because the file wa... | 2 | 2016-06-23T17:26:34Z | 37,998,857 | <p>To expand on my comment above (with help from <a href="http://stackoverflow.com/questions/7746263/how-play-mp3-with-pygame">this thread</a>), I think <code>play()</code> may be locking the file. You can manually try the following:</p>
<pre><code>def play():
mixer.init()
mixer.music.load("Speech.mp3")
mi... | 0 | 2016-06-23T18:07:55Z | [
"python",
"pygame",
"mp3"
] |
Error while re-opening sound file in python | 37,998,135 | <p>I was in the process of making a program that simply repeats any text you enter, and seemed to be working when I first tested it. The problem is that the second time I attempt to type anything, it crashes and says that permission was denied to the sound file I was recording it to. I believe it is because the file wa... | 2 | 2016-06-23T17:26:34Z | 37,999,477 | <p>Figured it out. I added this function:</p>
<pre><code>def delete():
sleep(2)
mixer.music.load("Holder.mp3")
os.remove("Speech.mp3")
</code></pre>
<p>And call it after <code>.play()</code>, so it now simply deletes the file when it is done and then re-creates it when you need to use it next.</p>
| 1 | 2016-06-23T18:45:06Z | [
"python",
"pygame",
"mp3"
] |
Error while re-opening sound file in python | 37,998,135 | <p>I was in the process of making a program that simply repeats any text you enter, and seemed to be working when I first tested it. The problem is that the second time I attempt to type anything, it crashes and says that permission was denied to the sound file I was recording it to. I believe it is because the file wa... | 2 | 2016-06-23T17:26:34Z | 38,002,488 | <p>I fixed the problem by writing to a temporary file and using <code>os.rename</code>:</p>
<pre><code>from gtts import gTTS
from pygame import mixer
import os
play_name = 'Speech.mp3'
save_name = "%s.%s" % (play_name, '.tmp')
def play():
mixer.music.load(play_name)
mixer.music.play()
def voice(x):
text... | 0 | 2016-06-23T21:51:30Z | [
"python",
"pygame",
"mp3"
] |
Perform full Merge between the columns of two data frames, based on starting alphabet | 37,998,243 | <p>I want to perform full merge between the values of two columns (Name) of two different data frames. Merge should only be done between Names starting with same alphabet. For eg. ABC should be merged with all Names of other data frame which start with letter 'A'. And this should be done for all letters 'A' to 'Z'. I a... | 1 | 2016-06-23T17:31:42Z | 37,998,570 | <p>I'd create a column of 'FirstLetter' and <code>[merge][1]</code> on that.</p>
<pre><code>import pandas as pd
import numpy as np
from string import ascii_uppercase
df1 = pd.DataFrame(np.random.choice(list(ascii_uppercase), (5, 3)))
df1 = df1.apply(lambda x: pd.Series([''.join(x)], index=['Name']), axis=1)
df1['Firs... | 0 | 2016-06-23T17:50:10Z | [
"python",
"pandas"
] |
How can I monitor input on a USB port in Windows? | 37,998,294 | <p>Short version: How do I monitor a USB port's input?</p>
<p>Long version: I wanted to use a console controller for my pc games, but couldn't find a freeware method of doing so that I liked. So I decided to make one myself, as much as a learning exercise as anything else, but I'm not sure how to monitor input on a US... | 1 | 2016-06-23T17:34:22Z | 37,998,352 | <p>Try <code>pyusb</code> and you will find examples on how to communicate with USB devices. It seems that the current repository is at GitHub: <a href="https://github.com/walac/pyusb" rel="nofollow">https://github.com/walac/pyusb</a></p>
| 0 | 2016-06-23T17:37:32Z | [
"python",
"c++",
"usb"
] |
python gettext: specify locale in _() | 37,998,300 | <p>I am looking fo a way to set the language on the fly when requesting a translation for a string in gettext. I'll explain why : </p>
<p>I have a multithreaded bot that respond to users by text on multiple servers, thus needing to reply in different languages.
The <a href="http://www.enseignement.polytechnique.fr/inf... | 2 | 2016-06-23T17:34:41Z | 38,001,061 | <p>The following simple example shows how to use a separate process for each translator:</p>
<pre><code>import gettext
import multiprocessing
import time
def translation_function(language):
try:
lang = gettext.translation('simple', localedir='locale', languages=[language])
lang.install()
w... | 1 | 2016-06-23T20:18:53Z | [
"python",
"multithreading",
"python-3.x",
"internationalization",
"gettext"
] |
python gettext: specify locale in _() | 37,998,300 | <p>I am looking fo a way to set the language on the fly when requesting a translation for a string in gettext. I'll explain why : </p>
<p>I have a multithreaded bot that respond to users by text on multiple servers, thus needing to reply in different languages.
The <a href="http://www.enseignement.polytechnique.fr/inf... | 2 | 2016-06-23T17:34:41Z | 38,004,947 | <p>I took a moment to whip up a script that uses <em>all</em> the locales available on the system, and tries to print a well-known message in them. Note that "all locales" includes mere encoding changes, which are negated by Python anyway, and plenty of translations are incomplete so do use the fallback.</p>
<p>Obviou... | 1 | 2016-06-24T02:56:29Z | [
"python",
"multithreading",
"python-3.x",
"internationalization",
"gettext"
] |
python gettext: specify locale in _() | 37,998,300 | <p>I am looking fo a way to set the language on the fly when requesting a translation for a string in gettext. I'll explain why : </p>
<p>I have a multithreaded bot that respond to users by text on multiple servers, thus needing to reply in different languages.
The <a href="http://www.enseignement.polytechnique.fr/inf... | 2 | 2016-06-23T17:34:41Z | 38,016,024 | <p>The following example uses the <code>translation</code> directly, as shown in <a href="http://stackoverflow.com/users/1405588/o11c">o11c's</a> <a href="http://stackoverflow.com/a/38004947/3657941">answer</a> to allow the use of threads:</p>
<pre><code>import gettext
import threading
import time
def translation_fun... | 1 | 2016-06-24T14:39:04Z | [
"python",
"multithreading",
"python-3.x",
"internationalization",
"gettext"
] |
Make a list of folders containing file names | 37,998,319 | <p>I currently know how to create a list of files that are in the current directory using:</p>
<pre><code>files = [os.path.join(root, name)
for root, dirs, files in os.walk(os.getcwd())
for name in files
if name.endswith(".fastq")]
</code></pre>
<p>However, I would like the list 'files' to ... | 0 | 2016-06-23T17:35:52Z | 37,998,862 | <p>Is this what you are looking for?</p>
<pre><code>import os
import json
file_list = dict()
for root, dirs, files in os.walk(os.getcwd()):
for name in files:
if name.endswith('.fastq'):
if root not in file_list:
file_list[root] = [name]
else:
file_li... | 1 | 2016-06-23T18:08:06Z | [
"python",
"file",
"terminal"
] |
how to show records related to a certain user in django admin | 37,998,362 | <p>I want to create a way for users to only be able to edit/add objects (Company objects) related with the logged in user.</p>
<p>Currently all logged in users are able to edit all Companys even when I create permissions to:</p>
<pre><code>Company | Can Add Company
Company | Can Change Company
</code></pre>
<p>What ... | 1 | 2016-06-23T17:38:11Z | 38,000,520 | <p>Maybe <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_queryset" rel="nofollow"><code>ModelAdmin.get_queryset()</code></a> can help. You can use it to perform checks on the <code>request.user</code> object.</p>
<pre><code>class MyModelAdmin(admin.ModelAdmin):
... | 1 | 2016-06-23T19:45:50Z | [
"python",
"django",
"django-admin",
"user-permissions"
] |
How to efficiently chain ipyparallel tasks and pass intermediate results to engines? | 37,998,484 | <p>I am trying to chain several tasks together in iPyParallel, like</p>
<pre><code>import ipyparallel
client = ipyparallel.Client()
view = client.load_balanced_view()
def task1(x):
## Do some work.
return x * 2
def task2(x):
## Do some work.
return x * 3
def task3(x):
## Do some work.
return x ... | 1 | 2016-06-23T17:45:04Z | 38,014,975 | <h2>Option 1: chain futures</h2>
<p>IPython parallel isn't the best at doing this because the connection has to be done at the client level. You do have to wait for the results to complete and return to the client before submitting the results. Essentially, your asyncio submit_all is the right way to do it for IPython... | 1 | 2016-06-24T13:46:57Z | [
"python",
"ipython-parallel"
] |
Create new columns based on multiple conditions in Python | 37,998,510 | <p>I have the following dataframe: </p>
<pre><code> data = [
(27450, 27450, 29420,"10/10/2016"),
(29420 , 36142, 29420, "10/10/2016"),
(11 , 11, 27450, "10/10/2016")]
#Create DataFrame base
df = pd.DataFrame(data, columns=("User_id","Actor1","Actor2", "Time"))
</code></pre>
<p>The first column contains the user_id... | 0 | 2016-06-23T17:46:40Z | 37,998,779 | <p>Heres my solution - I have assumed that if userid appears in actor1 column its not necessary it'll be in the same row...</p>
<pre><code>df["Col1"] = [1 if i in df["Actor1"].values else 0 for i in df["User_id"].values]
df["Col2"] = [df.iloc[i]["Actor2"] if j == 1 else df.iloc[i]["Actor1"] for i, j in enumerate(df["C... | 0 | 2016-06-23T18:04:08Z | [
"python",
"pandas",
"select",
"dataframe"
] |
Create new columns based on multiple conditions in Python | 37,998,510 | <p>I have the following dataframe: </p>
<pre><code> data = [
(27450, 27450, 29420,"10/10/2016"),
(29420 , 36142, 29420, "10/10/2016"),
(11 , 11, 27450, "10/10/2016")]
#Create DataFrame base
df = pd.DataFrame(data, columns=("User_id","Actor1","Actor2", "Time"))
</code></pre>
<p>The first column contains the user_id... | 0 | 2016-06-23T17:46:40Z | 37,998,835 | <pre><code>import numpy as np
import pandas as pd
data = [(27450, 27450, 29420,"10/10/2016"),
(29420 , 36142, 29420, "10/10/2016"),
(11 , 11, 27450, "10/10/2016")]
df = pd.DataFrame(data, columns=("User_id","Actor1","Actor2", "Time"))
mask = (df['User_id'] == df['Actor1'])
df['first actor'] = mask.ast... | 2 | 2016-06-23T18:06:28Z | [
"python",
"pandas",
"select",
"dataframe"
] |
ConfigObj 'un-nest' sections | 37,998,552 | <p>I'm using ConfigObj 5.0.6 to hold many user-defined values, some of which are nested. I use a <code>local.ini</code> to supercede typical values. There is no front-end, so users edit the configs as needed. To make that easier and more intuitive, there are some values that belong at the 'root' level of the config obj... | 1 | 2016-06-23T17:48:52Z | 37,998,600 | <p>According to <a href="http://www.voidspace.org.uk/python/configobj.html#the-config-file-format" rel="nofollow">the documentation</a>, that is not possible:</p>
<blockquote>
<p>In the outer section, single values can only appear before any sub-section.</p>
</blockquote>
| 1 | 2016-06-23T17:52:21Z | [
"python",
"python-2.7",
"configobj"
] |
Django Run Python script and Pass output to javascript file | 37,998,675 | <h3>I am new to Django</h3>
<h1>What I need:</h1>
<p>1 - Run a python Script
2 - pass data to javascript file </p>
<p>I don't know whether the sentence I am framing is technically correct in terms of Django.</p>
<p>The following is the javascript code and python code resp.</p>
<pre><code>var trace2 = {
x: [-0.... | 1 | 2016-06-23T17:57:29Z | 37,998,760 | <p>in <strong>views.py</strong></p>
<pre><code>def my_view(request,...):
...
render("my_template.html",context={"xyz_list":[[1,2,3],[2,3,4],[4,5,6]]})
</code></pre>
<p>in <strong>my_template.html</strong></p>
<pre><code>...
<script>
var xyz_data_array = {{ xyz_list }} ;
</script>
</code></pr... | 2 | 2016-06-23T18:02:37Z | [
"javascript",
"python",
"django",
"django-templates",
"django-views"
] |
if statement in python regex substitution | 37,998,767 | <p>I have a regex that searches for <code>this</code> or <code>that</code>. If it finds <code>this</code>, it replaces it with <code>ONE</code>. If it finds <code>that</code>, it replaces it with <code>TWO</code>.</p>
<p>Here is what it looks like in Perl:
</p>
<pre><code>m =~ s/(this)|(that)/ "ONE" x!! $1 . "TWO"... | 2 | 2016-06-23T18:02:58Z | 37,998,896 | <p>Python has no strange language syntax related to regular expressions - they are performed in well-behaved function calls.</p>
<p>So instead of a part of the call arguments that are executed on match, what you have is a callback function: all you have to do is to put a callable object as the second argument, instead... | 5 | 2016-06-23T18:10:23Z | [
"python",
"regex",
"perl",
"python-3.x"
] |
import error for a lot of packages | 37,998,817 | <p>Suddenly I can't import numpy or pip or a lot of other packages!
All return import error.</p>
<pre><code>which python
/usr/bin/python
which pip
/home/user/anaconda2/bin/pip
python -V
Python 2.7.11+
pip -V
pip 8.0.2+gx2 from /home/user/anaconda2/lib/python2.7/site-packages (python 2.7)
conda search numpy
nump... | -2 | 2016-06-23T18:05:46Z | 38,001,012 | <p>I somehow reproduce the error, and if you use the python in /home/user/anaconda2/bin instead of /usr/bin, it should be fine</p>
| 0 | 2016-06-23T20:16:06Z | [
"python",
"pip",
"conda"
] |
Fill a list/pandas.dataframe with all the missing data combinations (like complete() in R) | 37,998,861 | <p>I have data set like the following (this is an example, it actually has 66k rows):</p>
<pre><code> Type Food Loc Num
0 Fruit Banana House-1 15
1 Fruit Banana House-2 4
2 Fruit Apple House-2 6
3 Fruit Apple House-3 8
4 Vegetable Broccoli Hou... | 2 | 2016-06-23T18:08:05Z | 37,999,206 | <p>This should work:</p>
<pre><code>cond0 = df.Num.isnull()
cond1 = df.Food == 'Banana'
cond2 = df.Loc.str.match(r'House-[34567]')
cond3 = df.Food == 'Peppers'
cond4 = df.Loc != 'House-5'
missing_bananas = cond0 & cond1 & cond2
missing_peppers = cond0 & cond3 & cond4
missing_food = missing_bananas | m... | 0 | 2016-06-23T18:29:24Z | [
"python",
"dictionary",
"pandas",
"combinations",
"complete"
] |
Fill a list/pandas.dataframe with all the missing data combinations (like complete() in R) | 37,998,861 | <p>I have data set like the following (this is an example, it actually has 66k rows):</p>
<pre><code> Type Food Loc Num
0 Fruit Banana House-1 15
1 Fruit Banana House-2 4
2 Fruit Apple House-2 6
3 Fruit Apple House-3 8
4 Vegetable Broccoli Hou... | 2 | 2016-06-23T18:08:05Z | 37,999,616 | <p>You could use a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a>.</p>
<p>First you'll need a list of the valid <code>(type, food)</code> pairs. I'll get it from the data itself, rather than writing them out.</p>
<pre><code>In [88]... | 2 | 2016-06-23T18:52:49Z | [
"python",
"dictionary",
"pandas",
"combinations",
"complete"
] |
Using Djang ORM, Iterate through table records, test them and delete the record if needed | 37,998,864 | <p>How would you iterate through a table, using the Django ORM, and test the datetime fields to see if they are 8 days old, then delete them if they True.</p>
<pre><code># models.py
from django.db import models
class Tweet(models.Model):
tweet_id = models.Charfield()
tweet_date = models.DatetimeField()
</cod... | 2 | 2016-06-23T18:08:09Z | 37,999,247 | <p>You can directly query the database for more than 8 days old <code>tweets</code> using <code>lte</code> and delete the resultant <code>tweets</code>. There is no need of iterating over the results and then individually deleting all of them.</p>
<pre><code>@shared_task(name='cleanup')
def cleanup():
# filter and... | 3 | 2016-06-23T18:31:30Z | [
"python",
"django",
"datetime",
"orm",
"celery"
] |
Python - Create a PNG image with HTML hex color fill | 37,998,868 | <p>I have a script that generates a random hex code, and from that, I would like to generate an image with the generated color as the fill of the image. I looked at pylab, but was unable to get the result I was looking for. Could someone please assist me in figuring out how to do this?</p>
| -1 | 2016-06-23T18:08:24Z | 37,998,937 | <p>See <a href="https://pypi.python.org/pypi/Pillow" rel="nofollow">https://pypi.python.org/pypi/Pillow</a> to create the image file.</p>
<p>Following <a href="https://pillow.readthedocs.io/en/3.2.x/reference/ImageDraw.html#example-draw-a-gray-cross-over-an-image" rel="nofollow">https://pillow.readthedocs.io/en/3.2.x/... | 1 | 2016-06-23T18:12:50Z | [
"python",
"html",
"colors",
"hex",
"fill"
] |
How to use placeholder inside brackets in python? | 37,998,902 | <p>Today I was wondering about the limitations of python formatting of strings. For example, say you want to build this kind of string : <code>${SOME_APPLICATION_VAR}</code></p>
<p>If <code>SOME_APPLICATION_VAR</code> is not known in advance, how would you build this string ?</p>
<p>I tried <code>"${{}}".format(varia... | 3 | 2016-06-23T18:10:45Z | 37,998,929 | <p>You need to use 3 of each bracket. 2 get resolved into a literal set of brackets, and the last set acts as the placeholder for the formatting.</p>
<pre><code>print("${{{}}}".format(variable_name))
</code></pre>
| 4 | 2016-06-23T18:12:19Z | [
"python",
"string-formatting"
] |
Remove entire row from CSV (if blank) | 37,998,928 | <p>I have a data file from an instrument that outputs as a CSV. Reading the file and the corresponding columns are no issue, however, due to a slight change in instrumentation, the data file has changed and I'm not sure how to change my code to still read the file.</p>
<pre><code>f = open('Rotator_050816.dat')
lines =... | 2 | 2016-06-23T18:12:15Z | 37,999,110 | <p>1) Open the file in read-only mode and get all the lines</p>
<pre><code>lines_in_my_file = []
with open("my_file.csv", "r") as my_file:
lines_in_my_file = my_file.readlines()
</code></pre>
<p>2) Open the file again, this time in write mode, and write all non-blank lines into the file:</p>
<pre><code>with open... | 1 | 2016-06-23T18:24:10Z | [
"python",
"csv",
"matplotlib",
"scientific-computing"
] |
Remove entire row from CSV (if blank) | 37,998,928 | <p>I have a data file from an instrument that outputs as a CSV. Reading the file and the corresponding columns are no issue, however, due to a slight change in instrumentation, the data file has changed and I'm not sure how to change my code to still read the file.</p>
<pre><code>f = open('Rotator_050816.dat')
lines =... | 2 | 2016-06-23T18:12:15Z | 38,004,484 | <p>Here is my working solution that I have implemented:</p>
<pre><code>while (i<len(lines)):
data = lines[i].split(",")
if float(data[4]) >30000 and float(data[4]) <50000:
Temp_II.append(float(data[3])) #As K
Field_II.append(float(data[4])) #As Oe
Position_II.append(float(data[5... | 1 | 2016-06-24T01:50:42Z | [
"python",
"csv",
"matplotlib",
"scientific-computing"
] |
Run own function in pymongo in aggregation pipeline | 37,998,935 | <p>I have a function </p>
<pre><code>distanceFromGPS(latitude1,longitude1,latitude2,longitude2):
latitude2=float(latitude2)
longitude2=float(longitude2)
R = 6371
dLat = math.radians(latitude2-latitude1)
dLon = math.radians(longitude2-longitude1)
a = math.sin(dLat/2) * math.sin(dLat/2) + math.sin(dLon/2) * math.sin(dL... | 1 | 2016-06-23T18:12:44Z | 38,000,002 | <p>Re: After reading all the docs twice, I've come to the conclusion that you can't. You may have to re-write your function using mongo's <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/#aggregation-expression-operators" rel="nofollow">aggregation pipeline operators</a> to get the proper effect.... | 0 | 2016-06-23T19:16:27Z | [
"python",
"mongodb",
"pymongo"
] |
Replace substring string in one table with string in another table for an entire column | 37,999,079 | <p>Whenever there is a matching column/key between dataframe dfa and dfb, I want to change the name of the country in dataframe a with match in dataframe b.</p>
<p><strong>dfa data:<br><br></strong>
<strong>Country</strong><br>
Bolivia<br>
Bosnia-Herzegovina</p>
<p><br><br></p>
<p><strong>dfb data: (full and correct... | 0 | 2016-06-23T18:22:22Z | 37,999,453 | <p>If the two dataframes are lined up row wise or each have an index that already ensures that the correct rows will be matched, then this should work:</p>
<pre><code>dfb.combine_first(dfa)
</code></pre>
<p>If it isn't lined up, meaning "Bolivia" is labeled row 0 in dfa and "Bolivia, Plurinational State of" is labele... | 0 | 2016-06-23T18:44:01Z | [
"python",
"string",
"pandas"
] |
Element wise dot product of tensors in theano | 37,999,113 | <p>Is there a way to do an element wise dot product of tensors in theano. Suppose I have the following tensors:<br/></p>
<pre><code>>>>t1.shape.eval()
array([5, 3, 3])
>>>t2.shape.eval()
array([5, 3, 1)])
</code></pre>
<p>How can i do a dot product, so that each of the 5 (3*3) matrices of t1 get dot... | 0 | 2016-06-23T18:24:23Z | 38,002,569 | <p>I believe if you shuffle your second tensor, <code>t2</code>, along the 2nd axis (index = 1 because its 0-indexed), you could then use <code>theano.tensor.tensordot()</code> (<a href="http://deeplearning.net/software/theano/library/tensor/basic.html" rel="nofollow">reference</a>) to get the desired result. </p>
<pr... | 0 | 2016-06-23T21:57:14Z | [
"python",
"theano",
"deep-learning",
"lstm"
] |
How to not unpack all returned from a query? | 37,999,159 | <p>I have the following query (notice not a normal SELECT):</p>
<pre><code>sql = "SHOW PROCEDURE STATUS WHERE Db <> 'sys' "
</code></pre>
<p>Problem this returns many fields, which I need only the first two, see full code:</p>
<pre><code>sql = "SHOW PROCEDURE STATUS WHERE Db <> 'sys' "
self.cursor.execut... | 1 | 2016-06-23T18:27:07Z | 37,999,249 | <p>Try:</p>
<pre><code>res = [(Db,Name) for(Db,Name,*_) in self.cursor]
</code></pre>
<p>The <code>*</code> format in tuple unpacking represents "<em>a "catch-all" name which will be assigned a list of all items not assigned to a "regular" name.</em>"</p>
<p>References:</p>
<ul>
<li><a href="https://www.python.org/... | 1 | 2016-06-23T18:31:33Z | [
"python",
"mysql",
"python-3.x",
"mysql-connector-python"
] |
How to not unpack all returned from a query? | 37,999,159 | <p>I have the following query (notice not a normal SELECT):</p>
<pre><code>sql = "SHOW PROCEDURE STATUS WHERE Db <> 'sys' "
</code></pre>
<p>Problem this returns many fields, which I need only the first two, see full code:</p>
<pre><code>sql = "SHOW PROCEDURE STATUS WHERE Db <> 'sys' "
self.cursor.execut... | 1 | 2016-06-23T18:27:07Z | 37,999,295 | <p>Don't unpack the row into multiple variables to begin with. Just put the row into one variable and take what you want from that.</p>
<pre><code>[(row[0], row[1]) for row in self.cursor]
</code></pre>
<p>or maybe even:</p>
<pre><code>[row[:2] for row in self.cursor]
</code></pre>
| 2 | 2016-06-23T18:34:30Z | [
"python",
"mysql",
"python-3.x",
"mysql-connector-python"
] |
Time formatting strings in Python | 37,999,205 | <p>I'm trying to convert these strings of numbers into a "hh:mm:ss" format. The strings are all different lengths, here are a few: </p>
<pre><code>(212812, 218654, 232527, 235959, 0, 181240, 25959, 153834)
</code></pre>
<p>So I want to turn the above numbers into this: </p>
<pre><code>(21:28:12, 21:86:54, 23:25:27, ... | 0 | 2016-06-23T18:29:21Z | 37,999,454 | <p>As others have pointed out in comments, it's unclear what the right answer is for some inputs (e.g. 1234, which my code would say is 00:12:34). I also decided that 02:59:59 is a better answer than 2:59:59, given the desire to get 00:00:00.</p>
<p>So here's my code, which deals with all of the above inputs correctly... | 2 | 2016-06-23T18:44:02Z | [
"python",
"datetime",
"string-formatting"
] |
Time formatting strings in Python | 37,999,205 | <p>I'm trying to convert these strings of numbers into a "hh:mm:ss" format. The strings are all different lengths, here are a few: </p>
<pre><code>(212812, 218654, 232527, 235959, 0, 181240, 25959, 153834)
</code></pre>
<p>So I want to turn the above numbers into this: </p>
<pre><code>(21:28:12, 21:86:54, 23:25:27, ... | 0 | 2016-06-23T18:29:21Z | 37,999,761 | <p>Well since we're making up answers here's a "solution" that doesn't use regexes:</p>
<pre><code>In [3]: def weird_time_format(fmt):
...: fmt = str(fmt)
...: hours = fmt[:2].ljust(2, '0')
...: mins = fmt[2:4].ljust(2, '0')
...: secs = fmt[4:6].ljust(2, '0')
...: return ':'.join((ho... | 1 | 2016-06-23T19:01:25Z | [
"python",
"datetime",
"string-formatting"
] |
Time formatting strings in Python | 37,999,205 | <p>I'm trying to convert these strings of numbers into a "hh:mm:ss" format. The strings are all different lengths, here are a few: </p>
<pre><code>(212812, 218654, 232527, 235959, 0, 181240, 25959, 153834)
</code></pre>
<p>So I want to turn the above numbers into this: </p>
<pre><code>(21:28:12, 21:86:54, 23:25:27, ... | 0 | 2016-06-23T18:29:21Z | 38,000,207 | <p>Here is another attempt. </p>
<p>The basic concept is adding <code>0</code> if input string length less than <code>6</code>.</p>
<pre><code>a = (212812, 218654, 232527, 235959, 0, 181240, 25959, 153834)
input_list = map(str,a)
for input in input_list:
if len(input) != 6:
input = ''.join(['0' for i in r... | 0 | 2016-06-23T19:27:31Z | [
"python",
"datetime",
"string-formatting"
] |
Time formatting strings in Python | 37,999,205 | <p>I'm trying to convert these strings of numbers into a "hh:mm:ss" format. The strings are all different lengths, here are a few: </p>
<pre><code>(212812, 218654, 232527, 235959, 0, 181240, 25959, 153834)
</code></pre>
<p>So I want to turn the above numbers into this: </p>
<pre><code>(21:28:12, 21:86:54, 23:25:27, ... | 0 | 2016-06-23T18:29:21Z | 38,007,316 | <p>Hope this helps:</p>
<pre><code>data = (212812, 218654, 232527, 235959, 0, 181240, 25959, 153834)
time = map(str, data) #int to string
def conv(time_array):
for t in time_array:
if(len(t) != 6):
t = str(t.zfill(6)) #filling 0's if less than 6
print ':'.join(t[i:i + 2] for i in rang... | 0 | 2016-06-24T06:54:30Z | [
"python",
"datetime",
"string-formatting"
] |
How to pass hex values to a python script from command line | 37,999,293 | <p>I have a simple script that passes a command (hex value) to a uC using I2C. I wanted to pass the address and command values through the command line as argv's.</p>
<p>Here is my code:</p>
<pre><code>import smbus
import time
from sys import argv
bus = smbus.SMBus(1)
addr = argv[1]
cmd = argv[2]
#address is 0x09
#... | 0 | 2016-06-23T18:34:28Z | 37,999,386 | <pre><code>import smbus
import time
from sys import argv
bus = smbus.SMBus(1)
if sys.argv[1].startswith("0x"): # base 16
addr = int(argv[1][2:],16)
cmd = int(argv[2][2:],16)
else: # base 10
addr = int(argv[1])
cmd = int(argv[2])
print [addr,cmd] # you should see no quotes indicating that these are inde... | 2 | 2016-06-23T18:40:05Z | [
"python",
"command-line-arguments"
] |
'Invalid type comparison' in the code | 37,999,389 | <p>I have a <code>pandas dataframe</code> which has many columns. These columns may have 3 values - True, False and NaN. I'm replcaing the <code>NaN</code> with the string <code>missing</code>. The sample values for one of my columns is as follows:</p>
<pre><code>ConceptTemp.ix[:,1].values
</code></pre>
<p>resulting ... | 0 | 2016-06-23T18:40:14Z | 37,999,975 | <p>As people have commented, it is a bit weird to combine types in your arrays (i.e. strings with booleans). You're going to get results where the boolean array may not be what you think it is. But if you absolutely have to, there are a couple of ways you could go about doing this. The first is with <code>isin</code>:<... | 2 | 2016-06-23T19:15:10Z | [
"python",
"pandas",
"dataframe"
] |
How to set path to python (venv) executable in atom editor | 37,999,400 | <p>I'm trying to switch to Atom Editor for my python projects. I have several of those and each is set up using <code>virtualenv</code>. </p>
<p>How do I set up this editor, so that when I open up one project it will be using <code>python.exe</code> from its path and not some other? </p>
<p>I don't want to add anythi... | 0 | 2016-06-23T18:40:56Z | 38,010,189 | <p>It seems that python-autocomplete plugin is all we need in atom python coding. Just set your virtualenv from the console, then type <code>atom .</code> and editor (accompanied with aforementioned plugin) will pick that up. No other configuration is necessary.</p>
| 0 | 2016-06-24T09:36:35Z | [
"python",
"virtualenv",
"atom"
] |
Pipe the output of a program as args into a Python script? | 37,999,433 | <p>I'm writing a script to take in the JSON output of some LXD containers in my infrastructure. LXD pretty-prints some JSON and I was to feed that JSON into my Python script.</p>
<pre><code>python myscript.py | lxc list --format json
</code></pre>
<p>What can I do in my script to read this data correctly or have it h... | -3 | 2016-06-23T18:42:58Z | 37,999,559 | <p>it is <code>pipe from | pipe to</code> so if you want to pipe lxc to python switch it to the other way</p>
<pre><code>lxc list --format json | python myscript.py
</code></pre>
| 3 | 2016-06-23T18:49:17Z | [
"python",
"json"
] |
pandas: Grouping or filtering based on values in list, instead of dataframe | 37,999,632 | <p>I want to get a row count of the frequency of each value, even if that value doesn't exist in the dataframe.</p>
<pre><code>d = {'light' : pd.Series(['b','b','c','a','a','a','a'], index=[1,2,3,4,5,6,9]),'injury' : pd.Series([1,5,5,5,2,2,4], index=[1,2,3,4,5,6,9])}
testdf = pd.DataFrame(d)
injury light
1 ... | 0 | 2016-06-23T18:53:27Z | 38,002,166 | <p>Try this: </p>
<pre><code>df = pd.crosstab(df.light, df.injury,margins=True)
df
injury 1 2 4 5 All
light
a 0 2 1 1 4
b 1 0 0 1 2
c 0 0 0 1 1
All 1 2 1 3 7
df["All"]
light
a 4
b 2
c 1
All 7
</code></pre>
| 0 | 2016-06-23T21:28:23Z | [
"python",
"pandas"
] |
Python Mplayer Script Doesn't Run While Playing | 37,999,639 | <p>I am very much a noob with Python and Linux commands but I'm trying to wrap my head around it.</p>
<p>My application is bigger than this sample but I am trying to get this working before expanding.</p>
<p>I am using mplayer in slave mode to play a video clip but I want to automatically kill it when the clip is don... | 0 | 2016-06-23T18:53:55Z | 37,999,900 | <p>You can use the <a href="https://docs.python.org/2/library/subprocess.html#module-subprocess" rel="nofollow">subprocess</a> lib as recommended in the <a href="https://docs.python.org/2/library/os.html#os.popen" rel="nofollow">docs</a> which say about os.popen <em>Deprecated since version 2.6: This function is obsole... | 0 | 2016-06-23T19:10:48Z | [
"python",
"mplayer"
] |
parsing linux iscsi multipath.conf into python nested dictionaries | 37,999,670 | <p>I writing a script that involves adding/removing multipath "objects" from the standard multipath.conf configuration file, example below:</p>
<pre><code># This is a basic configuration file with some examples, for device mapper
# multipath.
## Use user friendly names, instead of using WWIDs as names.
defaults {
... | 0 | 2016-06-23T18:56:07Z | 38,002,846 | <p>Try something like this:</p>
<pre><code>def parse_conf(conf_lines):
config = []
# iterate on config lines
for line in conf_lines:
# remove left and right spaces
line = line.rstrip().strip()
if line.startswith('#'):
# skip comment lines
continue
e... | 1 | 2016-06-23T22:22:13Z | [
"python",
"dictionary",
"config",
"iscsi"
] |
parsing linux iscsi multipath.conf into python nested dictionaries | 37,999,670 | <p>I writing a script that involves adding/removing multipath "objects" from the standard multipath.conf configuration file, example below:</p>
<pre><code># This is a basic configuration file with some examples, for device mapper
# multipath.
## Use user friendly names, instead of using WWIDs as names.
defaults {
... | 0 | 2016-06-23T18:56:07Z | 38,012,746 | <p>If you don't use recursion, you will need some way of keeping track of your level. But even then it is difficult to have references to parents or siblings in order to add data (I failed). Here's another take based on Daniele Barresi's mention of recursion on the iterable input:</p>
<p>Data: </p>
<pre><code>inp = "... | 1 | 2016-06-24T11:49:00Z | [
"python",
"dictionary",
"config",
"iscsi"
] |
Django error deploying to heroku requirements | 37,999,847 | <p>I am trying to deploy my a django app to heroku. I have a virtual environment(of course). I have the procfile, setup.py and runtime.txt set up correctly. It runs perfectly on a local development server, but when I push to heroku it gives some kind of error with the requirements file.</p>
<p>This is the third traceb... | 0 | 2016-06-23T19:07:14Z | 38,000,811 | <p>How was the requirements.txt file created? Is it possible it is corrupted or not plain text or has non-printable characters in it?</p>
<p>I recommend deleting requirements.txt and generating it cleanly based on pip freeze.</p>
<p>If you are using Windows Powershell the <a href="https://github.com/pypa/pip/issues/3... | 2 | 2016-06-23T20:02:32Z | [
"python",
"django",
"heroku"
] |
Scipy dendrogram with names | 37,999,852 | <p>I'm using the example dendrogram from <a href="http://stackoverflow.com/questions/2982929/plotting-results-of-hierarchical-clustering-ontop-of-a-matrix-of-data-in-python">this post</a> in my work but would also like to keep track of which row / column is from which piece of data.</p>
<p>I've edited the code with re... | 1 | 2016-06-23T19:07:42Z | 38,002,052 | <p>The python package <a href="https://github.com/WarrenWeckesser/heatmapcluster" rel="nofollow"><code>heatmapcluster</code></a> that I wrote accepts (in fact, requires) labels.</p>
<p>Here's a simplified version of your script using <code>heatmapcluster</code>:</p>
<pre><code>import numpy as np
import matplotlib.pyp... | 1 | 2016-06-23T21:20:10Z | [
"python",
"scipy",
"hierarchical-clustering",
"dendrogram"
] |
How to gather arrays of unequal length with mpi4py | 37,999,866 | <h2>Desired behavior:</h2>
<p>I am trying to take a number of lists of varied lengths on different nodes, collect them together in one node, and have that master node place them in a set. This list is named <code>rout_array</code> in each node. Note that the elements in <code>rout_array</code> are only integers, and n... | 1 | 2016-06-23T19:08:13Z | 38,008,452 | <p>If your lengths are different across processes, you need to use the vector variant <code>Gatherv</code>. With that function you provide an array containing the various lengths (recvcounts).</p>
<p>Unfortunately the mpi4py documentation does currently not describe how to use <code>Gatherv</code> or any other of the ... | 2 | 2016-06-24T07:59:12Z | [
"python",
"mpi",
"mpi4py"
] |
Use pandas to set a score of relations between columns | 37,999,904 | <p>I'm want to find relations between columns and create a new column with the score, but I'm lost and have no idea of how to do it.</p>
<p>Here are the columns I'm using</p>
<pre><code>Yan TNSeq Kato Eco-GeneOrth Essential
accA accA accA accA accA
accB accB accB accB... | 0 | 2016-06-23T19:11:02Z | 38,000,533 | <p>You can do that:</p>
<pre><code>df['Score'] = pd.DataFrame(df, columns=['Yan', 'TNSeq', 'Kato', 'Eco-GeneOrth']).eq(df['Essential'], axis='rows').sum(axis=1)
</code></pre>
| 0 | 2016-06-23T19:46:14Z | [
"python",
"pandas"
] |
Use pandas to set a score of relations between columns | 37,999,904 | <p>I'm want to find relations between columns and create a new column with the score, but I'm lost and have no idea of how to do it.</p>
<p>Here are the columns I'm using</p>
<pre><code>Yan TNSeq Kato Eco-GeneOrth Essential
accA accA accA accA accA
accB accB accB accB... | 0 | 2016-06-23T19:11:02Z | 38,000,767 | <p>Check this out. There might be some performance issue if your data set is large, however, since your data is not aligned by row, I don't see a way around to avoid checking the whole data frame for every Essential gene:</p>
<pre><code>import pandas as pd
def check(ess, col):
return any(col.str.contains(ess))
df[... | 0 | 2016-06-23T19:59:59Z | [
"python",
"pandas"
] |
How to force matplotlib to plot before the end of a function | 37,999,928 | <p>I have a function that plots a set of data with some points highlighted (the computer-measured values) and asks for user inputs about those points (the theoretical values for those points) in order to calibrate a device.</p>
<p>This used to work fine. Now, however, without changing anything, the plot doesn't show u... | 0 | 2016-06-23T19:12:10Z | 38,017,337 | <p>For what it's worth, I found an answer to my specific problem (after lots of trial and error).</p>
<p>What I needed was for the function that draws a plot to pause for a long time before continuing. I don't know why, maybe it has to do with the plot not being finished before python starts executing the following co... | 0 | 2016-06-24T15:48:21Z | [
"python",
"matplotlib",
"jupyter-notebook"
] |
regex with optional capturing groups and negative lookahead | 37,999,932 | <p>This problem has been with me for quite some time. Here is the base of a string I'd like to search for:</p>
<p><code>aa.bb.cc</code></p>
<p>Each token (tokenized by '.') can be succeeded/followed with zero or more groups of array indexing:</p>
<p>e.g. <code>aa[1].bb[2][3].cc</code></p>
<p>If my text contains a s... | 2 | 2016-06-23T19:12:50Z | 38,000,284 | <p>Adding the start-of-string anchor <code>^</code> to the beginning and the end-of-string anchor <code>$</code> to the end of your regex will cause it to match only strings containing exactly what you described and nothing more.</p>
<pre><code>>>> regex = re.compile('^((\w+)([\[\]\w]+)*\.(\w+)([\[\]\w]+)*\.(... | 0 | 2016-06-23T19:32:02Z | [
"python",
"regex",
"negative-lookahead"
] |
regex with optional capturing groups and negative lookahead | 37,999,932 | <p>This problem has been with me for quite some time. Here is the base of a string I'd like to search for:</p>
<p><code>aa.bb.cc</code></p>
<p>Each token (tokenized by '.') can be succeeded/followed with zero or more groups of array indexing:</p>
<p>e.g. <code>aa[1].bb[2][3].cc</code></p>
<p>If my text contains a s... | 2 | 2016-06-23T19:12:50Z | 38,000,314 | <p>You can bound the repeat number of <code>((\w+)(\[\d+\])*\.)</code> by 2 then add <code>(\w+)(\[\d+\])*</code> at the trailing of your regex. And don't forget to use start-end anchors.</p>
<pre><code>^((\w+)(\[\d+\])*\.){2}(\w+)(\[\d+\])*$
</code></pre>
<p>See the demo: <a href="https://regex101.com/r/jG3uK7/7" re... | 0 | 2016-06-23T19:33:44Z | [
"python",
"regex",
"negative-lookahead"
] |
regex with optional capturing groups and negative lookahead | 37,999,932 | <p>This problem has been with me for quite some time. Here is the base of a string I'd like to search for:</p>
<p><code>aa.bb.cc</code></p>
<p>Each token (tokenized by '.') can be succeeded/followed with zero or more groups of array indexing:</p>
<p>e.g. <code>aa[1].bb[2][3].cc</code></p>
<p>If my text contains a s... | 2 | 2016-06-23T19:12:50Z | 38,000,324 | <p>With regex shown <a href="https://regex101.com/r/tJ3rJ2/4" rel="nofollow">here</a>
I get desired match.</p>
<p>Use negative lookahead and lookbehind. </p>
<p><code>(?<!\.)\w{2}(\[\d+])*\.\w{2}(\[\d+])*\.\w{2}(\[\d+])*(?!\.\w+)</code></p>
| 0 | 2016-06-23T19:34:25Z | [
"python",
"regex",
"negative-lookahead"
] |
regex with optional capturing groups and negative lookahead | 37,999,932 | <p>This problem has been with me for quite some time. Here is the base of a string I'd like to search for:</p>
<p><code>aa.bb.cc</code></p>
<p>Each token (tokenized by '.') can be succeeded/followed with zero or more groups of array indexing:</p>
<p>e.g. <code>aa[1].bb[2][3].cc</code></p>
<p>If my text contains a s... | 2 | 2016-06-23T19:12:50Z | 38,000,483 | <p>Use this pattern, it will capture 3 sets anywhere: </p>
<pre><code>(?<!\.)\b((?:(?:\w+(?:\[\d+\])*)\.){2}(?:\w+(?:\[\d+\])*))(?![\w\.])
</code></pre>
<p><a href="https://regex101.com/r/tJ3rJ2/6" rel="nofollow">Demo</a></p>
| 0 | 2016-06-23T19:43:35Z | [
"python",
"regex",
"negative-lookahead"
] |
GroupBy Transformation on hierarchically indexed dataframe | 38,000,075 | <p>I would like to take my Pandas dataframe with hierarchically indexed columns and normalize the values such that the values with the same outer index sum to one. For example:</p>
<pre><code>cols = pd.MultiIndex.from_tuples([('A', 1), ('A', 2), ('B', 1), ('B', 2)])
X = pd.DataFrame(np.arange(20).reshape(5,4), columns... | 1 | 2016-06-23T19:20:23Z | 38,000,339 | <p>is that what you want?</p>
<pre><code>In [33]: X.groupby(level=0, axis=1).apply(lambda x: x.div(x.sum(axis=1), axis=0))
Out[33]:
A B
1 2 1 2
0 0.000000 1.000000 0.400000 0.600000
1 0.444444 0.555556 0.461538 0.538462
2 0.470588 0.529412 0.4761... | 1 | 2016-06-23T19:35:16Z | [
"python",
"pandas"
] |
Python CSV Reader Control Flow | 38,000,141 | <p>I was fairly surprised to see this functionality in Python's CSV reader. </p>
<pre><code>with open(sys.argv[1]) as csvfile:
reader = csv.DictReader(csvfile)
for i in range(3):
sys.stdout.write('A ')
for row in reader:
sys.stdout.write('B ')
#sys.argv[1] is a 3 row csv file
</cod... | 0 | 2016-06-23T19:24:18Z | 38,000,185 | <p>Your <code>reader</code> object from <code>csv.DictReader</code> is a generator. It got exhausted in the first iteration of the outer <code>for</code>. So in the following iterations, the inner <code>for</code> loop has no items to execute the loop.</p>
| 2 | 2016-06-23T19:26:27Z | [
"python",
"csv",
"iterator"
] |
printing/writing horizontally/vertically | 38,000,160 | <p>I have code that successfully retrieves a column of values from a file. When I attempt to write them into a file, it appears as a successive line like:</p>
<pre><code>0.000000.000000.000000.000000.000000.000000.000000.000000.000000.000000.000
</code></pre>
<p>I would prefer that it print out in a list like:</p>
<... | 0 | 2016-06-23T19:25:12Z | 38,000,294 | <p>to write on the file a new line try</p>
<pre><code>f.write('\n')
</code></pre>
<p>after the <code>f.write(parts[1])</code></p>
| 3 | 2016-06-23T19:32:37Z | [
"python"
] |
printing/writing horizontally/vertically | 38,000,160 | <p>I have code that successfully retrieves a column of values from a file. When I attempt to write them into a file, it appears as a successive line like:</p>
<pre><code>0.000000.000000.000000.000000.000000.000000.000000.000000.000000.000000.000
</code></pre>
<p>I would prefer that it print out in a list like:</p>
<... | 0 | 2016-06-23T19:25:12Z | 38,000,355 | <p>I am not sure about the 2nd part of your question without testing it myself, but if you'd like to print in a column format you could try</p>
<pre><code>>>> x = ['apples', 'bananas', 'grapes']
>>> print "\n".join(x)
apples
bananas
grapes
</code></pre>
<p>or in your case <code>x</code> would equal... | 0 | 2016-06-23T19:36:13Z | [
"python"
] |
convert string to float and align columns in dataframe | 38,000,199 | <p>I have a Dataframe df where a <code>Date</code> column belongs to each <code>Value</code> column. The contents are (still) formatted as strings:</p>
<pre><code> Date Value1 Date Value2
Index
0 30.01.2001 20,32 30.05.2005 50,55
1 30.02.2001 19,5 30... | 0 | 2016-06-23T19:27:16Z | 38,000,814 | <p>A number of steps:</p>
<pre><code># I wanted to split into two dataframes
df1 = df.iloc[:, :2].copy()
# rename column to Date because my `read_csv` parsing
df2 = df.iloc[:, 2:].copy().rename(columns={'Date.1': 'Date'})
# As EdChum suggested.
df1.Value1 = df1.Value1.str.replace(',', '.').astype(float)
df2.Value2 = ... | 1 | 2016-06-23T20:02:41Z | [
"python",
"pandas",
"dataframe",
"decimal"
] |
escaping one of the keys in formatting a string | 38,000,205 | <p>I was trying to generate a dynamic id which comes from a an object at runtime and insert this into database.</p>
<pre><code>'{"mykey": {value}}'.format(value=obj.id)
</code></pre>
<p>but this gives an error</p>
<blockquote>
<p>KeyError: '"mykey"'</p>
</blockquote>
<p>expected result:</p>
<pre><code>'{"mykey":... | 0 | 2016-06-23T19:27:27Z | 38,000,241 | <p>You need to <a href="http://stackoverflow.com/questions/5466451/how-can-i-print-a-literal-characters-in-python-string-and-also-use-format">escape the <code>{</code></a>:</p>
<pre><code>>>> value = 4
>>> '{{"mykey": {value}}}'.format(value=value)
'{"mykey": 4}'
</code></pre>
<p>You can also access... | 4 | 2016-06-23T19:29:24Z | [
"python",
"python-2.7",
"string-formatting"
] |
Can't connect to local Machine IP through TCP From Arduino Uno using SIM900 Shield | 38,000,220 | <p>So you have a basic understanding of the parts im using, I have:</p>
<ul>
<li><p>Arduino Uno</p></li>
<li><p>Seeed Studio GPRS Shield v2.0 (<a href="http://www.seeedstudio.com/wiki/GPRS_Shield_V2.0" rel="nofollow">http://www.seeedstudio.com/wiki/GPRS_Shield_V2.0</a>)</p></li>
<li><p>Ultimate GPS for Adafruit V3.3 (... | 0 | 2016-06-23T19:28:03Z | 38,000,963 | <p>First of all as a suggestion, you can combine the two shields by using SIM908 (unless you are getting more precision on your GPS shield). Since your TCP connection is working, I bet that the port 10000 on your ubuntu is blocked by the firewall. You can first try to turn off your firewall and see if it works. If it d... | 0 | 2016-06-23T20:13:30Z | [
"python",
"tcp",
"arduino",
"at-command",
"gprs"
] |
Can't connect to local Machine IP through TCP From Arduino Uno using SIM900 Shield | 38,000,220 | <p>So you have a basic understanding of the parts im using, I have:</p>
<ul>
<li><p>Arduino Uno</p></li>
<li><p>Seeed Studio GPRS Shield v2.0 (<a href="http://www.seeedstudio.com/wiki/GPRS_Shield_V2.0" rel="nofollow">http://www.seeedstudio.com/wiki/GPRS_Shield_V2.0</a>)</p></li>
<li><p>Ultimate GPS for Adafruit V3.3 (... | 0 | 2016-06-23T19:28:03Z | 38,067,388 | <p>The IP you're using is inside a <a href="https://en.wikipedia.org/wiki/Network_address_translation" rel="nofollow">NAT</a> since it starts with 192.168. Unless you have a private apn with the mobile operator you're using, you won't be able to reach your Ubuntu from a public IP. Your ISP gives you a public IP address... | 1 | 2016-06-28T05:00:30Z | [
"python",
"tcp",
"arduino",
"at-command",
"gprs"
] |
Scraping JSON arrays nested tags | 38,000,237 | <p>I am trying to scrape data from a JSON file. I am able to scrape data from some of the tags but few nested tags are giving problem. Following is a sample from the file - </p>
<pre><code>{"orders":[{
"order_id":9000,
"flight_start":"2017-06-15T05:00:00.000Z",
"flight_end":"2017-06-22T05:00:00.000Z",
"spots":... | 0 | 2016-06-23T19:29:06Z | 38,000,539 | <p>The json data in your question isn't complete. Making some assumptions, this could work:</p>
<pre><code>for i in data["orders"]:
k = i["order_id"]
j = i["flight_start"]
l = i["flight_end"]
m = i ['spots']
for value in m:
a = value["spot_length"]
b = value["spot_id"]
n = i["c... | 1 | 2016-06-23T19:46:45Z | [
"python",
"arrays",
"json",
"web-scraping",
"urllib"
] |
Regex in Python Equation Replacement | 38,000,252 | <p>I'm somewhat new to regex and Python and am in the following situation. I'd like to take an equation string, like <code>"A + B + C + 4D"</code>, and place the number 1 in front of all variables that have no number in front of them. So something like:</p>
<pre><code>>>> foo_eqn = "A + B + C + 4D"
>>&g... | 2 | 2016-06-23T19:30:28Z | 38,000,482 | <p>Looks like the <code>re.I</code> (ignore case flag) is the culprit:</p>
<pre><code>>>> def fill_in_ones(in_eqn):
... out_eqn = re.sub(r"(\b[A-Z]\b)", "1"+ r"\1", in_eqn)
... return(out_eqn)
...
>>>
>>> fill_in_ones("A + 3B + C + 2D + E")
'1A + 3B + 1C + 2D + 1E'
</code></pre>
<p>... | 4 | 2016-06-23T19:43:33Z | [
"python",
"regex"
] |
How to change bokeh logo | 38,000,285 | <p>Is there anyway to set my own logo on a bokeh plot? I would like to set my own .png instead of using the bokeh colorful circle. </p>
<p>Referring specifically to changing the
<a href="http://i.stack.imgur.com/ZQAsu.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZQAsu.png" alt="bokeh image on the toolbar">... | 1 | 2016-06-23T19:32:09Z | 38,001,240 | <p>As of Bokeh <code>0.12</code> this is an <a href="https://github.com/bokeh/bokeh/issues/3820" rel="nofollow">open feature request</a>. For now your only options are to grey-out the logo, or to remove it entirely. </p>
| 2 | 2016-06-23T20:28:34Z | [
"python",
"bokeh"
] |
regular expression that matches unless a character is present? | 38,000,290 | <p>How can I match 'x' with any amount of whitespace on the right side, Unless the 'x' is followed by another 'x'? </p>
<p>So far I have:</p>
<pre><code>find_nonSpace_rightSideOf_x = re.compile(r'x[\s]*')
</code></pre>
<p>But obviously, this will still catch even if the text is 'xx'. How can I make this catch 'xaldk... | 0 | 2016-06-23T19:32:26Z | 38,000,341 | <p>Use a negative look ahead assertion:</p>
<pre><code>re.compile(r'x(?!x)')
</code></pre>
<p>Will <em>catch</em> the second <code>x</code> in <code>'xxaldkfjdlk'</code> </p>
<blockquote>
<p>but not the first x</p>
</blockquote>
<p>To <em>catch</em> the spaces, add: <code>\s*</code></p>
<pre><code>re.compile(r'x... | 2 | 2016-06-23T19:35:18Z | [
"python",
"regex"
] |
regular expression that matches unless a character is present? | 38,000,290 | <p>How can I match 'x' with any amount of whitespace on the right side, Unless the 'x' is followed by another 'x'? </p>
<p>So far I have:</p>
<pre><code>find_nonSpace_rightSideOf_x = re.compile(r'x[\s]*')
</code></pre>
<p>But obviously, this will still catch even if the text is 'xx'. How can I make this catch 'xaldk... | 0 | 2016-06-23T19:32:26Z | 38,000,475 | <p>Another simple solution would be this:</p>
<pre><code>x[^x][\s]*
</code></pre>
<p>I.e. 'x' followed by "not-x", followed by spaces.</p>
<p>BTW, a very useful tool is the python regex tester: <a href="http://pythex.org/" rel="nofollow">http://pythex.org/</a></p>
| 2 | 2016-06-23T19:43:14Z | [
"python",
"regex"
] |
regular expression that matches unless a character is present? | 38,000,290 | <p>How can I match 'x' with any amount of whitespace on the right side, Unless the 'x' is followed by another 'x'? </p>
<p>So far I have:</p>
<pre><code>find_nonSpace_rightSideOf_x = re.compile(r'x[\s]*')
</code></pre>
<p>But obviously, this will still catch even if the text is 'xx'. How can I make this catch 'xaldk... | 0 | 2016-06-23T19:32:26Z | 38,000,751 | <p>If I understood your question correctly, you want to match the last <code>x</code> to the end of the line.</p>
<p>To do that you can use this regex:</p>
<pre><code>x[^x]*$
</code></pre>
<p><strong><a href="https://regex101.com/r/eN2cU6/1" rel="nofollow">Working demo</a></strong></p>
<p><a href="http://i.stack.im... | 2 | 2016-06-23T19:59:28Z | [
"python",
"regex"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.