title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Removing white space and colon | 39,359,816 | <p>I have a file with a bunch of numbers that have white spaces and colons and I am trying to remove them. As I have seen on this forum the function <code>line.strip.split()</code> works well to achieve this. Is there a way of removing the white space and colon all in one go? Using the method posted by Lorenzo I have t... | 0 | 2016-09-07T00:58:10Z | 39,360,725 | <p>You did not provide an example of what your input file looks like so we can only speculate what solution you need. I'm going to suppose that you need to extract integers from your input text file and print their values.</p>
<p>Here's how I would do it:</p>
<ul>
<li>Instead of trying to eliminate whitespace charact... | 1 | 2016-09-07T03:21:25Z | [
"python",
"numpy"
] |
how to convert string to numeric in python | 39,359,843 | <p>I would like to convert string (%) to float.but my method didnt work well.
the result slightly differ from correct number.
for example,</p>
<pre><code>a=pd.Series(data=["0.1%","0.2%"])
0 0.1%
1 0.2%
dtype: object
</code></pre>
<p>first, I strip "%"</p>
<pre><code>a.str.rstrip("%")
0 0.1
1 0.2
dtype:... | 2 | 2016-09-07T01:02:57Z | 39,359,882 | <p>Many rational numbers can't be represented exactly as a floating-point number. In particular, any number that has to have a five as a factor in the denominator, like 1/(2*5), can't be represented exactly. There isn't much you can do about this: either round the displayed number so it looks right, or use an infinite-... | 2 | 2016-09-07T01:10:14Z | [
"python",
"pandas",
"numpy",
"floating-point"
] |
how to convert string to numeric in python | 39,359,843 | <p>I would like to convert string (%) to float.but my method didnt work well.
the result slightly differ from correct number.
for example,</p>
<pre><code>a=pd.Series(data=["0.1%","0.2%"])
0 0.1%
1 0.2%
dtype: object
</code></pre>
<p>first, I strip "%"</p>
<pre><code>a.str.rstrip("%")
0 0.1
1 0.2
dtype:... | 2 | 2016-09-07T01:02:57Z | 39,367,499 | <p>As a folow-up to the suggestion by @D-Von, the following python packages can be useful to you: <a href="https://docs.python.org/3/library/decimal.html" rel="nofollow">decimal</a> and <a href="https://docs.python.org/3/library/fractions.html" rel="nofollow">fractions</a></p>
<p>Then you can do some things like:</p>
... | 1 | 2016-09-07T10:32:12Z | [
"python",
"pandas",
"numpy",
"floating-point"
] |
how to connect an app to a database with python? | 39,359,845 | <p>I'm new to python, so I want to know how to store the data in a database! </p>
<p>For a sample example, I want to store informations about users :</p>
<pre><code>ent1 = input('Enter your name: ')
ent2 = input('Enter your adress: ')
ent3 = int(input('Enter your number phone: '))
</code></pre>
<p>The question is ho... | 0 | 2016-09-07T01:03:32Z | 39,359,941 | <p>Use <code>sqllite3</code> library to perform SQL <code>insert</code> query to insert data into database. For example</p>
<pre><code>import sqlite3
conn = sqlite3.connect('user.db')
## Create table. Skip if table already exists
conn.execute('''CREATE TABLE IF NOT EXISTS users
(name TEXT NOT NULL,
a... | 1 | 2016-09-07T01:19:34Z | [
"python",
"database",
"sqlite3"
] |
how to connect an app to a database with python? | 39,359,845 | <p>I'm new to python, so I want to know how to store the data in a database! </p>
<p>For a sample example, I want to store informations about users :</p>
<pre><code>ent1 = input('Enter your name: ')
ent2 = input('Enter your adress: ')
ent3 = int(input('Enter your number phone: '))
</code></pre>
<p>The question is ho... | 0 | 2016-09-07T01:03:32Z | 39,377,519 | <p>You can emulate a database with Python objects.</p>
<p>Create a <code>dict,</code> and store all your data therein.</p>
<p>Then, serialise (<a href="https://docs.python.org/3/library/pickle.html" rel="nofollow"><code>pickle</code></a>) the data to disk (with <code>pickle.dump</code>) and next time you need to acce... | 0 | 2016-09-07T19:14:47Z | [
"python",
"database",
"sqlite3"
] |
Will the file be closed after returning from function? | 39,359,871 | <p>Here is a python function:</p>
<pre><code>def read_data(filename):
f = zipfile.ZipFile(filename)
for name in f.namelist():
return tf.compat.as_str(f.read(name))
f.close()
</code></pre>
<p>Will the file be closed? There is no error when calling it.</p>
| 0 | 2016-09-07T01:08:15Z | 39,359,994 | <p>The file won't be closed. If you want to close the file, you can write it like:</p>
<pre><code>def read_data(filename):
with zipfile.ZipFile(filename) as f:
for name in f.namelist():
return tf.compat.as_str(f.read(name))
</code></pre>
<p>Testing your code:
<a href="http://i.stack.imgur.com/... | 1 | 2016-09-07T01:27:34Z | [
"python",
"file",
"zipfile"
] |
How do I have multiple windows in Kivy? | 39,359,950 | <p>I am trying to open one GUI from a completely different GUI. I am developing on a desktop and the windows have different sizes from each other. I looked at screen manager but I feel as if there is an easier way to do this.</p>
<p>Thanks in advance!</p>
| 0 | 2016-09-07T01:21:44Z | 39,360,654 | <p>It's possible, but kinda inconvenient. The issue is that kivy supports only one window per app, so you need to work around it somehow. I personally just use multiple *Layouts (which are different GUIs with different functions) in a single window, showing and hiding them as necessary. Obviously this approach has its ... | 0 | 2016-09-07T03:09:20Z | [
"python",
"user-interface",
"kivy",
"kivy-language"
] |
In scrapy, I use XPATH to pick HTML and got many unnecessary "" and ,? | 39,360,013 | <p>I faced with a problem with parsing <a href="http://so.gushiwen.org/view_20788.aspx" rel="nofollow">http://so.gushiwen.org/view_20788.aspx</a></p>
<p><img src="http://i.stack.imgur.com/W3jfH.png" alt="Inspector"></p>
<p>This is what I want:</p>
<pre><code>"detail_text": ["
寥è½å¤è¡å®«ï¼å®«è±å¯å¯çº¢ã... | 2 | 2016-09-07T01:30:14Z | 39,360,458 | <p>You can add predicate <code>[normalize-space()]</code> to avoid picking up empty text nodes i.e those containing whitespaces only :</p>
<pre><code>item['detail_text'] = site.xpath('div[@class="son2"]/text()[normalize-space()]').extract()
</code></pre>
| 3 | 2016-09-07T02:41:13Z | [
"python",
"xpath",
"scrapy"
] |
How to load multiple csv into pandas without concatenate? | 39,360,043 | <p>I would like to apply two separate graphs to each text file in a folder with subdirectories, however I wouldn't want them to be joined into one data frame.
I am currently only able to load one file into pandas at a time. If I put the root directory, I get an error that the File doesn't exist.</p>
<pre><code>data = ... | 0 | 2016-09-07T01:35:58Z | 39,360,104 | <p>Just do two read statements into two variables and go from there:</p>
<pre><code>data1 = pd.read_csv(r'/Users/work/DexterStudio/DataFolder/file1', sep=" ", header = None, na_values='NaN')
data2 = pd.read_csv(r'/Users/work/DexterStudio/DataFolder/file2', sep=" ", header = None, na_values='NaN')
</code></pre>
<p>Not... | 0 | 2016-09-07T01:47:04Z | [
"python",
"csv",
"pandas"
] |
What is the fast way to get a list with the corresponding serial number with pandas? | 39,360,107 | <p>I have to drop some columns, sometimes the columns name is hart to type, so I want to get a list or tuple or array with the corresponding serial number, then I can drop them with <code>df1.drop(df1.columns[[0, 1, 3]], axis=1)</code>.</p>
<p>What is the fast way with pandas to do it like this?</p>
<pre><code>In [2]... | 0 | 2016-09-07T01:47:33Z | 39,788,263 | <p>Finally, I found a way to do it fast and easy:</p>
<pre><code>for i, element in enumerate(df.columns):
print(i, element)
</code></pre>
| 0 | 2016-09-30T09:33:59Z | [
"python",
"pandas"
] |
How do I get astropy Column to store string of any length? | 39,360,168 | <p>I'm generating a few catalogues, and would like to have a column for comments. For some reason, when I generate the column and try to store a comment it only takes the first character. </p>
<pre><code>from astropy.table import Column
C1 = Column(['']*12, name = 'ID')
C1[4] = 'test comment'
</code></pre>
<p>Then ... | 0 | 2016-09-07T01:56:43Z | 39,363,664 | <p>For this use case I usually first collect the data as a Python list of strings and then call the <code>astropy.table.Column</code> constructor.</p>
<pre><code>>>> from astropy.table import Column
>>> data = ['short', 'something longer']
>>> Column(data=data, name='spam')
<Column name='... | 0 | 2016-09-07T07:23:35Z | [
"python",
"string",
"ascii",
"astropy"
] |
Corrupted GZIP file downloaded from Google Cloud Storage | 39,360,222 | <p>When I download a GZIP file stored in a bucket in Google Cloud Storage from the Storage platform web UI, everything goes well and I can unzip the file without any problem.</p>
<p>However, when I use googleapiclient with Python in order to download the file, I cannot unzip it. 7-Zip says that the file is broken.
My ... | 0 | 2016-09-07T02:05:57Z | 39,364,805 | <p>I changed the output file to binary and it solved it:</p>
<pre><code>with open(out_file, 'wb') as f:
</code></pre>
<p>instead of:</p>
<pre><code>with open(out_file, 'w') as f:
</code></pre>
| 1 | 2016-09-07T08:25:10Z | [
"python",
"gzip",
"google-cloud-storage"
] |
Access files relative to imported python module | 39,360,242 | <p>Preliminary:</p>
<p>I have Anaconda 3 on Windows 10, and a folder, <code>folder_default</code>, that I have put on the Python path. I'm not actually sure whether that's the right terminology, so to be clear: regardless to where my Python script is, if I have a line of code that says <code>import myFile</code>, that... | 0 | 2016-09-07T02:08:13Z | 39,360,322 | <p>You can get the path to current module using the <code>getfile</code> method of <code>inspect</code> module as <code>inspect.getfile(inspect.currentframe())</code>.
For example:</p>
<pre><code># File : my_misc.py
import os, inspect
module_dir_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentfr... | 0 | 2016-09-07T02:20:29Z | [
"python",
"import",
"relative-path",
"python-import"
] |
How to specify the level of json.loads()? | 39,360,261 | <p>I have a JSON string to be loaded:</p>
<pre><code>{"a": 1, "b": {"c": 123} }
</code></pre>
<p>If I use <code>json.loads</code>, it will load <code>{"c": 123}</code> as a <code>dict</code>. However, I don't want that to happen.</p>
<p>I want to be able to access the string directly, without interpreting the intern... | -1 | 2016-09-07T02:10:15Z | 39,360,531 | <p>You have one solution using json.loads object_hook parameter.</p>
<p>object_hook is an optional function that will be called with the result of any object literal decoded (a dict). The return value of object_hook will be used instead of the dict. This feature can be used to implement custom decoders (e.g. JSON-RPC ... | -1 | 2016-09-07T02:51:56Z | [
"python",
"json"
] |
How to specify the level of json.loads()? | 39,360,261 | <p>I have a JSON string to be loaded:</p>
<pre><code>{"a": 1, "b": {"c": 123} }
</code></pre>
<p>If I use <code>json.loads</code>, it will load <code>{"c": 123}</code> as a <code>dict</code>. However, I don't want that to happen.</p>
<p>I want to be able to access the string directly, without interpreting the intern... | -1 | 2016-09-07T02:10:15Z | 39,362,865 | <p>To directly answer your question: no, <code>json.loads</code> doesn't support this.</p>
<p>I've included two ways to accomplish your goal below. The first is very robust and relies on the lexer from <a href="https://pypi.python.org/pypi/ijson/" rel="nofollow"><code>ijson</code></a>. The second method is much less r... | 0 | 2016-09-07T06:44:26Z | [
"python",
"json"
] |
Regex for format ( HHh MMs SSs ) with optional hours | 39,360,329 | <p>I am struggling to get a regex working for the below format. Pointers appeciated</p>
<pre><code>( 43m 12s )
( 13m 11s )
( 11h 43m 12s )
( 1h 43m 12s )
</code></pre>
<p>Edit:</p>
<p>The above examples are part of longer strings.</p>
<p>Edit2:</p>
<p>This is what I have now:</p>
<pre><code> \s\(\s\d{1,2}[a-z]\s.... | 0 | 2016-09-07T02:21:17Z | 39,360,354 | <p>You don't necessarily need to approach it with regular expressions.</p>
<p>Here is an another option - use a <a href="https://labix.org/python-dateutil" rel="nofollow"><code>dateutil</code></a> datetime parser:</p>
<pre><code>>>> from dateutil.parser import parse
>>> l = ["43m 12s", "13m 11s", "1... | 2 | 2016-09-07T02:25:16Z | [
"python",
"regex"
] |
Regex for format ( HHh MMs SSs ) with optional hours | 39,360,329 | <p>I am struggling to get a regex working for the below format. Pointers appeciated</p>
<pre><code>( 43m 12s )
( 13m 11s )
( 11h 43m 12s )
( 1h 43m 12s )
</code></pre>
<p>Edit:</p>
<p>The above examples are part of longer strings.</p>
<p>Edit2:</p>
<p>This is what I have now:</p>
<pre><code> \s\(\s\d{1,2}[a-z]\s.... | 0 | 2016-09-07T02:21:17Z | 39,361,962 | <p>If you don't need to capture hours minutes and seconds, this will work: <code>\(\s?(?:\d{1,2}\w )+\s?\)</code> you can see it working here: <a href="https://regex101.com/r/yC8iH6/1" rel="nofollow">https://regex101.com/r/yC8iH6/1</a></p>
<p><strong>[EDIT]</strong>: Add capturing if needed:</p>
<p>If you need to cap... | 1 | 2016-09-07T05:41:59Z | [
"python",
"regex"
] |
How do I use raw input inside a function | 39,360,336 | <p>I have scoured the forum trying to find a good way to make a function that takes raw input and uses it.</p>
<pre><code>print "Roll for Agility"
def Rolling(a, b, value):
in1 = raw_input()
if in1 == 'roll':
irand = randrange(a, b)
elif in1 == 'Roll':
irand = randrange(a, b)
els... | -3 | 2016-09-07T02:22:45Z | 39,360,487 | <p>The code has some typos. Error message <code>NameError: name 'value' is not defined</code> is generated because that statement has been mistakenly put outside the <code>Rolling</code> function body where <code>value</code> is not defined.</p>
<p>Corrected code should look like:</p>
<pre><code>#Rolling for Agility
... | 2 | 2016-09-07T02:44:36Z | [
"python"
] |
Data won't load from text file - ValueError: not enough values to unpack (expected 3, got 1) | 39,360,345 | <p>Can't get this text data to load:</p>
<pre class="lang-none prettyprint-override"><code>Al,95191,619851,
Joe,651651,616951,
</code></pre>
<p>The load module:</p>
<pre><code>def loadPlayers():
Roster = {}
filename = input("Filename to load: ")
inFile = open(filename, "rt")
print("Loading data...")
... | 0 | 2016-09-07T02:23:58Z | 39,360,840 | <p>You can improve the script a little to parse better some cases of extra data not formated as suspected.</p>
<pre><code>def loadPlayers():
Roster = {}
filename = input("Filename to load: ")
inFile = open(filename, "rt")
print("Loading data...")
while True:
inLine = inFile.readline()
... | 0 | 2016-09-07T03:36:28Z | [
"python"
] |
How to aggregate values of pandas series | 39,360,479 | <h3>Data manipulation using pandas</h3>
<p>Anyone having bright ways to manipulate the values of concatenated pandas series to find total counts? </p>
<hr>
<p>Current data (type: <code>pandas.core.series.Series</code>)
FYI, this data is generated by using 'groupby' function from the raw data.</p>
<pre><code>date ... | 1 | 2016-09-07T02:43:41Z | 39,361,527 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.cumsum.html" rel="nofollow"><code>DataFrameGroupBy.cumsum</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.groupby.html" rel="nofollow"><code>groupby</co... | 2 | 2016-09-07T05:01:38Z | [
"python",
"pandas",
"series",
"multi-index",
"cumsum"
] |
Trying to scrape this website using python but unable to get the required data | 39,360,498 | <p>I am trying to get the company names in this website <a href="https://siftery.com/microsoft-outlook" rel="nofollow">https://siftery.com/microsoft-outlook</a>
Basically it lists some companies that use Microsoft Outlook.
I used BeautifulSoup,requests,urllib and urllib2 but I still am not getting the names of the comp... | -1 | 2016-09-07T02:46:49Z | 39,360,846 | <p>That site loads the information using javascript that means that when you do the requests, the DOM is rendered without the information because it is loaded asynchronously, for sites like that you should use selenium.</p>
<p>Note:
Before you build a scraper you should look if the site has an api or end-points with C... | 1 | 2016-09-07T03:36:57Z | [
"python",
"web-scraping"
] |
Trying to scrape this website using python but unable to get the required data | 39,360,498 | <p>I am trying to get the company names in this website <a href="https://siftery.com/microsoft-outlook" rel="nofollow">https://siftery.com/microsoft-outlook</a>
Basically it lists some companies that use Microsoft Outlook.
I used BeautifulSoup,requests,urllib and urllib2 but I still am not getting the names of the comp... | -1 | 2016-09-07T02:46:49Z | 39,361,131 | <p>The data is available directly as JSON. You can use requests to get it like this:</p>
<pre><code>import requests
r = requests.post('https://siftery.com/product-json/microsoft-outlook')
data = r.json()['content']
companies = data['companies']
for company in companies:
print(companies[company]['name'])
</code></... | 0 | 2016-09-07T04:19:31Z | [
"python",
"web-scraping"
] |
Using zipped queryset many times in template | 39,360,519 | <p>I have a model that is only a string :</p>
<pre><code>class Data(models.Model):
string = models.CharField(max_length=200);
</code></pre>
<p>There are <strong>2</strong> registered instances of the model in my database.</p>
<p>It is rendered by this view, which zips the queryset which another list: </p>
<pre>... | 0 | 2016-09-07T02:50:36Z | 39,360,591 | <p>In Pythno 3, <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow"><code>zip</code></a> will give you an iterator, meaning it will be consumed on the first loop and therefore not print anything on the second loop.</p>
<p>You can fix this by casting the iterator to a list, replacing <code>zip... | 2 | 2016-09-07T02:59:54Z | [
"python",
"django"
] |
Identification of rows containing column median in numpy matrix of cum percentiles | 39,360,535 | <p>Consider the matrix <code>quantiles</code> that's a subset <code>[:8,:3,0]</code> of a 3D matrix with shape <code>(10,355,8)</code>. </p>
<pre><code>quantiles = np.array([
[ 1. , 1. , 1. ],
[ 0.63763978, 0.61848863, 0.75348137],
[ 0.43439645, 0.42485407, 0.5341457 ],
... | 1 | 2016-09-07T02:52:15Z | 39,360,536 | <p>Bumping into the old <code>mask</code> operation in <code>Numpy</code>, I found the following solution</p>
<pre><code>#mask quantities that are less than .5
masked_quantiles = ma.masked_where(quantiles<.5,quantiles)
#identify the minimum in column of the masked array
median_idx = np.where(masked_quantiles == ma... | 1 | 2016-09-07T02:52:15Z | [
"python",
"arrays",
"numpy",
"boolean",
"median"
] |
Identification of rows containing column median in numpy matrix of cum percentiles | 39,360,535 | <p>Consider the matrix <code>quantiles</code> that's a subset <code>[:8,:3,0]</code> of a 3D matrix with shape <code>(10,355,8)</code>. </p>
<pre><code>quantiles = np.array([
[ 1. , 1. , 1. ],
[ 0.63763978, 0.61848863, 0.75348137],
[ 0.43439645, 0.42485407, 0.5341457 ],
... | 1 | 2016-09-07T02:52:15Z | 39,361,277 | <h2>Approach #1</h2>
<p>Here's an approach using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> and some masking trick -</p>
<pre><code># Mask of quantiles lesser than or equal to 0.5 to select the invalid ones
mask1 = quantiles<=0.5
# Since we... | 1 | 2016-09-07T04:35:46Z | [
"python",
"arrays",
"numpy",
"boolean",
"median"
] |
matplotlib multiple values under cursor | 39,360,740 | <p>This question is very similar to those answered here,</p>
<p><a href="http://stackoverflow.com/questions/14754931/matplotlib-values-under-cursor">matplotlib values under cursor</a></p>
<p><a href="http://stackoverflow.com/questions/14349289/in-a-matplotlib-figure-window-with-imshow-how-can-i-remove-hide-or-redefin... | 0 | 2016-09-07T03:23:27Z | 39,364,042 | <p>You could probably build on something like this example. It doesn't display the information inside the figure (for now only using a <code>print()</code> statement), but it demonstrates a simple method of capturing clicks on <code>scatter</code> points and showing information for those points:</p>
<pre><code>import ... | 1 | 2016-09-07T07:44:07Z | [
"python",
"matplotlib"
] |
Matching the structure of a list? | 39,360,926 | <p>For example:</p>
<pre><code>A=[1,[2,3],[4,[5,6]],7]
B=[2,3,4,5,6,7,8]
</code></pre>
<p>How can I get <code>[2,[3,4],[5,[6,7]],8]</code>?</p>
| 0 | 2016-09-07T03:49:45Z | 39,361,013 | <p>You could use a pretty simple recursive function:</p>
<pre><code>def match(struct, source):
try:
return [match(i, source) for i in struct]
except TypeError:
return next(source)
A=[1,[2,3],[4,[5,6]],7]
B=[2,3,4,5,6,7,8]
match(A, iter(B))
# [2, [3, 4], [5, [6, 7]], 8]
</code></pre>
<p>Here i... | 9 | 2016-09-07T04:03:10Z | [
"python",
"list"
] |
Xlsxwriter Excel Chart Border | 39,361,072 | <p>Is there a way to remove an Excel chart border using Xlsxwriter? I need my chart to blend in to an Excel sheet without the grid lines showing and I haven't had any luck so far.</p>
| 1 | 2016-09-07T04:10:06Z | 39,367,342 | <p>You can use the <a href="http://xlsxwriter.readthedocs.io/chart.html#chart-set-chartarea" rel="nofollow"><code>set_chartarea()</code></a> method to set the border for the chart object:</p>
<pre><code>import xlsxwriter
workbook = xlsxwriter.Workbook('chart.xlsx')
worksheet = workbook.add_worksheet()
worksheet.writ... | 3 | 2016-09-07T10:25:15Z | [
"python",
"xlsxwriter"
] |
Remove numbers from a string with a letter in front | 39,361,073 | <pre><code>combined['Cabin'] = combined['Cabin'].map(lambda c : c[0])
</code></pre>
<p>I'm following a tutorial, except this line throws the error <code>TypeError: 'float' object has no attribute '__getitem__'</code></p>
<p>Anyway to fix this? </p>
<p>My column's data looks like
<a href="http://i.stack.imgur.com/dYH... | 1 | 2016-09-07T04:10:26Z | 39,361,138 | <p>I suspect the problem is that your <code>X</code> isn't what you think it is. If it's a float, for example, 123.45:</p>
<p><code>>>> 123.45['Y']</code><br>
<code>Traceback (most recent call last):</code><br>
<code>File "<stdin>", line 1, in <module></code><br>
<code>TypeError: 'float' object ha... | 0 | 2016-09-07T04:20:53Z | [
"python"
] |
Remove numbers from a string with a letter in front | 39,361,073 | <pre><code>combined['Cabin'] = combined['Cabin'].map(lambda c : c[0])
</code></pre>
<p>I'm following a tutorial, except this line throws the error <code>TypeError: 'float' object has no attribute '__getitem__'</code></p>
<p>Anyway to fix this? </p>
<p>My column's data looks like
<a href="http://i.stack.imgur.com/dYH... | 1 | 2016-09-07T04:10:26Z | 39,361,338 | <p>I am not sure what is your concern. Is this what you are trying to do?</p>
<pre><code>import pandas as pd
X = pd.DataFrame({'Y': ["NAN", "C85", "NAN", "C123", "NAN"]})
print X
Y
0 NAN
1 C85
2 NAN
3 C123
4 NAN
lambda_f = lambda c: c[0]
X['Y'] = map(lambda_f, X['Y'])
print X
Y
0 N
1 C
2 N
3 C... | 0 | 2016-09-07T04:41:14Z | [
"python"
] |
Python calling Matlab User Function from any directory using matlab module | 39,361,081 | <p><strong>Background</strong></p>
<p>I'm working with Python 2.7.6 and Matlab 2016a and have installed the official MathWorks Python to Matlab bridge. It is the matlab and matlab.engine modules. All of the other questions I've seen on SO regarding matlab/python use third-party wrappers that seem out of date. I have... | 0 | 2016-09-07T04:12:16Z | 39,373,010 | <p>Due to the comment by @excaza, I solved this by setting the MATLABPATH environment variable to point to the folder containing my *.m files.</p>
<p><a href="http://www.mathworks.com/help/matlab/matlab_env/add-folders-to-search-path-upon-startup-on-unix-or-macintosh.html" rel="nofollow">http://www.mathworks.com/help/... | 0 | 2016-09-07T14:45:11Z | [
"python",
"matlab",
"path"
] |
Python detect character surrounded by spaces | 39,361,214 | <p>Anyone know how I can find the character in the center that is surrounded by spaces?</p>
<p><code>1 + 1</code></p>
<p>I'd like to be able to separate the <code>+</code> in the middle to use in a if/else statement.</p>
<p>Sorry if I'm not too clear, I'm a Python beginner.</p>
| 0 | 2016-09-07T04:29:01Z | 39,361,262 | <p>I think you are looking for something like the <code>split()</code> method which will split on white space by default.</p>
<p>Suppose we have a string <code>s</code></p>
<pre><code>s = "1 + 1"
chunks = s.split()
print(chunks[1]) # Will print '+'
</code></pre>
| 5 | 2016-09-07T04:34:37Z | [
"python",
"python-3.x"
] |
Python detect character surrounded by spaces | 39,361,214 | <p>Anyone know how I can find the character in the center that is surrounded by spaces?</p>
<p><code>1 + 1</code></p>
<p>I'd like to be able to separate the <code>+</code> in the middle to use in a if/else statement.</p>
<p>Sorry if I'm not too clear, I'm a Python beginner.</p>
| 0 | 2016-09-07T04:29:01Z | 39,361,275 | <p>You can use regex:</p>
<pre><code>s="1 + 1"
a=re.compile(r' (?P<sym>.) ')
a.search(s).group('sym')
</code></pre>
| 0 | 2016-09-07T04:35:36Z | [
"python",
"python-3.x"
] |
Python detect character surrounded by spaces | 39,361,214 | <p>Anyone know how I can find the character in the center that is surrounded by spaces?</p>
<p><code>1 + 1</code></p>
<p>I'd like to be able to separate the <code>+</code> in the middle to use in a if/else statement.</p>
<p>Sorry if I'm not too clear, I'm a Python beginner.</p>
| 0 | 2016-09-07T04:29:01Z | 39,361,292 | <p>This regular expression will detect a single character surrounded by spaces, if the character is a plus or minus or mult or div sign: <code>r' ([+-*/]) '</code>. Note the spaces inside the apostrophes. The parentheses "capture" the character in the middle. If you need to recognize a different set of characters, chan... | 0 | 2016-09-07T04:37:12Z | [
"python",
"python-3.x"
] |
Python detect character surrounded by spaces | 39,361,214 | <p>Anyone know how I can find the character in the center that is surrounded by spaces?</p>
<p><code>1 + 1</code></p>
<p>I'd like to be able to separate the <code>+</code> in the middle to use in a if/else statement.</p>
<p>Sorry if I'm not too clear, I'm a Python beginner.</p>
| 0 | 2016-09-07T04:29:01Z | 39,361,302 | <p>Not knowing how many spaces separate your central character, then I'd use the following:</p>
<pre><code>s = '1 + 1'
middle = filter(None, s.split())[1]
print middle # +
</code></pre>
<p>The <code>split</code> works as in the solution provided by Zac, but if there are more than a single space, then the returned ... | 0 | 2016-09-07T04:38:13Z | [
"python",
"python-3.x"
] |
Python detect character surrounded by spaces | 39,361,214 | <p>Anyone know how I can find the character in the center that is surrounded by spaces?</p>
<p><code>1 + 1</code></p>
<p>I'd like to be able to separate the <code>+</code> in the middle to use in a if/else statement.</p>
<p>Sorry if I'm not too clear, I'm a Python beginner.</p>
| 0 | 2016-09-07T04:29:01Z | 39,361,313 | <pre><code>import re
def find_between(string, start_=' ', end_=' '):
re_str = r'{}([-+*/%^]){}'.format(start_, end_)
try:
return re.search(re_str, string).group(1)
except AttributeError:
return None
print(find_between('9 * 5', ' ', ' '))
</code></pre>
| 0 | 2016-09-07T04:38:55Z | [
"python",
"python-3.x"
] |
what's the usage of __traceback_hide__ | 39,361,321 | <p>I have seen this line of code in some functions</p>
<pre><code>__traceback_hide__ = True
</code></pre>
<p>What does it do? It seems like its trying to suppress the error traceback. In what situations should the traceback be hidden?</p>
| 0 | 2016-09-07T04:39:52Z | 39,361,498 | <p>Looks like this is <a href="https://github.com/jazzband/django-debug-toolbar/issues/160" rel="nofollow">mostly a convenience for web frameworks</a> (Sentry, werkzeug, <a href="http://pythonpaste.org/modules/exceptions.html#paste.exceptions.collector.ExceptionCollector" rel="nofollow">Paste</a>, Django) to make it so... | 0 | 2016-09-07T04:58:12Z | [
"python"
] |
what's the usage of __traceback_hide__ | 39,361,321 | <p>I have seen this line of code in some functions</p>
<pre><code>__traceback_hide__ = True
</code></pre>
<p>What does it do? It seems like its trying to suppress the error traceback. In what situations should the traceback be hidden?</p>
| 0 | 2016-09-07T04:39:52Z | 39,361,531 | <p>Googling for "python __traceback_hide__", I learn that it's intended to let a complicated framework hide part of its inner workings by suppressing some stack frames from the exception printout, so that the user does not become confused lots of irrelevant output.</p>
| 0 | 2016-09-07T05:01:44Z | [
"python"
] |
what's the usage of __traceback_hide__ | 39,361,321 | <p>I have seen this line of code in some functions</p>
<pre><code>__traceback_hide__ = True
</code></pre>
<p>What does it do? It seems like its trying to suppress the error traceback. In what situations should the traceback be hidden?</p>
| 0 | 2016-09-07T04:39:52Z | 39,361,573 | <p><code>__tracebackhide__</code> can be set to hide a function from the traceback when using PyTest. <code>__traceback_hide__</code> appears to be used in the Python Paste package for the same purpose.</p>
<p>Here's what the <a href="http://pythonpaste.org/modules/exceptions.html#module-paste.exceptions.collector" re... | 1 | 2016-09-07T05:05:15Z | [
"python"
] |
Broadcast an operation along specific axis in python | 39,361,341 | <p>In python, suppose I have a square (numpy) matrix <strong>X</strong>, of size <em>n x n</em> and I have a numpy vector <strong>a</strong> of size <em>n</em>. </p>
<p>Very simply, I want to perform a broadcasting subtraction of <strong>X - a</strong>, but I want to be able to specify along which dimension, so that I... | 1 | 2016-09-07T04:41:31Z | 39,361,699 | <p>Let's generate arrays with random elems</p>
<p>Inputs :</p>
<pre><code>In [62]: X
Out[62]:
array([[ 0.32322974, 0.50491961, 0.40854442, 0.36908488],
[ 0.58840196, 0.1696713 , 0.75428203, 0.01445901],
[ 0.27728281, 0.33722084, 0.64187916, 0.51361972],
[ 0.39151808, 0.6883594 , 0.938... | 1 | 2016-09-07T05:18:55Z | [
"python",
"arrays",
"numpy",
"matrix",
"numpy-broadcasting"
] |
Broadcast an operation along specific axis in python | 39,361,341 | <p>In python, suppose I have a square (numpy) matrix <strong>X</strong>, of size <em>n x n</em> and I have a numpy vector <strong>a</strong> of size <em>n</em>. </p>
<p>Very simply, I want to perform a broadcasting subtraction of <strong>X - a</strong>, but I want to be able to specify along which dimension, so that I... | 1 | 2016-09-07T04:41:31Z | 39,363,367 | <p>Start with 2 dimensions that are different (in label at least)</p>
<ul>
<li><code>X</code> shape <code>(n,m)</code></li>
<li><code>a</code> shape <code>(n,)</code></li>
<li><code>b</code> shape <code>(m,)</code></li>
</ul>
<p>The ways to combine these are:</p>
<pre><code>(n,m)-(n,) => (n,m)-(n,1) => (n,m)
X... | 1 | 2016-09-07T07:09:17Z | [
"python",
"arrays",
"numpy",
"matrix",
"numpy-broadcasting"
] |
How to create a list from another list using specific criteria in Python? | 39,361,381 | <p>How can I create a list from another list using python?
If I have a list:</p>
<pre><code>input = ['a/b', 'g', 'c/d', 'h', 'e/f']
</code></pre>
<p>How can I create the list of only those letters that follow slash "/" i.e.</p>
<pre><code>desired_output = ['b','d','f']
</code></pre>
<p>A code would be very helpful.... | 5 | 2016-09-07T04:45:45Z | 39,361,427 | <p>You probably have this input.You can get by simple list comprehension.</p>
<pre><code>input = ["a/b", "g", "c/d", "h", "e/f"]
print [i.split("/")[1] for i in input if i.find("/")==1 ]
</code></pre>
<p>or </p>
<pre><code>print [i.split("/")[1] for i in input if "/" in i ]
</code></pre>
<blockquote>
<p>Output: [... | 7 | 2016-09-07T04:50:52Z | [
"python",
"list"
] |
How to create a list from another list using specific criteria in Python? | 39,361,381 | <p>How can I create a list from another list using python?
If I have a list:</p>
<pre><code>input = ['a/b', 'g', 'c/d', 'h', 'e/f']
</code></pre>
<p>How can I create the list of only those letters that follow slash "/" i.e.</p>
<pre><code>desired_output = ['b','d','f']
</code></pre>
<p>A code would be very helpful.... | 5 | 2016-09-07T04:45:45Z | 39,361,436 | <p>If you fix your list by having all strings encapsulated by "", you can then use this to get what you want.</p>
<pre><code>input = ["a/b", "g", "c/d", "h", "e/f"]
output = []
for i in input:
if "/" in i:
output.append(i.split("/")[1])
print output
['b', 'd', 'f']
</code></pre>
| 0 | 2016-09-07T04:52:00Z | [
"python",
"list"
] |
How to create a list from another list using specific criteria in Python? | 39,361,381 | <p>How can I create a list from another list using python?
If I have a list:</p>
<pre><code>input = ['a/b', 'g', 'c/d', 'h', 'e/f']
</code></pre>
<p>How can I create the list of only those letters that follow slash "/" i.e.</p>
<pre><code>desired_output = ['b','d','f']
</code></pre>
<p>A code would be very helpful.... | 5 | 2016-09-07T04:45:45Z | 39,361,452 | <p>With regex:</p>
<pre><code>>>> from re import match
>>> input = ['a/b', 'g', 'c/d', 'h', 'e/f', '/', 'a/']
>>> [m.groups()[0] for m in (match(".*/([\w+]$)", item) for item in input) if m]
['b', 'd', 'f']
</code></pre>
| 2 | 2016-09-07T04:53:42Z | [
"python",
"list"
] |
How to create a list from another list using specific criteria in Python? | 39,361,381 | <p>How can I create a list from another list using python?
If I have a list:</p>
<pre><code>input = ['a/b', 'g', 'c/d', 'h', 'e/f']
</code></pre>
<p>How can I create the list of only those letters that follow slash "/" i.e.</p>
<pre><code>desired_output = ['b','d','f']
</code></pre>
<p>A code would be very helpful.... | 5 | 2016-09-07T04:45:45Z | 39,361,462 | <p>Simple one-liner could be to:</p>
<pre><code>>> input = ["a/b", "g", "c/d", "h", "e/f"]
>> list(map(lambda x: x.split("/")[1], filter(lambda x: x.find("/")==1, input)))
Result: ['b', 'd', 'f']
</code></pre>
| 1 | 2016-09-07T04:54:23Z | [
"python",
"list"
] |
How to create a list from another list using specific criteria in Python? | 39,361,381 | <p>How can I create a list from another list using python?
If I have a list:</p>
<pre><code>input = ['a/b', 'g', 'c/d', 'h', 'e/f']
</code></pre>
<p>How can I create the list of only those letters that follow slash "/" i.e.</p>
<pre><code>desired_output = ['b','d','f']
</code></pre>
<p>A code would be very helpful.... | 5 | 2016-09-07T04:45:45Z | 39,361,478 | <pre><code>>>> input = ["a/b", "g", "c/d", "h", "e/f"]
>>> output=[]
>>> for i in input:
if '/' in i:
s=i.split('/')
output.append(s[1])
>>> output
['b', 'd', 'f']
</code></pre>
| 1 | 2016-09-07T04:56:43Z | [
"python",
"list"
] |
Python 3.4 calculating the mode,median reading through a file | 39,361,434 | <p>I was wondering if there was another way to code
At the core of this problem is the easiest way to solve this problem is to read a file and save the values in the list. Where then you'd have: </p>
<pre><code>a = [1,2,3,4,5,6,1,1,1,1]
import statistics
listMode = statistics.mode(a) # median, average, etc...
</co... | 1 | 2016-09-07T04:51:43Z | 39,361,473 | <p>If the set of input numbers comes from a reasonably small universe of values, as in your example, you could use a <code>Counter</code> to count how many of each value you see as they pass by. From that <code>Counter</code> you can get the mode easily, and the median with a little work. Calculating the average on the... | 3 | 2016-09-07T04:56:03Z | [
"python",
"python-3.x"
] |
Import celery task without importing dependencies | 39,361,511 | <p>I have two modules </p>
<pre><code>alpha.py
beta.py
</code></pre>
<p><code>beta.py</code> can only be run on <code>beta.server</code> because it requires a licensed solver than only exists on <code>beta.server</code>. </p>
<p>Within <code>alpha.py</code>, there's a portion of code that calls: </p>
<pre><code>bet... | 0 | 2016-09-07T04:59:56Z | 39,375,215 | <p>I ran into this before but never got it to work "right". I used a hacky workaround instead.</p>
<p>You can put the <code>import proprietary</code> statement in the <code>beta.beta_task</code> def itself. Your 'alpha' file doesn't actually run the 'beta' def, it just uses celery's task decorator to dispatch a messa... | 1 | 2016-09-07T16:34:43Z | [
"python",
"celery"
] |
minimum cost path in matrix | 39,361,555 | <p>Question -</p>
<p>Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.</p>
<p>Note: You can only move either down or right at any point in time</p>
<p>I know this is a common question and most of you guys would know t... | 2 | 2016-09-07T05:03:59Z | 39,361,930 | <p>I don't think it's correct to return 0 when you fall off the edge of the grid. That makes it look like you've succeeded. So I think the 2 that you are erroneously reporting is the 1 in upper left plus the 1 in lower left, followed by a "successful" falling off the bottom of the grid. I recommend you adjust your what... | 2 | 2016-09-07T05:39:32Z | [
"python",
"algorithm",
"dynamic"
] |
How to create 2 csv files when using recursion | 39,361,605 | <p>I want to create 2 csv files.</p>
<p>I have 2 array in one function then i am looping through it and calling another function to write into an csv file so it will create 2 csv files</p>
<pre><code>import time
import datetime
import csv
time_value = time.time()
def csv_write(s):
print s
f3 = open("import_"+... | 1 | 2016-09-07T05:09:04Z | 39,361,625 | <p>You need to add the argument into the file name:</p>
<pre><code>f3 = open("import_"+"".join(s)+"_"+str(int(time_value))+".csv", 'wt')
</code></pre>
<p>In this case you will have two files (with <code>"ab"</code> and <code>"sv"</code> in the names) if <code>a</code> contains two elements from your example. Here we ... | 0 | 2016-09-07T05:12:19Z | [
"python",
"arrays",
"csv"
] |
How to create 2 csv files when using recursion | 39,361,605 | <p>I want to create 2 csv files.</p>
<p>I have 2 array in one function then i am looping through it and calling another function to write into an csv file so it will create 2 csv files</p>
<pre><code>import time
import datetime
import csv
time_value = time.time()
def csv_write(s):
print s
f3 = open("import_"+... | 1 | 2016-09-07T05:09:04Z | 39,361,668 | <p>I'm not an experienced Python guy but it looks like the time value that names the files is being defined once outside of code dealing with the numbers of elements. Each array their would have the same time value.csv name as that time value was defined at the start and isn't called again. Try nesting the time value b... | 0 | 2016-09-07T05:16:12Z | [
"python",
"arrays",
"csv"
] |
How to create 2 csv files when using recursion | 39,361,605 | <p>I want to create 2 csv files.</p>
<p>I have 2 array in one function then i am looping through it and calling another function to write into an csv file so it will create 2 csv files</p>
<pre><code>import time
import datetime
import csv
time_value = time.time()
def csv_write(s):
print s
f3 = open("import_"+... | 1 | 2016-09-07T05:09:04Z | 39,361,762 | <p>First convert it into Dataframe then save it in CSV format </p>
<pre><code>import pandas as pd
a = [["a","b"],["s","v"]]
df=pd.DataFrame(a)
i=len(df)
for j in range(i):
df.iloc[:,j].to_csv(str(j)+'.csv',index=False)
</code></pre>
<p>After executing this code, you will get two csv files (As length of array ... | 1 | 2016-09-07T05:25:10Z | [
"python",
"arrays",
"csv"
] |
Python: extract pattern from stdout and save in csv | 39,361,621 | <p>I have log files of around 20000-30000 lines long, they contain all sort of data , each line starting with current time stamp, followed by path of files/linu numbers and then value of objects added with some additional (unnecessary info).</p>
<pre><code>2016/08/31 17:27:43/usr/log/data/old/objec: 540: Adjustment St... | 1 | 2016-09-07T05:11:37Z | 39,361,751 | <pre><code>import csv
with open('out.csv', 'w') as output_file, open('in.txt') as input_file:
writer = csv.writer(output_file)
for l in input_file:
if 'object ID:' in l:
object_id = l.split(':')[-1].strip()
elif 'Start location:' in l:
start_loc = l.split(':')[-1].strip(... | 3 | 2016-09-07T05:24:32Z | [
"python",
"csv",
"pattern-matching",
"export-to-csv"
] |
python logging module AttributeError: 'str' object has no attribute 'write' | 39,361,630 | <p>I am using tornado,and in its app,I import logging just want to log some info about server.
I put this:</p>
<pre><code>logging.config.dictConfig(web_LOGGING)
</code></pre>
<p>right before:</p>
<pre><code> tornado.options.parse_command_line()
</code></pre>
<p>but when I run the server,when I click any link,I get ... | 0 | 2016-09-07T05:12:53Z | 39,361,698 | <p>Psychic debugging says <code>web_LOGGING</code> has a key named <code>stream</code> with a <code>str</code> value (probably a file path); <a href="https://docs.python.org/3/library/logging.html#logging.basicConfig" rel="nofollow"><code>stream</code> is only for already opened files, if you want to pass a file path, ... | 1 | 2016-09-07T05:18:52Z | [
"python",
"logging",
"tornado"
] |
meaning of assignment operator in python2.7 | 39,361,706 | <p>i do the following:</p>
<pre><code>a=12345
</code></pre>
<p>I am trying to undertstand the meaning of this.Please answer below questions.</p>
<ol>
<li><p>a points to the memory address of 12345
(True/False)</p></li>
<li><p>If i do b=12345. Then b also points to the memoery address of 12345
(True/False)</p></li>
<... | 1 | 2016-09-07T05:20:12Z | 39,361,837 | <ol>
<li><p><em>"a points to the memory address of 12345 (True/False)"</em></p>
<p>True.</p></li>
<li><p><em>"If i do b=12345. Then b also points to the memoery address of 12345 (True/False)"</em></p>
<p>Maybe. If you had assigned <code>b=a</code>, the <code>b</code> would point to the same memory location as <code>... | 1 | 2016-09-07T05:31:06Z | [
"python",
"python-2.7"
] |
Unable to run Python script from specific directoy. What could be the reason? | 39,361,732 | <p>1) OS = MacOS (El Capitan)</p>
<p>2) Using native Python install</p>
<p>3) Problem: I wrote a script in a directory called "pythonscripts". This will not run from this directory. If I copy the same script to a directory above this, or one below this or to the user's home directory, it runs just fine. I have attem... | 1 | 2016-09-07T05:22:56Z | 39,361,860 | <p>If you have a file called urllib2.py, you must rename it.
You should never name a script like a python package/module.</p>
| 0 | 2016-09-07T05:33:24Z | [
"python",
"osx"
] |
Using Sigmoid instead of Tanh activation function fails - Neural Networks | 39,361,755 | <p>I'm looking at the following <a href="http://www.bogotobogo.com/python/files/NeuralNetworks/nn3.py" rel="nofollow">code</a> from <a href="http://www.bogotobogo.com/python/python_Neural_Networks_Backpropagation_for_XOR_using_one_hidden_layer.php" rel="nofollow">this blog</a></p>
<p>It gives the option to use both th... | 2 | 2016-09-07T05:24:49Z | 39,362,349 | <p>Looks like the model you use doesn't train biases.
The only difference between <code>tanh</code> and <code>sigmoid</code> is scaling and offset. Learning the new scaling will be done through the weights, but you'll also need to learn to compensate for the new offset, which should be done by learning the biases as we... | 0 | 2016-09-07T06:11:26Z | [
"python",
"neural-network",
"backpropagation",
"sigmoid"
] |
Move non empty cells to left in grouped columns pandas | 39,361,839 | <p>I have a dataframe where there are multiple columns with similar column names. I want the empty cells to be populated with those columns which have data to the right. </p>
<pre><code>Address1 Address2 Address3 Address4 Phone1 Phone2 Phone3 Phone4
ABC nan def na... | 3 | 2016-09-07T05:31:23Z | 39,362,818 | <p><strong><code>pushna</code></strong><br>
Pushes all null values to the end of the series</p>
<p><strong><code>coltype</code></strong><br>
Uses <code>regex</code> to extract the non-numeric prefix from all column names</p>
<pre><code>def pushna(s):
notnull = s[s.notnull()]
isnull = s[s.isnull()]
values ... | 2 | 2016-09-07T06:41:37Z | [
"python",
"pandas",
"multiple-columns",
null,
"shift"
] |
Move non empty cells to left in grouped columns pandas | 39,361,839 | <p>I have a dataframe where there are multiple columns with similar column names. I want the empty cells to be populated with those columns which have data to the right. </p>
<pre><code>Address1 Address2 Address3 Address4 Phone1 Phone2 Phone3 Phone4
ABC nan def na... | 3 | 2016-09-07T05:31:23Z | 39,364,043 | <p>Solutions with <code>MultiIndex</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html" rel="nofollow"><code>dropna</code></a>:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'Address1': {0: 'ABC', 1: 'ABC'},
'Address2': ... | 3 | 2016-09-07T07:44:10Z | [
"python",
"pandas",
"multiple-columns",
null,
"shift"
] |
NoReverseMatch in Django 1.10 | 39,361,877 | <p>Here is my <strong>url.py</strong></p>
<pre><code>from django.conf.urls import url
from django.contrib import admin
from app import views, auth
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.index, name = 'index'),
url(r'^login/', auth.login, name = 'login'),
url(r'^logout/', aut... | 2 | 2016-09-07T05:35:40Z | 39,361,941 | <p>You should use admin namespace, like written in the <a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#reversing-admin-urls" rel="nofollow">docs</a>. You could also look on other admin urls in that namespace. </p>
<pre><code>{% url 'admin:index' %}
</code></pre>
| 1 | 2016-09-07T05:40:40Z | [
"python",
"django"
] |
NoReverseMatch in Django 1.10 | 39,361,877 | <p>Here is my <strong>url.py</strong></p>
<pre><code>from django.conf.urls import url
from django.contrib import admin
from app import views, auth
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.index, name = 'index'),
url(r'^login/', auth.login, name = 'login'),
url(r'^logout/', aut... | 2 | 2016-09-07T05:35:40Z | 39,361,979 | <p>Use <code>admin:index</code> if you want to have an url to <code>/admin/</code> site.
If you install <a href="https://pypi.python.org/pypi/django-extensions/0.7.1" rel="nofollow">django-extensions</a> you can use <code>./manage.py show_urls</code> to get the list of urls for your app</p>
| 1 | 2016-09-07T05:43:29Z | [
"python",
"django"
] |
NoReverseMatch in Django 1.10 | 39,361,877 | <p>Here is my <strong>url.py</strong></p>
<pre><code>from django.conf.urls import url
from django.contrib import admin
from app import views, auth
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.index, name = 'index'),
url(r'^login/', auth.login, name = 'login'),
url(r'^logout/', aut... | 2 | 2016-09-07T05:35:40Z | 39,363,609 | <p>Set admin url in your project urls.py, same folder as your settings.py</p>
<pre><code>Url(r'^admin/', admin.site.urls),
</code></pre>
<p>Then call it in your template:</p>
<p><code><a href="{% url 'admin:index' %} > link </a></code></p>
| 1 | 2016-09-07T07:21:25Z | [
"python",
"django"
] |
NoReverseMatch in Django 1.10 | 39,361,877 | <p>Here is my <strong>url.py</strong></p>
<pre><code>from django.conf.urls import url
from django.contrib import admin
from app import views, auth
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.index, name = 'index'),
url(r'^login/', auth.login, name = 'login'),
url(r'^logout/', aut... | 2 | 2016-09-07T05:35:40Z | 39,475,989 | <p>1 . Make a <code>url.py</code> in app folder and use</p>
<pre><code>urlpatterns = [
url(r'^admin/', admin.site.urls),
]
</code></pre>
<p>and in template use</p>
<pre><code><a href="{% url 'admin:index' %}">Admin</a>
</code></pre>
<p>or</p>
<ol start="2">
<li>Use <code><a href="/admin">Admi... | 1 | 2016-09-13T17:40:36Z | [
"python",
"django"
] |
Convert date column in dataframe to ticks in python | 39,361,916 | <p>Good day</p>
<p>I have a pandas dataframe with 3 columns. Column two is in date format yyyy-mm-dd but I would like to convert these to ticks. I would like to know the most efficient way to do this (i.e. I don't want to loop through each row).</p>
<p>My code is as follows:</p>
<pre><code>#Example of getting ticks
... | 1 | 2016-09-07T05:38:41Z | 39,362,414 | <p>First, wrap the converting-to-ticks part in a function, such as</p>
<pre><code>def convert_to_tic(s):
return time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())
</code></pre>
<p>Then, turn your column into a <code>DataFrame</code> and use <a href="http://pandas.pydata.org/pandas-docs/stable/gene... | 0 | 2016-09-07T06:15:58Z | [
"python",
"datetime",
"time"
] |
Pandas: Groupby and cut within a group | 39,362,151 | <p>I have a pandas dataframe which looks like this:</p>
<pre><code>userid name date
1 name1 2016-06-04
1 name2 2016-06-05
1 name3 2016-06-04
1 name1 2016-06-06
2 name23 2016-06-01
2 name2 2016-06-01
3 name1 2016-06-03
3 ... | 3 | 2016-09-07T05:57:31Z | 39,362,397 | <p>You can first sort <code>DataFrame</code> by column <code>date</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>sort_values</code></a> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html"... | 3 | 2016-09-07T06:14:50Z | [
"python",
"python-2.7",
"pandas"
] |
Python - does range() mutate variable values while in recursion? | 39,362,283 | <p>While working on understanding string permutations and its implementation in python (regarding to <a href="http://stackoverflow.com/a/20955291/1055601">this post</a>) I stumbled upon something in a <code>for</code> loop using <code>range()</code> I just don't understand.</p>
<p>Take the following code:</p>
<pre><c... | 1 | 2016-09-07T06:06:11Z | 39,362,697 | <p>Your conclusion is <strong>incorrect</strong>. <code>step</code> value does not change by using <code>range</code>.
This can be verified as:</p>
<pre><code>def no_recursion(step=0):
print "Step I: {}".format(step)
for i in range(step, 2):
print "Step II: {}".format(step)
print "Value i: {}".... | 1 | 2016-09-07T06:35:13Z | [
"python",
"recursion"
] |
Append Values from input to a sublist in Python | 39,362,297 | <p>I am trying to append values from an input to sublists in a list.
Each number of Student and name should be in a sublist.
ex: </p>
<pre><code>[[123,John],[124,Andrew]]
</code></pre>
<p>Where the outside list would be the number of students, and the sublists , the info of the students..</p>
<p>Here is what my code... | 0 | 2016-09-07T06:07:29Z | 39,362,376 | <p>Your code can be greatly simplified:</p>
<ol>
<li>You don't need to pre-allocate the lists and sublists. Just have one list, and append the sublists as you receive inputs.</li>
<li>You don't need to cast user input from <code>input</code> to strings, as they are strings already.</li>
</ol>
<p>Here's the modified c... | 2 | 2016-09-07T06:13:34Z | [
"python",
"list",
"append",
"sublist"
] |
Append Values from input to a sublist in Python | 39,362,297 | <p>I am trying to append values from an input to sublists in a list.
Each number of Student and name should be in a sublist.
ex: </p>
<pre><code>[[123,John],[124,Andrew]]
</code></pre>
<p>Where the outside list would be the number of students, and the sublists , the info of the students..</p>
<p>Here is what my code... | 0 | 2016-09-07T06:07:29Z | 39,362,439 | <p>Your code can be more pythonic and can make use of some basic error handling as well. Create the inner list inside the while loop and simply append to the outer student list. This should work.</p>
<pre><code>students = []
while True:
try:
choice = int(input("1- Register Student 0- Exit"))
except Val... | 0 | 2016-09-07T06:17:57Z | [
"python",
"list",
"append",
"sublist"
] |
Python - multithreading with sockets gives random results | 39,362,359 | <p>I am really confused about my problem right now. I want to discover an open port over a list of hosts (or subnet).</p>
<p>So first let's show what I've done so far.. </p>
<pre><code>from multiprocessing.dummy import Pool as ThreadPool
from netaddr import IPNetwork as getAddrList
import socket, sys
this = sys.... | 1 | 2016-09-07T06:12:17Z | 39,402,783 | <p><strong>The first mistake was:</strong></p>
<blockquote>
<p>But note that my CPU usage is <10% and the
network usage is <50%!</p>
</blockquote>
<p>Actually it was a 400 % network usage. I expected bits instead of bytes.<br>
Very embrassing..</p>
<p><strong>And the second mistake was:</strong></p>
<bloc... | 0 | 2016-09-09T02:10:03Z | [
"python",
"multithreading",
"sockets",
"connection",
"multiprocessing"
] |
Find Image components using python/PIL | 39,362,381 | <p>Is there a function in PIL/Pillow that for a grayscale image, will separate the image into sub images containing the components that make up the original image? For example, a png grayscale image with a set of blocks in them. Here, the images types always have high contrast to the background.</p>
<p>I don't want to... | 1 | 2016-09-07T06:13:56Z | 39,362,636 | <p>Yes, it is possible. You can use <code>edge</code> detection algorithms in PIL.
Sample code:</p>
<pre><code>from PIL import Image, ImageFilter
image = Image.open('/tmp/sample.png').convert('RGB')
image = image.filter(ImageFilter.FIND_EDGES)
image.save('/tmp/output.png')
</code></pre>
<p>sample.png :</p>
<p><a hr... | 0 | 2016-09-07T06:31:00Z | [
"python",
"pillow"
] |
Find Image components using python/PIL | 39,362,381 | <p>Is there a function in PIL/Pillow that for a grayscale image, will separate the image into sub images containing the components that make up the original image? For example, a png grayscale image with a set of blocks in them. Here, the images types always have high contrast to the background.</p>
<p>I don't want to... | 1 | 2016-09-07T06:13:56Z | 39,363,644 | <p>Not using PIL, but worth a look I think:
I start with a list of image files that I've imported as a list of <code>numpy</code> arrays, and I create a list of boolean versions where the <code>threshold</code> is <code>> 0</code></p>
<pre><code>from skimage.measure import label, regionprops
import numpy as np
boo... | 0 | 2016-09-07T07:22:38Z | [
"python",
"pillow"
] |
ttk.Separator appearing as dot "." when using .pack() layout manager | 39,362,394 | <p>My question is similar to <a href="http://stackoverflow.com/questions/37924785/ttk-separator-set-the-length-width">this one</a>, but I'm using the layout manager <code>pack</code> rather than <code>grid</code> so the answer in the alternate thread doesn't work for me.</p>
<p>Code:</p>
<pre><code> iconLabelImage... | 0 | 2016-09-07T06:14:39Z | 39,363,498 | <p>Actually the idea is same with the <a href="http://stackoverflow.com/questions/37924785/ttk-separator-set-the-length-width">question</a> you have provided above. That means:</p>
<blockquote>
<p>The expand option tells the manager to assign additional space to the widget box. If the parent widget is made larger th... | 1 | 2016-09-07T07:15:45Z | [
"python",
"python-3.x",
"tkinter",
"separator",
"ttk"
] |
how to access previous line while we are accessing lines one by one in a loop using python? | 39,362,464 | <p>this is my code to print 20 lines at a time but I want to print 20 lines and then i want to start printing from 20th line how can I do that can anyone tell me? please</p>
<pre><code>f1=open("sample.txt","r")
last_pos=0
line=0
while True:
for i,l in enumerate(f1):
#l=f1.readline()
if l=="":
... | 0 | 2016-09-07T06:19:09Z | 39,362,514 | <p>To locate some line, you can use seek() function.</p>
| 0 | 2016-09-07T06:22:34Z | [
"python",
"file"
] |
How can I set the default position of a trackbar in OpenCV? | 39,362,497 | <p>In OpenCV, using the createTrackbar function, how can someone set the default slider position to a maximum?</p>
<p>I have several sliders, some representing minimum values, and some representing maximum values. It would be nice, if the sliders for a max value, started out at the maximum (255), rather than the minim... | 1 | 2016-09-07T06:21:04Z | 39,362,553 | <p>Just use the value field:</p>
<blockquote>
<p>Python: cv.CreateTrackbar(trackbarName, windowName, value, count,
onChange) â None </p>
<p>Parameters:<br>
trackbarname â Name of the created trackbar. </p>
<p>winname â Name of the window that will be used as a parent
of the created trackbar.... | 2 | 2016-09-07T06:25:26Z | [
"python",
"opencv"
] |
How can I set the default position of a trackbar in OpenCV? | 39,362,497 | <p>In OpenCV, using the createTrackbar function, how can someone set the default slider position to a maximum?</p>
<p>I have several sliders, some representing minimum values, and some representing maximum values. It would be nice, if the sliders for a max value, started out at the maximum (255), rather than the minim... | 1 | 2016-09-07T06:21:04Z | 39,362,565 | <p>I think you didn't pay much attention reading documentation, there you can find:<br>
<strong>value</strong> â Optional pointer to an integer variable whose value reflects the position of the slider. Upon creation, the slider position is defined by this variable.<br>
<strong>count</strong> â Maximal position of t... | 1 | 2016-09-07T06:26:01Z | [
"python",
"opencv"
] |
Class and external method call | 39,362,580 | <p>I am going through a data structures course and I am not understanding how a Class can call a method that's in another Class.<br>
The code below has 2 classes: <code>Printer</code> and <code>Task</code>.<br>
Notice that class <code>Printer</code> has a method called <code>startNext</code>, and this has a variable <c... | 2 | 2016-09-07T06:27:15Z | 39,363,055 | <p>If I understand clearly your question, it is because you are adding task object to Queue list. Then when you are getting object (list item) back, you are getting again Task object:</p>
<pre><code>#creating Task object and adding to Queque list
task = Task(currentSecond)
printQueue.enqueue(task)
class Queue:
de... | 1 | 2016-09-07T06:53:42Z | [
"python"
] |
python download images are not saved to the correct directory | 39,362,591 | <p>When i use python 2.7 to download images from a website, the code as follows:</p>
<pre><code>pic = requests.get(src[0])
f = open("pic\\"+str(i) + '.jpg', "wb")
f.write(pic.content)
f.close()
i += 1
</code></pre>
<p>I want to save the picture into pic directory, but I find that images is saved in the same directory... | 0 | 2016-09-07T06:28:00Z | 39,362,645 | <p><a href="http://www.howtogeek.com/181774/why-windows-uses-backslashes-and-everything-else-uses-forward-slashes/" rel="nofollow">Windows uses backslashes for file paths</a>, but Ubuntu uses forward slashes. This is why your save path with a backslash doesn't work on Ubuntu.</p>
<p>You probably want to use <a href="h... | 2 | 2016-09-07T06:31:46Z | [
"python",
"file"
] |
python download images are not saved to the correct directory | 39,362,591 | <p>When i use python 2.7 to download images from a website, the code as follows:</p>
<pre><code>pic = requests.get(src[0])
f = open("pic\\"+str(i) + '.jpg', "wb")
f.write(pic.content)
f.close()
i += 1
</code></pre>
<p>I want to save the picture into pic directory, but I find that images is saved in the same directory... | 0 | 2016-09-07T06:28:00Z | 39,362,875 | <pre><code>import os
f = open(os.sep.join(['pic', str(i), '.jpg']), 'wb')
</code></pre>
<p>Now the line should be os agnostic</p>
| 1 | 2016-09-07T06:44:53Z | [
"python",
"file"
] |
what does "()" syntax mean in python | 39,362,622 | <p>I am learning Exception Handling in python and came across following code snippet : an exception class:</p>
<pre><code>from flask import jsonify
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.messa... | 2 | 2016-09-07T06:29:58Z | 39,362,658 | <p>From python shell:</p>
<pre><code>>>> type(())
<type 'tuple'>
</code></pre>
<p>So it's a <a href="https://docs.python.org/2/library/functions.html?highlight=tuple#tuple" rel="nofollow">tuple</a>.</p>
| 3 | 2016-09-07T06:32:31Z | [
"python"
] |
what does "()" syntax mean in python | 39,362,622 | <p>I am learning Exception Handling in python and came across following code snippet : an exception class:</p>
<pre><code>from flask import jsonify
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.messa... | 2 | 2016-09-07T06:29:58Z | 39,362,703 | <p><code>()</code> stands for an empty tuple. On the other hand, <code>or</code> here acts like <a href="https://en.wikipedia.org/wiki/Null_coalescing_operator" rel="nofollow">null coalescing operator</a> in <code>self.payload or ()</code> where the entire expression returns an empty tuple if <code>self.payload</code> ... | 5 | 2016-09-07T06:35:40Z | [
"python"
] |
what does "()" syntax mean in python | 39,362,622 | <p>I am learning Exception Handling in python and came across following code snippet : an exception class:</p>
<pre><code>from flask import jsonify
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.messa... | 2 | 2016-09-07T06:29:58Z | 39,362,751 | <p>Basically what is happening is that as @turkus answered: </p>
<blockquote>
<p>From python shell:</p>
<pre><code>type(())
<type 'tuple'>
</code></pre>
<p>So it's a tuple.</p>
</blockquote>
<p>What it is doing is checking if <code>self.payload</code> is not <code>None</code>.
If it is <code>None</code>... | 1 | 2016-09-07T06:38:33Z | [
"python"
] |
Showing columns in pandas | 39,362,624 | <p>I have a term x document matrix in pandas (made from a CSV) of the form:</p>
<pre><code>cheese, milk, bread, butter
0,2,1,0
1,1,0,0
1,1,1,1
0,1,0,1
</code></pre>
<p>So if I say '<em>give me the columns at index 1 and 2 where the values of a given row are both > 0</em>'. </p>
<p>I want to end up with this:</p>
<... | 2 | 2016-09-07T06:30:22Z | 39,362,715 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow"><code>iloc</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>#get 1. and 2. column... | 1 | 2016-09-07T06:36:30Z | [
"python",
"pandas",
"indexing",
"condition",
"multiple-columns"
] |
Showing columns in pandas | 39,362,624 | <p>I have a term x document matrix in pandas (made from a CSV) of the form:</p>
<pre><code>cheese, milk, bread, butter
0,2,1,0
1,1,0,0
1,1,1,1
0,1,0,1
</code></pre>
<p>So if I say '<em>give me the columns at index 1 and 2 where the values of a given row are both > 0</em>'. </p>
<p>I want to end up with this:</p>
<... | 2 | 2016-09-07T06:30:22Z | 39,363,070 | <pre><code>df.loc[[1, 2], df.loc[[1, 2]].gt(0).all()]
</code></pre>
<p><a href="http://i.stack.imgur.com/qHCu1.png" rel="nofollow"><img src="http://i.stack.imgur.com/qHCu1.png" alt="enter image description here"></a></p>
| 1 | 2016-09-07T06:54:25Z | [
"python",
"pandas",
"indexing",
"condition",
"multiple-columns"
] |
List out of index after deleting elements- python | 39,362,632 | <p>I'm trying to implement a simple SSTF program and trying to iterate over the queue of processes that have come in and subsequently delete anything that I have taken into account but it says "Out of index error".</p>
<pre><code>for i in xrange(0,len(queue)):
for j in xrange(0,(len(queue))):
a = abs(queue... | -1 | 2016-09-07T06:30:52Z | 39,363,017 | <p>My guess is that you didn't initialize min and pos properly (e.g. min is not small enough), thus the value pos has never been set. Then queue[pos] points to an undefined position.</p>
| 1 | 2016-09-07T06:51:29Z | [
"python",
"algorithm",
"python-2.7"
] |
What is the most elegant way to create a dictionary with the value as lists? | 39,362,707 | <p>So I have something like</p>
<pre><code>retval = {}
# ...
# some code here to fetch data
# ...
for row in cursor.fetchall():
if row.someid not in retval:
retval[row.someid] = [dict(zip(columns,rows))]
else:
retval[row.someid].append(dict(zip(columns,rows))
</code></pre>
<p>which yields:</... | 3 | 2016-09-07T06:35:53Z | 39,362,753 | <p>Try using <code>defaultdict</code> from the builtin <code>collections</code> module:</p>
<pre class="lang-python prettyprint-override"><code>from collections import defaultdict
retval = defaultdict(lambda: [])
# ...
# some code here to fetch data
# ...
for row in cursor.fetchall():
retval[row.someid].append(d... | 3 | 2016-09-07T06:38:46Z | [
"python"
] |
indexing issues when extracting specified latitude and longitude | 39,362,967 | <p>I want to extract a specified latitude and longitude from a <code>netCDF</code> file. In the past, I have never had issues with extracting the data. I am assuming that the reason it is not working this time is because I read in my data differently (see below)</p>
<pre><code>data = netCDF4.Dataset('/home/eburrows/me... | 0 | 2016-09-07T06:48:32Z | 39,373,646 | <p>The results of <code>lat_us</code> from the <code>where</code> command are a tuple of indices, not the actual indices that are needed for slicing <code>air_temp</code>. To fix this, you need to index the first result from <code>lat_us</code> to access the array of latitude indices. </p>
<p>For instance,</p>
<pre... | 0 | 2016-09-07T15:14:58Z | [
"python",
"list",
"indexing",
"tuples",
"typeerror"
] |
How to use `scipy.optimize.leastsq` to optimize in the joint least squares direction? | 39,363,046 | <p>I want to be able to move along a gradient in the <em>joint least squares direction</em>.</p>
<p>I thought I could do this using <code>scipy.optimize.leastsq</code> (<a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.leastsq.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/gen... | 0 | 2016-09-07T06:53:05Z | 39,366,922 | <p>I don't think you need <code>scipy.optimize.leastsq</code> because your problem can be solved analytically. At any moment, the gradient of the fuction <code>np.sum(x)</code> where <code>x</code> is an array, is <code>2*x</code>. So, if you want to obtain the smallest increase, then you have to increase the smallest ... | 1 | 2016-09-07T10:05:22Z | [
"python",
"numpy",
"optimization",
"scipy",
"least-squares"
] |
Brightness/Histogram normalization for time lapse images | 39,363,183 | <p>I'm working in a laboratory and we often make time lapse series (image every hour) of stem cells. The current idea is to put all frames together and make a video showing this growing cells (similar to this <a href="https://www.youtube.com/watch?v=zSuLDqRfhXo" rel="nofollow">youtube video</a>). Which could done simpl... | 0 | 2016-09-07T06:59:40Z | 39,363,906 | <p>Are those images RGB or gray values? I would just perform a normalization in your loop after reading each frame:</p>
<pre><code>frame = frame/np.max(frame)
</code></pre>
<p>In case of gray values each image should then have values between 0 and 1 but depending on how your images look like you could also try other ... | 0 | 2016-09-07T07:37:05Z | [
"python",
"opencv",
"timelapse"
] |
Brightness/Histogram normalization for time lapse images | 39,363,183 | <p>I'm working in a laboratory and we often make time lapse series (image every hour) of stem cells. The current idea is to put all frames together and make a video showing this growing cells (similar to this <a href="https://www.youtube.com/watch?v=zSuLDqRfhXo" rel="nofollow">youtube video</a>). Which could done simpl... | 0 | 2016-09-07T06:59:40Z | 39,370,737 | <p>If your data is in a 3D array, you shouldn't need to loop over it to do this. With 5 images of, say 256 x 256, you should be able to construct an array that is <code>arr.shape == (256, 256, 5)</code>. My initial comment was a little off I think, but the below example should do it.</p>
<pre><code>target_array = []
... | 1 | 2016-09-07T13:05:15Z | [
"python",
"opencv",
"timelapse"
] |
Why python request working but C# request not working? | 39,363,348 | <p>First, i try to post the script in PostMan tool.</p>
<pre><code>{"AO":"ECHO"}
</code></pre>
<p>It working fine. Then i'm writing this request in C# but it not working.
And more i wrote the request again in Python, and it working well.
But my project is in Microsoft C#. I dont want to run script Python in C# at all... | 2 | 2016-09-07T07:08:05Z | 39,403,931 | <p>Python will automatically add Content-Length http header.
<a href="https://docs.python.org/2/library/httplib.html#httpconnection-objects" rel="nofollow">https://docs.python.org/2/library/httplib.html#httpconnection-objects</a></p>
<p>I think you might have to set this header manually in C#. </p>
<pre><code>httpWe... | 0 | 2016-09-09T04:35:34Z | [
"c#",
"python",
"postman"
] |
Best algorithm to compare list or dict | 39,363,462 | <p>I'm dealing with a bit complicated data set via Python. I'm a novice Python coder. The data set is the collection of Date, Title, Contents and URL.</p>
<p>Conceptually, it will be like this.</p>
<pre><code>1st scraping runs, then I get,
[9/6 9:00, title1, content1]
[9/6 9:00, title2, content2]
[9/6 8:22, title3, ... | 1 | 2016-09-07T07:14:07Z | 39,364,341 | <p>Did you try something like that?</p>
<pre><code>>>> common_elements = []
>>> a = [['date', 'title1', 'content1'], ['date2', 'title2', 'content2']]
>>> b = [['date3', 'title3', 'content3'], ['date2', 'title2', 'content2']]
>>> for element in a:
... if element in b:
... ... | 0 | 2016-09-07T08:00:09Z | [
"python",
"python-3.x",
"compare"
] |
Best algorithm to compare list or dict | 39,363,462 | <p>I'm dealing with a bit complicated data set via Python. I'm a novice Python coder. The data set is the collection of Date, Title, Contents and URL.</p>
<p>Conceptually, it will be like this.</p>
<pre><code>1st scraping runs, then I get,
[9/6 9:00, title1, content1]
[9/6 9:00, title2, content2]
[9/6 8:22, title3, ... | 1 | 2016-09-07T07:14:07Z | 39,365,130 | <p>Try this for comparison between <code>list</code> in python 3:</p>
<pre><code>a= [['9/6 9:00', 'title1', 'content1'],
['9/6 9:00', 'title2', 'content2'],
['9/6 8:22', 'title3', 'content3'],
['9/6 11:01','title4', 'content4']]
b=[['9/6 13:05', 'title5', 'content5'],
['9/6 12:13', 'title6', 'content6'],
['9/6 9:00', ... | 1 | 2016-09-07T08:41:24Z | [
"python",
"python-3.x",
"compare"
] |
Best algorithm to compare list or dict | 39,363,462 | <p>I'm dealing with a bit complicated data set via Python. I'm a novice Python coder. The data set is the collection of Date, Title, Contents and URL.</p>
<p>Conceptually, it will be like this.</p>
<pre><code>1st scraping runs, then I get,
[9/6 9:00, title1, content1]
[9/6 9:00, title2, content2]
[9/6 8:22, title3, ... | 1 | 2016-09-07T07:14:07Z | 39,365,712 | <pre><code>a = [['9/6 9:00', 'title1', 'content1'],
['9/6 9:00', 'title2', 'content2'],
['9/6 8:22', 'title3', 'content3'],
['9/6 11:01','title4', 'content4']]
b = [['9/6 13:05', 'title5', 'content5'],
['9/6 12:13', 'title6', 'content6'],
['9/6 9:00', 'title1', 'content1'],
['9/6 14:21', '... | 0 | 2016-09-07T09:08:41Z | [
"python",
"python-3.x",
"compare"
] |
Filter a smaller file using another huge file | 39,363,480 | <p>I have a huge csv file with about 10^9 lines where each line has a pair of ids such as:</p>
<pre><code>IDa,IDb
IDb,IDa
IDc,IDd
</code></pre>
<p>Call this file1. I have another much smaller csv file with about 10^6 lines in the same format. Call this file2. </p>
<p>I want to simply find the lines in file2 which c... | 1 | 2016-09-07T07:14:58Z | 39,363,699 | <p>I would actually use <code>sqlite</code> for something like that. You could create a new database from the same directory as two files with <code>sqlite3 test.sqlite</code> and then do something like that:</p>
<pre><code>create table file1(id1, id2);
create table file2(id1, id2);
.separator ","
.import file1.csv fi... | 4 | 2016-09-07T07:25:34Z | [
"python",
"perl",
"awk"
] |
Filter a smaller file using another huge file | 39,363,480 | <p>I have a huge csv file with about 10^9 lines where each line has a pair of ids such as:</p>
<pre><code>IDa,IDb
IDb,IDa
IDc,IDd
</code></pre>
<p>Call this file1. I have another much smaller csv file with about 10^6 lines in the same format. Call this file2. </p>
<p>I want to simply find the lines in file2 which c... | 1 | 2016-09-07T07:14:58Z | 39,364,010 | <p>In perl,</p>
<pre><code>use strict;
use warnings;
use autodie;
# read file2
open my $file2, '<', 'file2';
chomp( my @file2 = <$file2> );
close $file2;
# record file2 line numbers each id is found on
my %id;
for my $line_number (0..$#file2) {
for my $id ( split /,/, $file2[$line_number] ) {
pu... | 1 | 2016-09-07T07:42:34Z | [
"python",
"perl",
"awk"
] |
Filter a smaller file using another huge file | 39,363,480 | <p>I have a huge csv file with about 10^9 lines where each line has a pair of ids such as:</p>
<pre><code>IDa,IDb
IDb,IDa
IDc,IDd
</code></pre>
<p>Call this file1. I have another much smaller csv file with about 10^6 lines in the same format. Call this file2. </p>
<p>I want to simply find the lines in file2 which c... | 1 | 2016-09-07T07:14:58Z | 39,364,025 | <pre><code>$ cat > file2 # make test file2
IDb,IDa
$ awk -F, 'NR==FNR{a[$1];a[$2];next} ($1 in a&&++a[$1]==1){print $1} ($2 in a&&++a[$2]==1){print $2}' file2 file1 > file3
$ cat file3 # file2 ids in file1 put to file3
IDa
IDb
$ awk -F, 'NR==FNR{a[$1];next} ($1 in a)||($2 in a){print $0}' file3 fi... | 5 | 2016-09-07T07:43:09Z | [
"python",
"perl",
"awk"
] |
Filter a smaller file using another huge file | 39,363,480 | <p>I have a huge csv file with about 10^9 lines where each line has a pair of ids such as:</p>
<pre><code>IDa,IDb
IDb,IDa
IDc,IDd
</code></pre>
<p>Call this file1. I have another much smaller csv file with about 10^6 lines in the same format. Call this file2. </p>
<p>I want to simply find the lines in file2 which c... | 1 | 2016-09-07T07:14:58Z | 39,364,064 | <p>Sample files:</p>
<pre><code>cat f1
IDa,IDb
IDb,IDa
IDc,IDd
cat f2
IDt,IDy
IDb,IDj
</code></pre>
<p>Awk solution: </p>
<pre><code>awk -F, 'NR==FNR {a[$1]=$1;b[$2]=$2;next} ($1 in a)||($2 in b)' f1 f2
IDb,IDj
</code></pre>
<p>This will store first and second columns of file1 in array a and b. Then print those ... | 0 | 2016-09-07T07:45:14Z | [
"python",
"perl",
"awk"
] |
Filter a smaller file using another huge file | 39,363,480 | <p>I have a huge csv file with about 10^9 lines where each line has a pair of ids such as:</p>
<pre><code>IDa,IDb
IDb,IDa
IDc,IDd
</code></pre>
<p>Call this file1. I have another much smaller csv file with about 10^6 lines in the same format. Call this file2. </p>
<p>I want to simply find the lines in file2 which c... | 1 | 2016-09-07T07:14:58Z | 39,372,191 | <p>Using these input files for testing:</p>
<pre><code>$ cat file1
IDa,IDb
IDb,IDa
IDc,IDd
$ cat file2
IDd,IDw
IDx,IDc
IDy,IDz
</code></pre>
<p>If file1 can fit in memory:</p>
<pre><code>$ awk -F, 'NR==FNR{a[$1];a[$2];next} ($1 in a) || ($2 in a)' file1 file2
IDd,IDw
IDx,IDc
</code></pre>
<p>If not but file2 can f... | 2 | 2016-09-07T14:09:27Z | [
"python",
"perl",
"awk"
] |
client=MongoClient() syntax error using pyspark | 39,363,491 | <p>I'm trying to realize analystics through Spark using Pyspark. The event, once analyzed, should be send in a Mongo database.
The python code is in the file myFile.py
However, when running this command:</p>
<pre><code>spark-2.0.0/bin/spark-submit myFile.py
</code></pre>
<p>I have the following error:</p>
<pre><code... | 0 | 2016-09-07T07:15:20Z | 39,367,071 | <p>So I'm answering my own question.</p>
<p>Some typing errors were in my code inducing error messages that were not explicitely designating those typing errors. Also, my pymongo installation was not correctly done.
I corrected the typing errors in my code and reinstalled pymongo and it seems to work now.</p>
| 0 | 2016-09-07T10:12:53Z | [
"python",
"mongodb",
"apache-spark",
"pymongo"
] |
Difference between adding path to PYTHONPATH and installing your own module | 39,363,544 | <p>I'm working on a python project that contains a number of routines I use repeatedly. Instead of rewriting code all the time, I just want to update my package and import it; however, it's nowhere near done and is constantly changing. I host the package on a repo so that colleagues on various machines (UNIX + Windows)... | 1 | 2016-09-07T07:18:15Z | 39,363,685 | <p>PYTHONPATH is a valid way of doing this, but in my (personal) opinion it's more useful if you have a whole different place where you keep your python variables. Like <code>/opt/pythonpkgs</code> or so.</p>
<p>For projects where I want it to be installed and also I have to keep developing, I use <code>develop</code>... | 0 | 2016-09-07T07:25:09Z | [
"python",
"module",
"packaging"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.