title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Sed to remove everything after "." in file using * command? | 18,602,234 | 3 | 2013-09-03T22:04:04Z | 18,602,273 | 8 | 2013-09-03T22:07:51Z | [
"python",
"bash",
"sed"
] | I have the following data.txt:
```
95 flour.
47 water.s
etc..
```
I need to remove everything after the period . in the file to yield something like this:
```
95 flour
47 water
etc..
```
I have tried the using these sed command without success, which yield a blank document:
```
sed "s/'.*//" data.txt > clean... | Either escape the `.` with a backslash to get a literal `.`, or use brackets to define a character class:
```
sed 's/\..*$//' data.txt > cleaned.txt
sed 's/[.].*$//' data.txt > cleaned.txt
```
You tried `'s/\.*//'`, which is "zero or more literal dots", which is different from "literal dot followed by zero or more of... |
Django ModelChoiceField has no plus button | 18,602,563 | 6 | 2013-09-03T22:32:54Z | 18,602,674 | 9 | 2013-09-03T22:45:16Z | [
"python",
"django",
"django-forms",
"django-admin"
] | I'm making a Django app with custom users. I've outlined the key components of my problem below, missing code is denoted by '...'. My custom user model has a foreign key relationship as follows:
```
class MyCustomUser(models.AbstractBaseUser, models.PermissionsMixin)
...
location = models.ForeignKey(Location)
... | You need to set a `RelatedFieldWidgetWrapper` wrapper in your model form:
> The RelatedFieldWidgetWrapper (found in django.contrib.admin.widgets)
> is used in the Admin pages to include the capability on a Foreign Key
> control to add a new related record. (In English: puts the little green plus sign to the right of t... |
matplotlib bar3d clipping problems | 18,602,660 | 4 | 2013-09-03T22:43:28Z | 18,606,009 | 11 | 2013-09-04T05:28:57Z | [
"python",
"matplotlib"
] | I am trying to create a 3D bar graph with Matplotlib 1.2.0 and Python 2.7.3. I followed the advice in <http://www.mail-archive.com/[email protected]/msg19740.html> and plotted the bar one by one, but I am still getting rendering problems (i.e., bars on top of each other).
Moreover, I get the follo... | This isn't the answer that you are looking for, but I think that this might be a bug in matplotlib. I think that the same problem was [encountered here](https://github.com/matplotlib/matplotlib/issues/1292/). The problem was described as "intractable" according to the [mplot3d FAQ](http://matplotlib.org/mpl_toolkits/mp... |
Progress indicator during pandas operations (python) | 18,603,270 | 15 | 2013-09-03T23:55:02Z | 18,611,535 | 10 | 2013-09-04T10:37:32Z | [
"python",
"pandas",
"ipython"
] | I regularly perform pandas operations on data frames in excess of 15 million or so rows and I'd love to have access to a progress indicator for particular operations.
Does a text based progress indicator for pandas split-apply-combine operations exist?
For example, in something like:
```
df_users.groupby(['userID', ... | To tweak Jeff's answer (and have this as a reuseable function).
```
def logged_apply(g, func, *args, **kwargs):
step_percentage = 100. / len(g)
import sys
sys.stdout.write('apply progress: 0%')
sys.stdout.flush()
def logging_decorator(func):
def wrapper(*args, **kwargs):
prog... |
Progress indicator during pandas operations (python) | 18,603,270 | 15 | 2013-09-03T23:55:02Z | 34,365,537 | 17 | 2015-12-18T23:36:34Z | [
"python",
"pandas",
"ipython"
] | I regularly perform pandas operations on data frames in excess of 15 million or so rows and I'd love to have access to a progress indicator for particular operations.
Does a text based progress indicator for pandas split-apply-combine operations exist?
For example, in something like:
```
df_users.groupby(['userID', ... | Due to popular demand, `tqdm` has added support for `pandas`. Unlike the other answers, this **will not noticeably slow pandas down** -- here's an example for `DataFrameGroupBy.progress_apply`:
```
import pandas as pd
import numpy as np
from tqdm import tqdm, tqdm_pandas
df = pd.DataFrame(np.random.randint(0, int(1e8... |
Assign strings to IDs in Python | 18,605,500 | 3 | 2013-09-04T04:38:18Z | 18,605,520 | 10 | 2013-09-04T04:41:15Z | [
"python",
"string"
] | I am reading a text file with python, formatted where the values in each column may be numeric or strings.
When those values are strings, I need to assign a unique ID of that string (unique across all the strings under the same column; the same ID must be assigned if the same string appears elsewhere under the same co... | Use a defaultdict with a default value factory that generates new ids:
```
ids = collections.defaultdict(itertools.count().next)
ids['a'] # 0
ids['b'] # 1
ids['a'] # 0
```
When you look up a key in a defaultdict, if it's not already present, the defaultdict calls a user-provided default value factory to get the va... |
Python List Group by Date | 18,606,381 | 3 | 2013-09-04T05:55:17Z | 18,606,470 | 7 | 2013-09-04T06:02:06Z | [
"python",
"list",
"date",
"timestamp",
"group"
] | Say I have a list looks like this:
```
[(datetime.datetime(2013, 8, 8, 1, 20, 15), 2060), (datetime.datetime(2013, 8, 9, 1, 6, 14), 2055), (datetime.datetime(2013, 8, 9, 1, 21, 1), 2050), (datetime.datetime(2013, 8, 10, 1, 5, 49), 2050), (datetime.datetime(2013, 8, 10, 1, 19, 51), 2050), (datetime.datetime(2013, 8, 11... | Use [`itertools.groupby`](http://docs.python.org/2/library/itertools.html#itertools.groupby):
```
>>> records = [(datetime.datetime(2013, 8, 8, 1, 20, 15), 2060), ....]
>>> import itertools
>>> [(dt, max(v for d, v in grp)) for dt, grp in itertools.groupby(records, key=lambda x: x[0].date())]
[(datetime.date(2013, 8, ... |
Can I use TLS version 1.1 or 1.2 in python 2? | 18,606,666 | 6 | 2013-09-04T06:15:52Z | 25,900,868 | 9 | 2014-09-17T21:46:27Z | [
"python",
"ssl",
"openssl"
] | I read a document that says that Python 2 only has `ssl.PROTOCOL_TLSv1` constant, and that `ssl.PROTOCOL_TLSv1_1` and `ssl.PROTOCOL_TLSv1_2` were added in Python 3.4. So how can I use TLS 1.1 and 1.2 in Python 2?
PS. I don't want to use TLS 1.0 because it has some security flaws. TLS 1.2 is the newest version now, so ... | With my apologies for resurrecting an old question, it appears that support for [TLS1.1 and TLS1.2](https://docs.python.org/2/library/ssl.html#ssl.PROTOCOL_TLSv1_2) will be brought in for Python 2.7.9, scheduled for release around [December 2014](http://legacy.python.org/dev/peps/pep-0373/#maintenance-releases). |
executing python file in terminal - socket.error: no socket could be created | 18,607,780 | 3 | 2013-09-04T07:23:21Z | 18,607,882 | 12 | 2013-09-04T07:29:40Z | [
"python"
] | ```
(webgame)Benjamins-MacBook:webgame test$ python bin/app.py
http://0.0.0.0:8080/
Traceback (most recent call last):
File "bin/app.py", line 21, in <module>
app.run()
File "/Users/test/Pythonprojects/webgame/lib/python2.7/site-packages/web/application.py", line 310, in run
return wsgi.runwsgi(self.wsgifunc(*middle... | Try
```
python bin/app.py 3030
```
There might be another server running on 8080. |
scrapy, how to separate text within a HTML tag element | 18,609,267 | 3 | 2013-09-04T08:47:12Z | 18,610,728 | 9 | 2013-09-04T09:55:38Z | [
"python",
"screen-scraping",
"scrapy",
"web-crawler"
] | Code containing my data:
```
<div id="content"><!-- InstanceBeginEditable name="EditRegion3" -->
<div id="content_div">
<div class="title" id="content_title_div"><img src="img/banner_outlets.jpg" width="920" height="157" alt="Outlets" /></div>
<div id="menu_list">
<table border="0" cellpadding="5... | I would select all `<td valign="top">` which contain a `<span class="foodTitle">`
```
//div[@id="menu_list"]//td[@valign="top"][.//span[@class="foodTitle"]]
```
and then for each one of these `td` cell, get all text nodes
```
.//text()
```
You get something like that:
```
['\n ',
'\n ... |
Get a value between min and max values in Python | 18,609,360 | 2 | 2013-09-04T08:52:21Z | 18,609,398 | 7 | 2013-09-04T08:54:03Z | [
"python",
"return",
"max",
"min"
] | I wan't to get a value if it's between min and max values. If the value is smaller than min, I want to get the min value and if it's greater than max I want to get the max.
I use this code now, but is there an inbuilt or smarter way to do it?
```
def inBetween(minv, val, maxv):
if minv < val < maxv: return val
if ... | Using [`min`](http://docs.python.org/2/library/functions.html#min), [`max`](http://docs.python.org/2/library/functions.html#max):
```
>>> def inbetween(minv, val, maxv):
... return min(maxv, max(minv, val))
...
>>> inbetween(2, 5, 10)
5
>>> inbetween(2, 1, 10)
2
>>> inbetween(2, 11, 10)
10
``` |
print: "IOError: [Errno 9] Bad file descriptor" | 18,615,130 | 3 | 2013-09-04T13:25:25Z | 18,615,272 | 7 | 2013-09-04T13:31:12Z | [
"python"
] | I understand why I am getting the "Bad file descriptor" error when printing with no console from this post: [why am I getting IOError: (9, 'Bad file descriptor') error while making print statements?](http://stackoverflow.com/questions/4230855/why-am-i-getting-ioerror-9-bad-file-descriptor-error-while-making-print-st).
... | [os.path.isfile()](http://docs.python.org/3.3/library/os.path.html#os.path.isfile) takes a file path (a string), not a file descriptor (a number), so your solution will not work as you expect.
You can use [os.isatty()](http://docs.python.org/3.3/library/os.html#os.isatty) instead:
```
if os.isatty(1):
print "text... |
Python inner functions | 18,616,084 | 9 | 2013-09-04T14:06:58Z | 18,616,198 | 8 | 2013-09-04T14:11:50Z | [
"python"
] | In python, I can write :
```
def func():
x = 1
print x
x+=1
def _func():
print x
return _func
test = func()
test()
```
when I run it, the output is :
**1**
**2**
As \_func has access to the "x" variable defined in func. Right...
But if I do :
```
def func():
x = 1
print x
... | Check this answer : <http://stackoverflow.com/a/293097/1741450>
> Variables in scopes other than the local function's variables can be accessed, but can't be rebound to new parameters without further syntax. Instead, assignment will create a new local variable instead of affecting the variable in the parent scope. For... |
ARMA out-of-sample prediction with statsmodels | 18,616,588 | 5 | 2013-09-04T14:29:54Z | 18,620,232 | 8 | 2013-09-04T17:29:15Z | [
"python",
"forecasting",
"statsmodels"
] | I'm using statsmodels to fit a ARMA model.
```
import statsmodels.api as sm
arma = sm.tsa.ARMA(data, order =(4,4));
results = arma.fit( full_output=False, disp=0);
```
Where `data` is a one-dimensional array. I know to get in-sample predictions:
```
pred = results.predict();
```
Now, given a second data set `dat... | I thought there was an issue for this. If you file one on github, I'll be more likely to remember to add something like this. The prediction machinery is not (yet) available as user-facing functions, so you'd have to do something like this.
If you've fit a model already, then you can do this.
```
# this is the nsteps... |
Python 3 sorting: Custom comparer removed in favor of key - why? | 18,617,014 | 16 | 2013-09-04T14:48:22Z | 18,617,377 | 7 | 2013-09-04T15:03:29Z | [
"python",
"algorithm",
"sorting",
"python-3.x"
] | In Python 2.4, you can pass a custom comparer to sort.
Let's take the list -
```
list=[5,1,2,3,6,0,7,1,4]
```
To sort with the even numbers first, and then odds, we can do the following -
```
evenfirst=lambda x,y:1 if x%2>y%2 else -1 if y%2>x%2 else x-y
list.sort(cmp=evenfirst)
list == [0, 2, 4, 6, 1, 1, 3, 5, 7] #... | Performance.
The `cmp` function was called every time the sorting algorithm needed a comparison between two elements.
In contrast, the `key` object can be *cached*. That is, the sorting algorithm only needs to get the key once for each element and then compare the keys. It doesn't need to get a new key for every comp... |
Boost.Python: Wrap functions to release the GIL | 18,618,333 | 5 | 2013-09-04T15:46:46Z | 18,648,366 | 7 | 2013-09-06T01:14:44Z | [
"c++",
"python",
"function",
"boost",
"boost-python"
] | I am currently working with Boost.Python and would like some help to solve a tricky problem.
**Context**
When a C++ method/function is exposed to Python, it needs to release the GIL (Global Interpreter Lock) to let other threads use the interpreter. This way, when the python code calls a C++ function, the interpreter... | Exposing functors as methods is not [officially supported](http://www.boost.org/doc/libs/1_58_0/libs/python/todo.html#wrapping-function-objects). The supported approach would be to expose a non-member function that delegates to the member-function. However, this can result in a large amount of boilerplate code.
As bes... |
matplotlib - change marker color along plot line | 18,619,422 | 6 | 2013-09-04T16:41:01Z | 18,619,652 | 12 | 2013-09-04T16:54:50Z | [
"python",
"matplotlib",
"plot"
] | I would like to plot a 2d data set with matplotlib such that the marker color for each data point is different. I found the example on multicolored lines (<http://matplotlib.org/examples/pylab_examples/multicolored_line.html>). However, this does not seem to work when plotting a line with markers.
The solution I came ... | I believe you can achieve this with `ax.scatter`:
```
# The data
x = np.linspace(0, 10, 1000)
y = np.sin(2 * np.pi * x)
# The colormap
cmap = cm.jet
# Create figure and axes
fig = plt.figure(1)
fig.clf()
ax = fig.add_subplot(1, 1, 1)
c = np.linspace(0, 10, 1000)
ax.scatter(x, y, c=c, cmap=cmap)
```
Scatter accepts... |
Matplotlib adjust figure margin | 18,619,880 | 8 | 2013-09-04T17:07:43Z | 23,566,364 | 9 | 2014-05-09T13:52:04Z | [
"python",
"matplotlib"
] | The following code gives me a plot with significant margins above and below the figure. I don't know how to eliminate the noticeable margins. `subplots_adjust` does not work as expected.
```
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10),range(10))
ax... | After plotting your chart you can easily manipulate margins this way:
```
plot_margin = 0.25
x0, x1, y0, y1 = plt.axis()
plt.axis((x0 - plot_margin,
x1 + plot_margin,
y0 - plot_margin,
y1 + plot_margin))
```
This example could be changed to the aspect ratio you want or change the margin... |
how to use two different functions within crosstab/pivot_table in pandas? | 18,620,199 | 5 | 2013-09-04T17:26:59Z | 18,620,407 | 7 | 2013-09-04T17:38:47Z | [
"python",
"merge",
"pandas",
"pivot-table",
"crosstab"
] | Using pandas, is it possible to compute a single cross-tabulation (or pivot table) containing values calculated from two different functions?
```
import pandas as pd
import numpy as np
c1 = np.repeat(['a','b'], [50, 50], axis=0)
c2 = list('xy'*50)
c3 = np.repeat(['G1','G2'], [50, 50], axis=0)
np.random.shuffle(c3)
c4... | You can give a list of functions:
```
pd.crosstab([df.c1,df.c2], [df.c3,df.c4], values=df.val, aggfunc=[len, np.mean])
```
---
If you want the table as shown in your question, you will have to rearrange the levels a bit:
```
In [42]: table = pd.crosstab([df.c1,df.c2], [df.c3,df.c4], values=df.val, aggfunc=[len, np.... |
Python insert numpy array into sqlite3 database | 18,621,513 | 13 | 2013-09-04T18:47:08Z | 18,622,264 | 16 | 2013-09-04T19:32:27Z | [
"python",
"numpy",
"sqlite3"
] | I'm trying to store a numpy array of about 1000 floats in a sqlite3 database but I keep getting the error "InterfaceError: Error binding parameter 1 - probably unsupported type".
I was under the impression a BLOB data type could be anything but it definitely doesn't work with a numpy array. Here's what I tried:
```
i... | You could register a new `array` data type with `sqlite3`:
```
import sqlite3
import numpy as np
import io
def adapt_array(arr):
"""
http://stackoverflow.com/a/31312102/190597 (SoulNibbler)
"""
out = io.BytesIO()
np.save(out, arr)
out.seek(0)
return sqlite3.Binary(out.read())
def convert_... |
Why is random.choice so slow? | 18,622,781 | 3 | 2013-09-04T20:02:14Z | 18,622,833 | 11 | 2013-09-04T20:05:46Z | [
"python",
"random",
"numpy"
] | While writing a script I discovered the numpy.random.choice function. I implemented it because it was was much cleaner than the equivalent if statement. However, after running the script I realized it is **significantly** slower than the if statement.
The following is a MWE. The first method takes 0.0 s, while the sec... | You're using it wrong. Vectorize the operation, or numpy will offer no benefit:
```
var = numpy.random.choice([-1, 0, 1], size=1000, p=[0.25, 0.5, 0.25])
```
Timing data:
```
>>> timeit.timeit('''numpy.random.choice([-1, 0, 1],
... size=1000,
... ... |
Python String to Int Or None | 18,623,668 | 5 | 2013-09-04T20:59:20Z | 18,623,698 | 17 | 2013-09-04T21:01:16Z | [
"python"
] | Learning Python and a little bit stuck.
I'm trying to set a variable to equal `int(stringToInt)` or if the string is empty set to `None`.
I tried to do `variable = int(stringToInt) or None` but if the string is empty it will error instead of just setting it to None.
Do you know any way around this? | If you want a one-liner like you've attempted, go with this:
```
variable = int(stringToInt) if stringToInt else None
```
This will assign `variable` to `int(stringToInt)` only if is not empty AND is "numeric". If, for example `stringToInt` is `'mystring'`, a `ValueError` will be raised.
To avoid `ValueError`s, so l... |
Execute fabric task from PyCharm | 18,623,912 | 7 | 2013-09-04T21:15:10Z | 18,624,174 | 23 | 2013-09-04T21:33:25Z | [
"python",
"django",
"fabric",
"pycharm"
] | I'm developing Django project in PyCharm and everything works properly. I've install fabric to my virtual env, and add fabfile.py in to my project. In this file I placed one test task definition:
```
def hello():
print("Hello fabric!")
```
After that I'm trying to execute this task directly from my PyCharm. Do yo... | Add a "Python" run configuration with `/path/to/your/env/bin/fab` as the script and `hello` as the script parameters.
Set the working directory to the directory with the fabfile.
Example:
 |
Pandas reset index on series to remove multiindex | 18,624,039 | 12 | 2013-09-04T21:23:25Z | 18,624,069 | 24 | 2013-09-04T21:25:35Z | [
"python",
"pandas"
] | I created a `Series` from a `DataFrame`, when I resampled some data with a count
like so: where `H2` is a `DataFrame`:
```
H3=H2[['SOLD_PRICE']]
H5=H3.resample('Q',how='count')
H6=pd.rolling_mean(H5,4)
```
This yielded a series that looks like this:
```
1999-03-31 SOLD_PRICE NaN
1999-06-30 SOLD_PRI... | Just call `reset_index()`:
```
In [130]: s
Out[130]:
0 1
1999-03-31 SOLD_PRICE NaN
1999-06-30 SOLD_PRICE NaN
1999-09-30 SOLD_PRICE NaN
1999-12-31 SOLD_PRICE 3
2000-03-31 SOLD_PRICE 3
Name: 2, dtype: float64
In [131]: s.reset_index()
Out[131]:
0 1 2
0 1999-03-31 S... |
Pandas reset index on series to remove multiindex | 18,624,039 | 12 | 2013-09-04T21:23:25Z | 18,624,323 | 12 | 2013-09-04T21:46:08Z | [
"python",
"pandas"
] | I created a `Series` from a `DataFrame`, when I resampled some data with a count
like so: where `H2` is a `DataFrame`:
```
H3=H2[['SOLD_PRICE']]
H5=H3.resample('Q',how='count')
H6=pd.rolling_mean(H5,4)
```
This yielded a series that looks like this:
```
1999-03-31 SOLD_PRICE NaN
1999-06-30 SOLD_PRI... | When you use double brackets, such as
```
H3 = H2[['SOLD_PRICE']]
```
H3 becomes a DataFrame. If you use single brackets,
```
H3 = H2['SOLD_PRICE']
```
then H3 becomes a Series. If H3 is a Series, then the result you desire follows naturally:
```
import pandas as pd
import numpy as np
rng = pd.date_range('1/1/2011... |
If-elif-else statement not working in simple Python 3.3 class? | 18,624,465 | 2 | 2013-09-04T21:56:40Z | 18,624,498 | 10 | 2013-09-04T21:58:32Z | [
"python",
"if-statement",
"python-3.x"
] | My code is:
```
def nameAndConfirm():
global name,confirm
print("What is your name? ")
name = input()
str(name)
print("Is",name,"correct? ")
confirm = input()
str(confirm)
print(confirm)
if confirm.upper() == "Y" or "YES":
classSelection()
elif confirm.upper() == "N" o... | The condition `confirm.upper() == "Y" or "YES"` and the other one are not evaluated as you expect. You want
```
confirm.upper() in {"Y", "YES"}
```
or
```
confirm.upper() == "Y" or confirm.upper() == "YES"
```
Your condition is equivalent to:
```
(confirm.upper() == "Y") or "YES"
```
which is always truthy:
```
... |
How to plot a wav file | 18,625,085 | 15 | 2013-09-04T22:52:15Z | 18,625,294 | 27 | 2013-09-04T23:15:47Z | [
"python",
"audio",
"matplotlib"
] | I have just read a wav file with scipy and now I want to make the plot of the file using matplotlib, on the "y scale" I want to see the aplitude and over the "x scale" I want to see the numbers of frames!
Any help how can I do this??
Thank you!
```
from scipy.io.wavfile import read
import numpy as np
from numpy import... | Hi you can call wave lib to read audio file !
To plot waveform use "plot" function from matplotlib
```
import matplotlib.pyplot as plt
import numpy as np
import wave
import sys
spf = wave.open('wavfile.wav','r')
#Extract Raw Audio from Wav File
signal = spf.readframes(-1)
signal = np.fromstring(signal, 'Int16')
... |
In which conditions a list turns into a string in python? | 18,626,926 | 2 | 2013-09-05T02:47:05Z | 18,626,967 | 8 | 2013-09-05T02:51:33Z | [
"python"
] | Hello guys I've got a little piece of code here that is giving me a headache. In this function I define a list called `word` and all of sudden the list becomes a string. I don't know how is this possible:
```
def find_best_shift(wordlist, text):
words = []
word = []
for x in range(0, 27):
apply_shi... | ```
for word in words:
```
reassigns the same name (`word`) to be an element of the `words` list before moving on to the next value for `x`. Change this to something else.
```
for item in words:
```
Reusing names can cause some funny headaches :(
Don't forget to update
```
y = is_word(wordlist, word)
```
to
```
... |
Django Celery get task count | 18,631,669 | 5 | 2013-09-05T08:43:23Z | 19,129,868 | 7 | 2013-10-02T04:09:26Z | [
"python",
"django",
"redis",
"celery"
] | I am currently using django with celery and everything works fine.
However I want to be able to give the users an opportunity to cancel a task if the server is overloaded by checking how many tasks are currently scheduled.
How can I achieve this ?
I am using redis as broker.
I just found this :
[Retrieve list of ta... | If your broker is configured as `redis://localhost:6379/1`, and your tasks are submitted to the general `celery` queue, then you can get the length by the following means:
```
import redis
queue_name = "celery"
client = redis.Redis(host="localhost", port=6379, db=1)
length = client.llen(queue_name)
```
Or, from a she... |
yum---no module named yum | 18,632,016 | 4 | 2013-09-05T09:00:13Z | 25,934,568 | 11 | 2014-09-19T13:02:14Z | [
"python",
"yum"
] | when I use yum in the shell,the error message is no module named yum, so I edit the /usr/bin/yum change the first line to another version of python, but nothing changes,and when I user different python to import yum, it brings out different error

![en... | Changing the first line of `/usr/bin/yum` to the default version of python may help.
eg.change `#!/usr/bin/python` to `#!/usr/bin/python2.4` |
Set to dict Python | 18,634,650 | 15 | 2013-09-05T11:04:02Z | 18,634,675 | 31 | 2013-09-05T11:05:23Z | [
"python",
"dictionary",
"set"
] | is there any pythonic way to convert a set into a dict?
I got the following set
```
s = {1,2,4,5,6}
```
and want the following dict
```
c = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0}
```
with a list you would do
```
a = [1,2,3,4,5,6]
b = []
while len(b) < len(a):
b.append(0)
c = dict(itertools.izip(a,b))
``` | Use [`dict.fromkeys()`](http://docs.python.org/2/library/stdtypes.html#dict.fromkeys):
```
c = dict.fromkeys(s, 0)
```
Demo:
```
>>> s = {1,2,4,5,6}
>>> dict.fromkeys(s, 0)
{1: 0, 2: 0, 4: 0, 5: 0, 6: 0}
```
This works for lists as well; it is the most efficient method to create a dictionary from a sequence. Note a... |
Set to dict Python | 18,634,650 | 15 | 2013-09-05T11:04:02Z | 18,634,766 | 9 | 2013-09-05T11:09:49Z | [
"python",
"dictionary",
"set"
] | is there any pythonic way to convert a set into a dict?
I got the following set
```
s = {1,2,4,5,6}
```
and want the following dict
```
c = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0}
```
with a list you would do
```
a = [1,2,3,4,5,6]
b = []
while len(b) < len(a):
b.append(0)
c = dict(itertools.izip(a,b))
``` | Besides the method given by [@Martijn Pieters](http://stackoverflow.com/users/100297/martijn-pieters), you can also use a dictionary comprehension like this:
```
s = {1,2,4,5,6}
d = {e:0 for e in s}
```
This method is slower than dict.fromkeys(), but it allows you to set the values in the dict to whatever you need, i... |
Calculator in python problems | 18,636,410 | 2 | 2013-09-05T12:31:42Z | 18,636,487 | 7 | 2013-09-05T12:34:48Z | [
"python",
"python-3.x"
] | I made a calculator in python
```
import time
print("Calculator 1.0")
print("made by AnAwesomeMiner")
print("Number 1 in calculation")
x = input()
print("Number 2")
y = input()
print("calculating")
time.sleep(3)
print("why is this not done yet")
time.sleep(3)
print("god this is taking forever")
time.sleep(3)
print("do... | `input()` returns string not number . That's why instead of addition , String concatenation is performed.
you need to use `int(x)` and `int(y)` for conversion.
use this statement `answear = int(x) + int(y)` |
Most pythonic way to convert a list of tuples | 18,637,651 | 4 | 2013-09-05T13:27:24Z | 18,637,677 | 10 | 2013-09-05T13:28:14Z | [
"python",
"list",
"tuples"
] | I need to convert a list of tuples in the style:
```
[(day1, name1, value1), (day2, name2, value2), (day3, name3, value3)]... etc
```
into:
```
[day1, day2, day3], [name1, name2, name3], [value1, value2, value3]... etc
```
Currently I'm doing it like this:
```
vals is the list of tuples
day = []
name = []
value = ... | A list comprehension with the [`zip()` function](http://docs.python.org/2/library/functions.html#zip) is easiest:
```
[list(t) for t in zip(*list_of_tuples)]
```
This applies each separate tuple as an argument to `zip()` using the `*arguments` expansion syntax. `zip()` then pairs up each value from each tuple into ne... |
How to sort list depending on substring? | 18,637,652 | 3 | 2013-09-05T13:27:23Z | 18,637,740 | 7 | 2013-09-05T13:31:11Z | [
"python",
"django"
] | I have this list sorted:
```
>>> L = ['actor_1', 'actor_3', 'actor_130', 'actor_55', 'actor_5']
>>> L.sort()
>>> L
['actor_1', 'actor_130', 'actor_3', 'actor_5', 'actor_55']
```
Is there a clean way to make the list sortable by the number after underline to have it like the following?:
```
['actor_1', 'actor_3', 'ac... | You can specify `key` function which generate comparison key:
```
>>> L = ['actor_1', 'actor_3', 'actor_130', 'actor_55', 'actor_5']
>>> def sort_key(s):
... s, n = s.split('_')
... return s, int(n)
...
>>> L.sort(key=sort_key)
>>> L
['actor_1', 'actor_3', 'actor_5', 'actor_55', 'actor_130']
``` |
How do I keep track of pip-installed packages in an Anaconda (Conda) environment? | 18,640,305 | 60 | 2013-09-05T15:25:41Z | 18,640,601 | 53 | 2013-09-05T15:40:16Z | [
"python",
"pip",
"anaconda",
"env",
"conda"
] | I've installed and have been using the [Anaconda](https://en.wikipedia.org/wiki/Anaconda_%28Python_distribution%29) Python distribution, and I have started using the Anaconda (Conda) environment. I can use the standard `conda install...` command to put packages from the distribution into my environments, but to use any... | `conda` will only keep track of the packages it installed. And `pip` will give you the packages that were either installed using the `pip` installer itself or they used `setuptools` in their `setup.py` so conda build generated the egg information. So you have basically three options.
1. You can take the union of the `... |
How do I keep track of pip-installed packages in an Anaconda (Conda) environment? | 18,640,305 | 60 | 2013-09-05T15:25:41Z | 19,799,193 | 18 | 2013-11-05T21:19:33Z | [
"python",
"pip",
"anaconda",
"env",
"conda"
] | I've installed and have been using the [Anaconda](https://en.wikipedia.org/wiki/Anaconda_%28Python_distribution%29) Python distribution, and I have started using the Anaconda (Conda) environment. I can use the standard `conda install...` command to put packages from the distribution into my environments, but to use any... | There is a branch of conda (new-pypi-install) that adds better integration with pip and PyPI. In particular conda list will also show pip installed packages and conda install will first try to find a conda package and failing that will use pip to install the package.
This branch is scheduled to be merged later this we... |
How do I keep track of pip-installed packages in an Anaconda (Conda) environment? | 18,640,305 | 60 | 2013-09-05T15:25:41Z | 20,750,388 | 11 | 2013-12-23T20:04:21Z | [
"python",
"pip",
"anaconda",
"env",
"conda"
] | I've installed and have been using the [Anaconda](https://en.wikipedia.org/wiki/Anaconda_%28Python_distribution%29) Python distribution, and I have started using the Anaconda (Conda) environment. I can use the standard `conda install...` command to put packages from the distribution into my environments, but to use any... | I followed @Viktor Kerkez's answer and have had mixed success. I found that sometimes this recipe of
> conda skeleton pypi PACKAGE
>
> conda build PACKAGE
would look like everything worked but I could not successfully import PACKAGE. Recently I asked about this on the [Anaconda user group](https://groups.google.com/a... |
How do I keep track of pip-installed packages in an Anaconda (Conda) environment? | 18,640,305 | 60 | 2013-09-05T15:25:41Z | 33,694,864 | 35 | 2015-11-13T14:21:44Z | [
"python",
"pip",
"anaconda",
"env",
"conda"
] | I've installed and have been using the [Anaconda](https://en.wikipedia.org/wiki/Anaconda_%28Python_distribution%29) Python distribution, and I have started using the Anaconda (Conda) environment. I can use the standard `conda install...` command to put packages from the distribution into my environments, but to use any... | [conda-env](https://github.com/conda/conda-env/) now does this automatically (if pip was installed with conda).
You can see how this works by using the export tool used for migrating an environment:
```
conda env export -n <env-name> > environment.yml
```
The file will list both conda packages and pip packages:
```... |
pandas: fill a column with some numpy arrays | 18,641,148 | 7 | 2013-09-05T16:08:51Z | 18,641,464 | 7 | 2013-09-05T16:26:20Z | [
"python",
"pandas"
] | I am using python2.7 and pandas 0.11.0.
I try to fill a column of a dataframe using DataFrame.apply(func). The func() function is supposed to return a numpy array (1x3).
```
import pandas as pd
import numpy as np
df= pd.DataFrame(np.random.randn(4, 3), columns=list('ABC'))
print(df)
A B ... | If you try to return multiple values from the function that is passed to `apply`, and the DataFrame you call the `apply` on has the same number of item along the axis (in this case columns) as the number of values you returned, Pandas will create a DataFrame from the return values with the same labels as the original D... |
Installing Pip-3.2 on Cygwin | 18,641,438 | 52 | 2013-09-05T16:24:59Z | 18,644,294 | 43 | 2013-09-05T19:21:06Z | [
"python",
"python-3.x",
"cygwin",
"pip"
] | I have Python 3 installed on Cygwin. However, I am unable to install Python 3 packages via `pip`. Is there a way to do this? | If you have more than one python installation, then you need to install pip (and probably also setuptools) for each installation separately.
To do so, you can first download [`ez_setup.py`](https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py) and run it with python3:
```
/usr/bin/python3 ez_setup.py
```
... |
Installing Pip-3.2 on Cygwin | 18,641,438 | 52 | 2013-09-05T16:24:59Z | 30,685,412 | 18 | 2015-06-06T17:03:51Z | [
"python",
"python-3.x",
"cygwin",
"pip"
] | I have Python 3 installed on Cygwin. However, I am unable to install Python 3 packages via `pip`. Is there a way to do this? | I think [the alternative install instructions](https://pip.pypa.io/en/latest/installing.html) linked by mata are simplest:
> To install pip, securely download [get-pip.py](https://bootstrap.pypa.io/get-pip.py).
>
> Then run the following (which may require administrator access):
>
> ```
> python get-pip.py
> ``` |
Installing Pip-3.2 on Cygwin | 18,641,438 | 52 | 2013-09-05T16:24:59Z | 32,027,563 | 60 | 2015-08-15T17:50:57Z | [
"python",
"python-3.x",
"cygwin",
"pip"
] | I have Python 3 installed on Cygwin. However, I am unable to install Python 3 packages via `pip`. Is there a way to do this? | 1)While installing cygwin, make sure you install the
python/python-setuptools from the list. This will install "easy\_install" package.
2) Type the following command:
```
easy_install-a.b pip
```
You must replace `a.b` with your python version which can be 2.7 or 3.4 or whatever else. |
concatenate an arbitrary number of lists in a function in Python | 18,642,428 | 6 | 2013-09-05T17:26:46Z | 18,642,464 | 8 | 2013-09-05T17:29:03Z | [
"python",
"list"
] | I hope to write the `join_lists` function to take an arbitrary number of lists and concatenate them. For example, if the inputs are
```
m = [1, 2, 3]
n = [4, 5, 6]
o = [7, 8, 9]
```
then we I call `print join_lists(m, n, o)`, it will return `[1, 2, 3, 4, 5, 6, 7, 8, 9]`. I realize I should use `*args` as the argument... | One way would be this (using `reduce`) because I currently feel functional:
```
import operator
from functools import reduce
def concatenate(*lists):
return reduce(operator.add, lists)
```
However, a better functional method is given in Marcin's answer:
```
from itertools import chain
def concatenate(*lists):
... |
concatenate an arbitrary number of lists in a function in Python | 18,642,428 | 6 | 2013-09-05T17:26:46Z | 18,642,549 | 13 | 2013-09-05T17:34:02Z | [
"python",
"list"
] | I hope to write the `join_lists` function to take an arbitrary number of lists and concatenate them. For example, if the inputs are
```
m = [1, 2, 3]
n = [4, 5, 6]
o = [7, 8, 9]
```
then we I call `print join_lists(m, n, o)`, it will return `[1, 2, 3, 4, 5, 6, 7, 8, 9]`. I realize I should use `*args` as the argument... | Although you can use something which invokes `__add__` sequentially, that is very much the wrong thing (for starters you end up creating as many new lists as there are lists in your input, which ends up having quadratic complexity).
The standard tool is `itertools.chain`:
```
def concatenate(*lists):
return itert... |
Why search in sorted list in python takes longer? | 18,643,653 | 6 | 2013-09-05T18:42:28Z | 18,643,853 | 7 | 2013-09-05T18:53:23Z | [
"python",
"list",
"sorting",
"search"
] | I did an experiment in which I tried to find the time it takes to search a python list. I have a list `arr` with random integers. `arr_s` has the same elements only sorted.
```
arr = np.random.randint(low = 0, high = 1000, size = 500)
arr_s = sorted(arr)
```
Now I create a random array of integers `find` which has el... | ```
arr = np.random.randint(low = 0, high = 1000, size = 500)
arr_s = sorted(arr)
```
`arr` is an array. `arr_s` is a list. Searching an array can be handled efficiently by numpy, but searching a list requires following pointers and performing type checks. It has nothing to do with sorting.
Note: [`in` does weird thi... |
GeoDjango GEOSException error | 18,643,998 | 21 | 2013-09-05T19:03:18Z | 18,721,622 | 45 | 2013-09-10T14:28:06Z | [
"python",
"django",
"homebrew",
"geodjango"
] | Trying to install a GeoDjango on my machine. I'm really new to Python and being brought into a project that has been a very tricky install for the other team members. I installed Python 2.7 and GEOS using brew, and running PSQL 9.2.4 but keep getting this error when I try to get the webserver running:
```
__import__(n... | This is my solution (obviously it is ugly, like my English, but works).
The problem is that the versions string has an white space unwanted in the RegEx.
The error says:
*GEOSException: Could not parse version info string "3.4.2-CAPI-1.8.2 r3921"*
And the geos\_version\_info warns:
*Regular expression should be abl... |
GeoDjango GEOSException error | 18,643,998 | 21 | 2013-09-05T19:03:18Z | 19,811,665 | 12 | 2013-11-06T12:04:13Z | [
"python",
"django",
"homebrew",
"geodjango"
] | Trying to install a GeoDjango on my machine. I'm really new to Python and being brought into a project that has been a very tricky install for the other team members. I installed Python 2.7 and GEOS using brew, and running PSQL 9.2.4 but keep getting this error when I try to get the webserver running:
```
__import__(n... | In the latest GEOS install, the above answer didn't work... but was close to the problem.
I changed the regex right above the geos\_version\_info():
from:
```
version_regex = re.compile(r'^(?P<version>(?P<major>\d+)\.(?P<minor>\d+)\.(?P<subminor>\d+))((rc(?P<release_candidate>\d+))|dev)?-CAPI-(?P<capi_version>\d+\.\d... |
Get Unique Tuples from List , Python | 18,644,091 | 8 | 2013-09-05T19:08:42Z | 18,644,123 | 10 | 2013-09-05T19:10:48Z | [
"python",
"list",
"set"
] | ```
>>> a= ('one', 'a')
>>> b = ('two', 'b')
>>> c = ('three', 'a')
>>> l = [a, b, c]
>>> l
[('one', 'a'), ('two', 'b'), ('three', 'a')]
```
How can I check for only the elements of this list with a unique second entry (column? item?), and then grab the first entry found on the list. Desired output is
```
>>> l
[('on... | Use a set (if the second item is hash-able):
```
>>> lis = [('one', 'a'), ('two', 'b'), ('three', 'a')]
>>> seen = set()
>>> [item for item in lis if item[1] not in seen and not seen.add(item[1])]
[('one', 'a'), ('two', 'b')]
```
The above code is equivalent to:
```
>>> seen = set()
>>> ans = []
for item in lis:
... |
How to manipulate wav file data in Python? | 18,644,166 | 7 | 2013-09-05T19:13:57Z | 18,644,461 | 10 | 2013-09-05T19:31:24Z | [
"python",
"scipy",
"wav"
] | I'm trying to read a wav file, then manipulate its contents, sample by sample
Here's what I have so far:
```
import scipy.io.wavfile
import math
rate, data = scipy.io.wavfile.read('xenencounter_23.wav')
for i in range(len(data)):
data[i][0] = math.sin(data[i][0])
print data[i][0]
```
The result I get is:
... | The array `data` returned by `wavfile.read` is a numpy array with an *integer* data type. The data type of a numpy array can not be changed in place, so this line:
```
data[i][0] = math.sin(data[i][0])
```
casts the result of `math.sin` to an integer, which will always be 0.
Instead of that line, create a new floati... |
and operation overloading in python | 18,644,263 | 5 | 2013-09-05T19:19:26Z | 18,644,311 | 7 | 2013-09-05T19:21:49Z | [
"python"
] | I know logically `and` is used for booleans evaluating to true if both the conditions are true, but I have a problem with the following statement:
```
print "ashish" and "sahil"
it prints out "sahil"?
another example:
return s[0] == s[-1] and checker(s[1:-1])
(taken from recursive function for palindrome string
c... | `x and y` basically means:
> return `y`, unless `x` is False-ish - in such case return `x`
Here is a list of possible combinations:
```
>>> from itertools import combinations
>>> items = [True, False, 0, 1, 2, '', 'yes', 'no']
>>> for a, b in combinations(items, 2):
print '%r and %r => %r' % (a, b, a and b)
Tr... |
and operation overloading in python | 18,644,263 | 5 | 2013-09-05T19:19:26Z | 18,644,313 | 10 | 2013-09-05T19:21:55Z | [
"python"
] | I know logically `and` is used for booleans evaluating to true if both the conditions are true, but I have a problem with the following statement:
```
print "ashish" and "sahil"
it prints out "sahil"?
another example:
return s[0] == s[-1] and checker(s[1:-1])
(taken from recursive function for palindrome string
c... | `and` is not overloaded.
In your code, `"ashish"` is a truthy value (because non-empty strings are truthy), so it evaluates `"sahil"`. As `"sahil"` is also a truthy value, `"sahil"` is returned to the print statement and is then printed. |
Windowed maximum in numpy | 18,645,013 | 9 | 2013-09-05T20:08:41Z | 18,645,174 | 9 | 2013-09-05T20:18:43Z | [
"python",
"numpy"
] | I have an array and I would like to produce a smaller array by scanning a 2x2 non-overlappingly windows and getting the maximum. Here is an example:
```
import numpy as np
np.random.seed(123)
np.set_printoptions(linewidth=1000,precision=3)
arr = np.random.uniform(-1,1,(4,4))
res = np.zeros((2,2))
for i in xrange(res.... | You can do this:
```
print arr.reshape(2,2,2,2).swapaxes(1,2).reshape(2,2,4).max(axis=-1)
[[ 0.439 0.962]
[-0.038 0.476]]
```
To explain starting with:
```
arr=np.array([[0.393,-0.428,-0.546,0.103],
[0.439,-0.154,0.962,0.37,],
[-0.038,-0.216,-0.314,0.458],
[-0.123,-0.881,-0.204,0.476]])
```
We first want to gro... |
Django REST framework object level permissions | 18,645,175 | 15 | 2013-09-05T20:18:48Z | 18,646,798 | 13 | 2013-09-05T22:13:28Z | [
"python",
"django",
"permissions",
"django-rest-framework"
] | I am using Django REST Framework to access a resource 'user'.
As user information is personal, I do not want a GET request to list every user on the system, UNLESS they are an admin.
If the user specifies their id, and they are logged in, I would like them to be able to view their details and amend them (PUT POST DEL... | I have done this in the past using a custom permission and overridden [`has_object_permission`](http://django-rest-framework.org/api-guide/permissions.html#custom-permissions) like the following:
```
from rest_framework import permissions
class MyUserPermissions(permissions.BasePermission):
"""
Handles permi... |
Django REST framework object level permissions | 18,645,175 | 15 | 2013-09-05T20:18:48Z | 23,437,552 | 7 | 2014-05-02T21:54:41Z | [
"python",
"django",
"permissions",
"django-rest-framework"
] | I am using Django REST Framework to access a resource 'user'.
As user information is personal, I do not want a GET request to list every user on the system, UNLESS they are an admin.
If the user specifies their id, and they are logged in, I would like them to be able to view their details and amend them (PUT POST DEL... | I have a similar need. Lets call my app `x`. Here's what I came up with.
First, put this in `x/viewsets.py`:
```
# viewsets.py
from rest_framework import mixins, viewsets
class DetailViewSet(
mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.Gen... |
Call python script from ruby | 18,645,352 | 7 | 2013-09-05T20:28:48Z | 18,645,461 | 8 | 2013-09-05T20:35:03Z | [
"python",
"ruby"
] | For example, I can use Python scripts in PHP like there:
```
exec("python script.py params",$result);
```
, where "script.py" - script name and var $result save output data.
How I can make it with Ruby? I mean, call Python scripts from Ruby. | You can shell-out to any shell binary and capture the response with backticks:
```
result = `python script.py params`
``` |
Python pandas to_excel 'utf8' codec can't decode byte | 18,645,401 | 7 | 2013-09-05T20:31:06Z | 18,661,440 | 9 | 2013-09-06T15:35:33Z | [
"python",
"excel",
"utf-8",
"pandas"
] | I'm trying to do some data work in Python pandas and having trouble writing out my results.
I read my data in as a CSV file and been exporting each script as it's own CSV file which works fine. Lately though I've tried exporting everything in 1 Excel file with worksheets and a few of the sheets give me an error
"'utf8... | Managed to solve this.
I made a function that goes through my columns that have strings and managed to decode/encode them into utf8 and it now works.
```
def changeencode(data, cols):
for col in cols:
data[col] = data[col].str.decode('iso-8859-1').str.encode('utf-8')
return data
``` |
Add numpy array as column to Pandas data frame | 18,646,076 | 8 | 2013-09-05T21:15:01Z | 18,646,275 | 7 | 2013-09-05T21:29:40Z | [
"python",
"numpy",
"pandas"
] | I have a Pandas data frame object of shape (X,Y) that looks like this:
```
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
```
and a numpy sparse matrix (CSC) of shape (X,Z) that looks something like this
```
[[0, 1, 0],
[0, 0, 1],
[1, 0, 0]]
```
How can I add the content from the matrix to the data frame in a new named column s... | ```
import numpy as np
import pandas as pd
import scipy.sparse as sparse
df = pd.DataFrame(np.arange(1,10).reshape(3,3))
arr = sparse.coo_matrix(([1,1,1], ([0,1,2], [1,2,0])), shape=(3,3))
df['newcol'] = arr.toarray().tolist()
print(df)
```
yields
```
0 1 2 newcol
0 1 2 3 [0, 1, 0]
1 4 5 6 [0, 0, 1]... |
Why is sin(180) not zero when using python and numpy? | 18,646,477 | 8 | 2013-09-05T21:45:04Z | 18,647,014 | 9 | 2013-09-05T22:33:49Z | [
"python",
"numpy",
"sin"
] | Does anyone know why the below doesn't equal 0?
```
import numpy as np
np.sin(np.radians(180))
```
or:
```
np.sin(np.pi)
```
When I enter it into python it gives me 1.22e-16. | The number `Ï` cannot be represented exactly as a floating-point number. So, `np.radians(180)` doesn't give you `Ï`, it gives you `3.1415926535897931`.
And `sin(3.1415926535897931)` is in fact something like `1.22e-16`.
So, how do you deal with this?
You have to work out, or at least guess at, appropriate absolute... |
In Python, variables inside if conditions hide the global scope even if they are not executed? | 18,647,162 | 11 | 2013-09-05T22:47:20Z | 18,647,337 | 7 | 2013-09-05T23:06:16Z | [
"python"
] | ```
def do_something():
print 'doing something...'
def maybe_do_it(hesitant=False):
if hesitant:
do_something = lambda: 'did nothing'
result = do_something()
print result
maybe_do_it()
```
The result of this code is:
```
File "scope_test.py", line 10, in <module>
maybe_do_it()
File "... | > How did the function get overridden even though the condition inside the if statement never executed?
The decision whether the variable is local or global is made at compile time. If there is an assignment to a variable anywhere in the function, it's a local variable, no matter if the assignment is ever executed.
>... |
Can't create new threads in Python | 18,647,230 | 4 | 2013-09-05T22:54:26Z | 18,648,672 | 15 | 2013-09-06T01:54:14Z | [
"python",
"multithreading",
"python-multithreading"
] | ```
import threading
threads = []
for n in range(0, 60000):
t = threading.Thread(target=function,args=(x, n))
t.start()
threads.append(t)
for t in threads:
t.join()
```
It is working well for range up to 800 on my laptop, but if I increase range to more than 800 I get the error `can't create new threa... | The problem is that no major platform (as of mid-2013) will let you create anywhere near this number of threads. There are a wide variety of different limitations you could run into, and without knowing your platform, its configuration, and the exact error you got, it's impossible to know which one you ran into. But he... |
Count letters in a text file | 18,647,707 | 4 | 2013-09-05T23:47:07Z | 18,647,773 | 10 | 2013-09-05T23:55:13Z | [
"python"
] | I am a beginner python programmer and I am trying to make a program which counts the numbers of letters in a text file. Here is what I've got so far:
```
import string
text = open('text.txt')
letters = string.ascii_lowercase
for i in text:
text_lower = i.lower()
text_nospace = text_lower.replace(" ", "")
text_n... | This is very readable way to accomplish what you want using [Counter](http://docs.python.org/2/library/collections.html#collections.Counter):
```
from string import ascii_lowercase
from collections import Counter
with open('text.txt') as f:
print Counter(letter for line in f
for letter in line.... |
Python "for loop" with two variables | 18,648,626 | 25 | 2013-09-06T01:48:29Z | 18,648,653 | 9 | 2013-09-06T01:52:13Z | [
"python",
"for-loop"
] | How can I include two variables in the same *for loop*:
```
t1 = [a list of integers, strings and lists]
t2 = [another list of integers, strings and lists]
def f(t): #a function that will read lists "t1" and "t2" and return all elements that are identical
for i in range(len(t1)) and for j in range(len(t2)):
... | Any reason you can't use a nested for loop?
```
for i in range(x):
for j in range(y):
``` |
Python "for loop" with two variables | 18,648,626 | 25 | 2013-09-06T01:48:29Z | 18,648,679 | 51 | 2013-09-06T01:55:29Z | [
"python",
"for-loop"
] | How can I include two variables in the same *for loop*:
```
t1 = [a list of integers, strings and lists]
t2 = [another list of integers, strings and lists]
def f(t): #a function that will read lists "t1" and "t2" and return all elements that are identical
for i in range(len(t1)) and for j in range(len(t2)):
... | If you want the effect of a nested for loop, use:
```
import itertools
for i, j in itertools.product(range(x), range(y)):
# Stuff...
```
If you just want to loop simultaneously, use:
```
for i, j in zip(range(x), range(y)):
# Stuff...
```
Note that if `x` and `y` are not the same length, `zip` will truncate... |
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128) | 18,649,512 | 41 | 2013-09-06T03:42:23Z | 18,649,608 | 48 | 2013-09-06T03:54:10Z | [
"python",
"python-2.7"
] | I'm using NLTK to perform kmeans clustering on my text file in which each line is considered as a document. So for example, my text file is something like this:
belong finger death punch
hasty
mike hasty walls jericho
jägermeister rules
rules bands follow performing jägermeister stage
approach
Now th... | The file is being read as a bunch of `str`s, but it should be `unicode`s. Python tries to implicitly convert, but fails. Change:
```
job_titles = [line.strip() for line in title_file.readlines()]
```
to explicitly decode the `str`s to `unicode` (here assuming UTF-8):
```
job_titles = [line.decode('utf-8').strip() fo... |
Python list comprehension for loops | 18,649,884 | 10 | 2013-09-06T04:26:34Z | 18,649,916 | 11 | 2013-09-06T04:29:57Z | [
"python",
"for-loop",
"list-comprehension"
] | I'm reading [the Python wikibook](https://en.wikibooks.org/wiki/Python_Programming/Lists) and feel confused about this part:
> List comprehension supports more than one for statement. It will
> evaluate the items in all of the objects sequentially and will loop
> over the shorter objects if one object is longer than t... | Just try it:
```
>>> [x+y for x in 'cat' for y in 'potty']
['cp', 'co', 'ct', 'ct', 'cy', 'ap', 'ao', 'at', 'at', 'ay', 'tp', 'to', 'tt', 'tt', 'ty']
>>> [x+y for x in 'catty' for y in 'pot']
['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'to', 'tt', 'tp', 'to', 'tt', 'yp', 'yo', 'yt']
```
The **inner** 'x' in the list c... |
Argparse unit tests: Suppress the help message | 18,651,705 | 4 | 2013-09-06T06:55:50Z | 18,652,005 | 9 | 2013-09-06T07:14:06Z | [
"python",
"unit-testing",
"argparse"
] | I'm writing test cases for argparse implementation. I intend to test '-h' feature. The following code does it. But it also outputs the usage for the script. Is there a way to suppress that?
```
self.assertRaises(SystemExit, arg_parse_obj.parse_known_args, ['-h'])
```
Also, can we check for the exception number thrown... | When testing for exception codes, use [`self.assertRaises()` as a context manager](http://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRaises); this gives you access to the raised exception, letting you test the `.code` attribute:
```
with self.assertRaises(SystemExit) as cm:
arg_parse_obj.parse... |
scipy equivalent for MATLAB spy | 18,651,869 | 4 | 2013-09-06T07:06:15Z | 18,652,689 | 8 | 2013-09-06T07:55:20Z | [
"python",
"matlab",
"scipy"
] | I have been porting code for an isomap algorithm from MATLAB to Python. I am trying to visualize the sparsity pattern using the spy function.
MATLAB command:
```
spy(sparse(A));
drawnow;
```
Python command:
```
matplotlib.pyplot.spy(scipy.sparse.csr_matrix(A))
plt.show()
```
I am not able to reproduce the MATLAB r... | Maybe it's your version of `matplotlib` that makes trouble, as for me `scipy.sparse` and `matplotlib.pylab` work well together.
See sample code below that produces the 'spy' plot attached.
```
import matplotlib.pylab as plt
import scipy.sparse as sps
A = sps.rand(10000,10000, density=0.00001)
M = sps.csr_matrix(A)
pl... |
A Pythonic way for "resume next" on exceptions? | 18,655,481 | 3 | 2013-09-06T10:21:41Z | 18,655,611 | 7 | 2013-09-06T10:26:51Z | [
"python",
"exception",
"exception-handling"
] | The problem:
I am reading a series of heterogeneous input files. I wrote a reader class for each of them, which reads the file using `__init__(self, file_name)`, and throws an exception in case of malformed input.
The code looks like this:
```
clients = Clients ('Clients.csv' )
si... | Store the classes and files in a sequence, the results into a dictionary:
```
inputs = (
(Clients, 'Clients.csv'),
(Simulation, 'Simulation.csv'),
(Indicators, 'Indicators.csv'),
(LegalEntity, 'LegalEntity.csv'),
(DefaultPortfolio, 'DefaultPortfolio.csv'),
(ExcludedProductTypes, 'ExcludedProduc... |
What exactly is the point of memoryview in Python | 18,655,648 | 14 | 2013-09-06T10:28:37Z | 18,655,702 | 12 | 2013-09-06T10:31:18Z | [
"python",
"buffer",
"memoryview"
] | **Checking the [documentation](http://docs.python.org/dev/library/stdtypes.html#memoryview) on memoryview:**
> memoryview objects allow Python code to access the internal data of an
> object that supports the buffer protocol without copying.
>
> class **memoryview**(obj)
>
> Create a memoryview that references obj. ob... | `memoryview` objects are great when you need subsets of binary data that only need to support indexing. Instead of having to take slices (and create new, potentially large) objects to pass to *another API* you can just take a `memoryview` object.
One such API example would be the `struct` module. Instead of passing in... |
What exactly is the point of memoryview in Python | 18,655,648 | 14 | 2013-09-06T10:28:37Z | 34,257,357 | 8 | 2015-12-13T22:51:16Z | [
"python",
"buffer",
"memoryview"
] | **Checking the [documentation](http://docs.python.org/dev/library/stdtypes.html#memoryview) on memoryview:**
> memoryview objects allow Python code to access the internal data of an
> object that supports the buffer protocol without copying.
>
> class **memoryview**(obj)
>
> Create a memoryview that references obj. ob... | One reason `memoryviews` are useful is because they can be sliced without copying the underlying data, unlike `bytes`/`str`.
For example, take the following toy example.
```
import time
for n in (100000, 200000, 300000, 400000):
data = 'x'*n
start = time.time()
b = data
while b:
b = b[1:]
... |
XPath: Find HTML element by *plain* text | 18,655,765 | 8 | 2013-09-06T10:35:07Z | 18,655,869 | 17 | 2013-09-06T10:41:19Z | [
"python",
"xpath",
"selenium"
] | *Please note:* A more refined version of this question, with an appropriate answer can be found [here](http://stackoverflow.com/questions/18703467/xpath-find-html-element-by-plain-text/18703468 "Refined version of this question on SO").
I would like to use the Selenium Python bindings to find elements with a given tex... | You can use `//*[contains(., 'This can not be found')]`.
The context node `.` will be converted to its string representation before comparison to 'This can not be found'.
**Be careful though** since you are using `//*`, so it will match **ALL** englobing elements that contain this string.
In your example case, it wi... |
How to convert list of elements to their default types | 18,656,498 | 2 | 2013-09-06T11:15:38Z | 18,656,542 | 7 | 2013-09-06T11:18:04Z | [
"python",
"list"
] | for eg I have the List:
```
old = ['Savannah', '234Today', '4.5678', '23456','0.2342429']
```
How can I convert it to a list with elements with the default type
to:
```
new = ['Savannah', '234Today', 4.5678, 23456,0.2342429]
```
The new list will have the elements with their default type be it float, int, long
... | You can use `ast.literal_eval` and some exception handling:
```
>>> from ast import literal_eval
>>> lis = ['Savannah', '234Today', '4.5678', '23456','0.2342429']
def solve(x):
try:
return literal_eval(x)
except (ValueError, SyntaxError):
return x
...
>>> map(solve, lis)
['Savannah', '234T... |
Error : "Document BlogPost may not be subclassed" mongoengine | 18,656,747 | 3 | 2013-09-06T11:28:32Z | 18,657,236 | 13 | 2013-09-06T11:53:09Z | [
"python",
"django",
"pymongo",
"mongoengine"
] | I am using pymongo version 2.6.1 with mongoengine 0.8.4. And I want to create one code using tutorial given in
link <https://mongoengine-odm.readthedocs.org/en/latest/tutorial.html>
My code is as follows in sample.py file:
```
from mongoengine import *
import datetime
class BlogPost(Document):
title = StringFie... | Looking at [the docs](https://mongoengine-odm.readthedocs.org/en/latest/tutorial.html#posts), it seems that you need:
```
meta = {'allow_inheritance': True}
```
in your `BlogPost` class. |
Recursive generator in Pythonic way? | 18,657,935 | 2 | 2013-09-06T12:30:00Z | 18,657,974 | 8 | 2013-09-06T12:32:18Z | [
"python",
"functional-programming"
] | Below is a generator that can create all combinations made of one character from a number of strings:
```
('ab', 'cd', 'ef') => 'ace', 'acf', 'ade', 'adf', 'bce', 'bcf', 'bde', 'bdf'.
```
However, I wonder if this can be done in a more Pythonic.
```
# Example input data
t = ('ab', 'cd', 'ef')
# Recursive generator
... | You can use `itertools.product`:
```
>>> from itertools import product
>>> lis = ('ab', 'cd', 'ef')
for p in product(*lis):
print "".join(p)
...
ace
acf
ade
adf
bce
bcf
bde
bdf
``` |
Generating a list of random numbers, summing to 1 | 18,659,858 | 15 | 2013-09-06T14:11:42Z | 18,659,948 | 15 | 2013-09-06T14:16:06Z | [
"python",
"random"
] | How would I make a list of N (say 100) random numbers, so that their sum is 1?
I can make a list of random numbers with
```
r = [ran.random() for i in range(1,100)]
```
How would I modify this so that the list sums to 1 (this is for a probability simulation). | The best way to do this is to simply make a list of as many numbers as you wish, then divide them all by the sum. They are totally random this way.
```
r = [ran.random() for i in range(1,100)]
s = sum(r)
r = [ i/s for i in r ]
```
or, as suggested by @TomKealy, keep the sum and creation in one loop:
```
rs = []
s = ... |
Generating a list of random numbers, summing to 1 | 18,659,858 | 15 | 2013-09-06T14:11:42Z | 18,662,466 | 25 | 2013-09-06T16:32:23Z | [
"python",
"random"
] | How would I make a list of N (say 100) random numbers, so that their sum is 1?
I can make a list of random numbers with
```
r = [ran.random() for i in range(1,100)]
```
How would I modify this so that the list sums to 1 (this is for a probability simulation). | The simplest solution is indeed to take N random values and divide by the sum.
A more generic solution is to use the Dirichlet distribution
<http://en.wikipedia.org/wiki/Dirichlet_distribution>
which is available in numpy.
By changing the parameters of the distribution you can change the "randomness" of individual nu... |
How can I preserve <br> as newlines with lxml.html text_content() or equivalent? | 18,660,382 | 9 | 2013-09-06T14:39:43Z | 18,661,076 | 13 | 2013-09-06T15:15:31Z | [
"python",
"lxml",
"lxml.html"
] | I want to preserve `<br>` tags as `\n` when extracting the text content from lxml elements.
Example code:
`fragment = '<div>This is a text node.<br/>This is another text node.<br/><br/><span>And a child element.</span><span>Another child,<br> with two text nodes</span></div>'`
```
h = lxml.html.fromstring(fragment)
... | Prepending an `\n` character to the tail of each `<br />` element should give the result you're expecting:
```
>>> import lxml.html as html
>>> fragment = '<div>This is a text node.<br/>This is another text node.<br/><br/><span>And a child element.</span><span>Another child,<br> with two text nodes</span></div>'
>>> d... |
Crontab Command Separate Line | 18,661,492 | 3 | 2013-09-06T15:38:17Z | 18,661,587 | 8 | 2013-09-06T15:43:46Z | [
"python",
"linux",
"shell",
"crontab"
] | I have two python scripts:
```
#1. getUrl.py # used to collect target urls which takes about 10 mins and used as the input for the next script
#2. monitoring.py # used to monitoring the website.
00 01 * * * /usr/bin/python /ephemeral/monitoring/getUrl.py > /ephemeral/monitoring/input && /usr/bin/python /ephemeral/mon... | No, you can't do that. From the man page:
> There is no way to split a single command line onto multiple lines,
> like the shell's trailing "\".
You can put the commands in a script and run it. |
In Python/NumPy, how to pad an array by replicating the elements? | 18,662,189 | 3 | 2013-09-06T16:16:20Z | 18,662,291 | 8 | 2013-09-06T16:21:58Z | [
"python",
"arrays",
"numpy"
] | For example, if I have an array
```
[1, 2, 1]
```
and I want to get a new array which is 4 times the length
```
[1,1,1,1,2,2,2,2,1,1,1,1]
```
How do I do this? | This is what [`numpy.repeat`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html) is for.
```
>>> x = numpy.array([1, 2, 1])
>>> numpy.repeat(x, 4)
array([1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1])
``` |
urllib.unquote_plus(s) does not convert plus symbol to space | 18,662,264 | 3 | 2013-09-06T16:20:54Z | 18,662,281 | 8 | 2013-09-06T16:21:40Z | [
"python"
] | from the documents, the urllib.unquote\_plus should replce plus signs by spaces.
but when I tried the below code in IDLE for python 2.7, it did not.
```
>>s = 'http://stackoverflow.com/questions/?q1=xx%2Bxx%2Bxx'
>>urllib.unquote_plus(s)
>>'http://stackoverflow.com/questions/?q1=xx+xx+xx'
```
I also tried doing somet... | `%2B` is the escape code for a *literal* `+`; it is being unescaped entirely correctly.
Don't confuse this with the *URL escaped* `+`, which is the escape character for spaces:
```
>>> s = 'http://stackoverflow.com/questions/?q1=xx+xx+xx'
>>> urllib.unquote_plus(s)
'http://stackoverflow.com/questions/?q1=xx xx xx'
``... |
Flask: How to render the linebreak in template? | 18,662,898 | 7 | 2013-09-06T17:00:37Z | 18,664,389 | 9 | 2013-09-06T18:35:21Z | [
"python",
"flask",
"wtforms",
"flask-wtforms"
] | I have a simple form like this:
```
class RecordForm(Form):
notes = TextAreaField('Notes')
```
I record the data in three paragraphs like this:
```
para1
para2
para3
```
In the template I would like to see the content of that record in read-only. (Not editable form)
record is this case the model containi... | All whitespace, including newlines, is turned into a single space in HTML.
Your options, from best to worst:
1. Put `white-space: pre-wrap;` on the containing element. This tells HTML to show all whitespace exactly as it appears in the source, including newlines. (You could also use a `<pre>` tag, but that will also ... |
python help! If/else statement | 18,662,975 | 2 | 2013-09-06T17:05:49Z | 18,663,072 | 8 | 2013-09-06T17:10:59Z | [
"python",
"if-statement"
] | I have been learning python through code academy. It asked me to create a if else statement that prints the users input, but if there is no input print "empty". I did pass the tutorial but when there is a user input it prints both the users input and "empty".
here is my code:
```
print "Welcome to the English to Pig ... | You seem to have a couple issues with your code. First I believe you should change your assignment of `length` to:
```
length = len(original)
```
That way you get the correct length of the string you binded to the name `original`. If you use `len("original")`, you will pass the string "original" to the `len()` functi... |
How do I pythonically set a value in a dictionary if it is None? | 18,663,026 | 4 | 2013-09-06T17:08:37Z | 18,663,052 | 17 | 2013-09-06T17:10:03Z | [
"python",
"dictionary"
] | This code is not bad, but I want to know how good programmers will write the code
```
if count.get('a') is None:
count['a'] = 0
``` | You can use `dict.setdefault` :
```
count.setdefault('a', 0)
```
help on `dict.setdefault`:
```
>>> print dict.setdefault.__doc__
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
``` |
How to account for accent characters for regex in Python? | 18,663,644 | 4 | 2013-09-06T17:48:05Z | 18,663,728 | 13 | 2013-09-06T17:52:15Z | [
"python",
"regex",
"django",
"hashtag",
"non-ascii-characters"
] | I currently use re.findall to find and isolate words after the '#' character for hash tags in a string:
```
hashtags = re.findall(r'#([A-Za-z0-9_]+)', str1)
```
It searches str1 and finds all the hashtags. This works however it doesn't account for accented characters like these for example: `áéÃóúñü¿`.
If on... | Try the following:
```
hashtags = re.findall(r'#(\w+)', str1, re.UNICODE)
```
[Regex101 Demo](http://www.regex101.com/r/cJ1wX7)
**EDIT**
Check the useful comment below from Martijn Pieters. |
Multiple pages using Reportlab - Django | 18,664,226 | 11 | 2013-09-06T18:24:20Z | 18,664,836 | 23 | 2013-09-06T19:05:34Z | [
"python",
"django",
"reportlab"
] | I'm working in a site using Django and I print a .pdf file using Repotlab.
Now, I want the file to have multiple pages, how can I do it?
My code:
```
from reportlab.pdfgen import canvas
from django.http import HttpResponse
def Print_PDF(request):
response = HttpResponse(content_type='application/pdf')
respo... | `showPage()`, despite its confusing name, will actually end the current page, so anything you draw on the canvas after calling it will go on the next page.
In your example, you can just use `p.showPage()` after each `p.drawString` example and they will all appear on their own page.
```
def Print_PDF(request):
res... |
Split function add: \xef\xbb\xbf...\n to my list | 18,664,712 | 21 | 2013-09-06T18:58:41Z | 18,664,752 | 36 | 2013-09-06T19:00:58Z | [
"python",
"split"
] | I want to open my `file.txt` and split all data from this file.
Here is my `file.txt`:
```
some_data1 some_data2 some_data3 some_data4 some_data5
```
and here is my python code:
```
>>>file_txt = open("file.txt", 'r')
>>>data = file_txt.read()
>>>data_list = data.split(' ')
>>>print data
some_data1 some_data2 some_... | Your file contains [UTF-8 BOM](http://en.wikipedia.org/wiki/Byte_order_mark) in the beginning.
To get rid of it, first decode your file contents to unicode.
```
fp = open("file.txt")
data = fp.read().decode("utf-8-sig").encode("utf-8")
```
But better don't encode it back to `utf-8`, but work with `unicode`d text. Th... |
Split function add: \xef\xbb\xbf...\n to my list | 18,664,712 | 21 | 2013-09-06T18:58:41Z | 18,664,766 | 7 | 2013-09-06T19:01:55Z | [
"python",
"split"
] | I want to open my `file.txt` and split all data from this file.
Here is my `file.txt`:
```
some_data1 some_data2 some_data3 some_data4 some_data5
```
and here is my python code:
```
>>>file_txt = open("file.txt", 'r')
>>>data = file_txt.read()
>>>data_list = data.split(' ')
>>>print data
some_data1 some_data2 some_... | The `\xef\xbb\xbf` is a [Byte Order Mark](http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding) for UTF-8 - the `\x` [is an escape sequence](http://docs.python.org/2/reference/lexical_analysis.html#string-literals) indicating the next two characters are a hex sequence representin... |
Loop through netcdf files and run calculations - Python or R | 18,665,078 | 5 | 2013-09-06T19:20:53Z | 18,666,291 | 9 | 2013-09-06T20:44:18Z | [
"python",
"netcdf"
] | This is my first time using netCDF and I'm trying to wrap my head around working with it.
I have multiple version 3 netcdf files (NOAA NARR air.2m daily averages for an entire year). Each file spans a year between 1979 - 2012. They are 349 x 277 grids with approximately a 32km resolution. Data was downloaded from [her... | You can use the very nice MFDataset feature in netCDF4 to treat a bunch of files as one aggregated file, without the need to use `ncrcat`. So you code would look like this:
```
from pylab import *
import netCDF4
f = netCDF4.MFDataset('/usgs/data2/rsignell/models/ncep/narr/air.2m.19??.nc')
# print variables
f.variable... |
How do I access embedded json objects in a Pandas DataFrame? | 18,665,284 | 8 | 2013-09-06T19:32:54Z | 18,666,142 | 15 | 2013-09-06T20:32:29Z | [
"python",
"json",
"mongodb",
"twitter",
"pandas"
] | **TL;DR If loaded fields in a Pandas DataFrame contain JSON documents themselves, how can they be worked with in a Pandas like fashion?**
Currently I'm directly dumping json/dictionary results from a Twitter library ([twython](https://github.com/ryanmcgrath/twython)) into a Mongo collection (called users here).
```
f... | One solution is just to smash it with the Series constructor:
```
In [1]: df = pd.DataFrame([[1, {'a': 2}], [2, {'a': 1, 'b': 3}]])
In [2]: df
Out[2]:
0 1
0 1 {u'a': 2}
1 2 {u'a': 1, u'b': 3}
In [3]: df[1].apply(pd.Series)
Out[3]:
a b
0 2 NaN
1 1 3
```
In some cases you'... |
Counting runs in a string | 18,665,563 | 8 | 2013-09-06T19:51:30Z | 18,665,581 | 18 | 2013-09-06T19:52:59Z | [
"python",
"string"
] | I have a string that looks like:
```
string = 'TTHHTHHTHHHHTTHHHTTT'
```
How can I count the number of runs in the string so that I get,
5 runs of T and 4 runs of H | You can use a combination of [`itertools.groupby`](https://docs.python.org/2/library/itertools.html#itertools.groupby) and [`collections.Counter`](https://docs.python.org/2/library/collections.html#collections.Counter):
```
>>> from itertools import groupby
>>> from collections import Counter
>>> strs = 'TTHHTHHTHHHHT... |
Filtering a list based on a list of booleans | 18,665,873 | 30 | 2013-09-06T20:12:29Z | 18,665,889 | 15 | 2013-09-06T20:13:32Z | [
"python",
"list",
"numpy"
] | I have a list of values which I need to filter given the values in a list of booleans:
```
list_a = [1, 2, 4, 6]
filter = [True, False, True, False]
```
I generate a new filtered list with the following line:
```
filtered_list = [i for indx,i in enumerate(list_a) if filter[indx] == True]
```
which results in:
```
... | Like so:
```
filtered_list = [i for (i, v) in zip(list_a, filter) if v]
```
Using `zip` is the 'pythonic' way to iterate over multiple sequences in parallel, without needing any indexing. Using itertools for such a simple case is a bit overkill ...
One thing you do in your example you should really stop doing is com... |
Filtering a list based on a list of booleans | 18,665,873 | 30 | 2013-09-06T20:12:29Z | 18,665,893 | 48 | 2013-09-06T20:13:44Z | [
"python",
"list",
"numpy"
] | I have a list of values which I need to filter given the values in a list of booleans:
```
list_a = [1, 2, 4, 6]
filter = [True, False, True, False]
```
I generate a new filtered list with the following line:
```
filtered_list = [i for indx,i in enumerate(list_a) if filter[indx] == True]
```
which results in:
```
... | You're looking for [`itertools.compress`](http://docs.python.org/3.1/library/itertools.html#itertools.compress):
```
>>> from itertools import compress
>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> list(compress(list_a, fil))
[1, 4]
```
## Timing comparisons(py3.x):
```
>>> list_a = [1, 2, 4, 6]... |
Filtering a list based on a list of booleans | 18,665,873 | 30 | 2013-09-06T20:12:29Z | 18,666,622 | 9 | 2013-09-06T21:08:03Z | [
"python",
"list",
"numpy"
] | I have a list of values which I need to filter given the values in a list of booleans:
```
list_a = [1, 2, 4, 6]
filter = [True, False, True, False]
```
I generate a new filtered list with the following line:
```
filtered_list = [i for indx,i in enumerate(list_a) if filter[indx] == True]
```
which results in:
```
... | With numpy:
```
In [128]: list_a = np.array([1, 2, 4, 6])
In [129]: filter = np.array([True, False, True, False])
In [130]: list_a[filter]
Out[130]: array([1, 4])
```
or see Alex Szatmary's answer if list\_a can be a numpy array but not filter
Numpy usually gives you a big speed boost as well
```
In [133]: list_a ... |
Downsample array in Python | 18,666,014 | 15 | 2013-09-06T20:21:50Z | 29,089,576 | 7 | 2015-03-17T00:54:35Z | [
"python",
"image-processing",
"numpy",
"scipy",
"gdal"
] | I have basic 2-D numpy arrays and I'd like to "downsample" them to a more coarse resolution. Is there a simple numpy or scipy module that can easily do this? I should also note that this array is being displayed geographically via Basemap modules.
SAMPLE:
 | 18,666,885 | 26 | 2013-09-06T21:31:37Z | 33,497,841 | 21 | 2015-11-03T11:20:31Z | [
"python",
"pycharm",
"docstring",
"doctest"
] | Does PyCharm 2.7 (or will PyCharm 3) have support for custom docstring and doctest stubs? If so, how does one go about writing this specific type of custom extension?
My current project has standardized on using the Google Python Style Guide (<http://google-styleguide.googlecode.com/svn/trunk/pyguide.html>). I love Py... | With PyCharm 5.0 we finally got to select [Google and NumPy Style Python Docstrings](https://www.jetbrains.com/pycharm/help/python-integrated-tools.html) templates.
It is also mentioned in the [whatsnew](https://www.jetbrains.com/pycharm/whatsnew/) section for PyCharm 5.0.
How to change the Docstring Format:
> File ... |
How can I check if a string only contains letters in Python? | 18,667,410 | 14 | 2013-09-06T22:17:48Z | 18,667,451 | 8 | 2013-09-06T22:21:28Z | [
"python",
"string",
"condition"
] | I'm trying to check if a string only contains letters, not digits or symbols.
For example:
```
>>> only_letters("hello")
True
>>> only_letters("he7lo")
False
``` | The `str.isalpha()` function works. ie.
```
if my_string.isalpha():
print('it is letters')
``` |
How can I check if a string only contains letters in Python? | 18,667,410 | 14 | 2013-09-06T22:17:48Z | 18,667,460 | 31 | 2013-09-06T22:22:09Z | [
"python",
"string",
"condition"
] | I'm trying to check if a string only contains letters, not digits or symbols.
For example:
```
>>> only_letters("hello")
True
>>> only_letters("he7lo")
False
``` | Simple:
```
if string.isalpha():
print("It's all letters")
```
[`str.isalpha()`](http://docs.python.org/2/library/stdtypes.html#str.isalpha) is only true if *all* characters in the string are letters:
> Return true if all characters in the string are alphabetic and there is at least one character, false otherwis... |
xcrun/lipo freezes with OS X Mavericks and XCode 4.x | 18,667,916 | 25 | 2013-09-06T23:12:06Z | 19,670,597 | 50 | 2013-10-29T22:46:36Z | [
"python",
"xcode",
"psycopg2",
"osx-mavericks",
"lipo"
] | Been trying to install psycopg2 with either easy\_install or pip, and the terminal gets stuck in a loop between xcrun and lipo.
```
sidwyn$ sudo easy_install psycopg2
Searching for psycopg2
Reading https://pypi.python.org/simple/psycopg2/
Reading http://initd.org/psycopg/
Reading http://initd.org/projects/psycopg2
Bes... | A more appropriate fix is:
```
ln /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/lipo /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/lipo
xcrun -k lipo
```
Why: xfx's fix will likely break being able to use xcode-select to choose your t... |
xcrun/lipo freezes with OS X Mavericks and XCode 4.x | 18,667,916 | 25 | 2013-09-06T23:12:06Z | 20,070,604 | 12 | 2013-11-19T11:42:05Z | [
"python",
"xcode",
"psycopg2",
"osx-mavericks",
"lipo"
] | Been trying to install psycopg2 with either easy\_install or pip, and the terminal gets stuck in a loop between xcrun and lipo.
```
sidwyn$ sudo easy_install psycopg2
Searching for psycopg2
Reading https://pypi.python.org/simple/psycopg2/
Reading http://initd.org/psycopg/
Reading http://initd.org/projects/psycopg2
Bes... | This one works for me:
```
xcode-select -âinstall
sudo mv /usr/bin/lipo /usr/bin/lipo.orig
sudo ln -s /Library/Developer/CommandLineTools/usr/bin/lipo /usr/bin
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.