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
Ignore null/blank cells with filter
38,570,044
<p>I'm trying to filter the 22nd column with numbers between <code>0.10</code> and <code>1.00</code> into <code>Day.csv</code>. But some of those cells are blank with no number at all and cause an error:</p> <p><code>ValueError: could not convert string to float:</code></p> <p>Here is what I tried:</p> <pre><code>re...
1
2016-07-25T14:10:39Z
38,570,162
<p>You can use a ternary conditional to return <code>False</code> for blanks:</p> <pre><code>filteredDay = filter(lambda p: 0.10 &lt;= float(p[23]) &lt;= 1.00 if p[23] != '' else False, reader) # ^^^^^^^^^^^^^^ </code></pre>
2
2016-07-25T14:15:31Z
[ "python", "csv", "lambda" ]
Ignore null/blank cells with filter
38,570,044
<p>I'm trying to filter the 22nd column with numbers between <code>0.10</code> and <code>1.00</code> into <code>Day.csv</code>. But some of those cells are blank with no number at all and cause an error:</p> <p><code>ValueError: could not convert string to float:</code></p> <p>Here is what I tried:</p> <pre><code>re...
1
2016-07-25T14:10:39Z
38,570,166
<p>Presumably you therefore need your filter to return False when the cell in question contains no value? Try:</p> <pre><code>filteredDay = filter(lambda p: p[23] != "" and 0.10 &lt;= float(p[23]) &lt;= 1.00, reader) </code></pre>
3
2016-07-25T14:15:41Z
[ "python", "csv", "lambda" ]
Type hint that a function never returns
38,570,144
<p>Python's new <a href="https://www.python.org/dev/peps/pep-0484/">type hinting</a> feature allows us to type hint that a function returns <code>None</code>...</p> <pre><code>def some_func() -&gt; None: pass </code></pre> <p>... or to leave the return type unspecified, which the PEP dictates should cause static ...
11
2016-07-25T14:14:47Z
38,679,309
<p>There is no answer to this question, yet. Here are a couple of reasons:</p> <ul> <li><p>When a function doesn't return, there is no return value (not even <code>None</code>) that a type could be assigned to. So you are not actually trying to annotate a type; you are trying to annotate <em>the absence of a type</em>...
2
2016-07-30T23:07:13Z
[ "python", "type-hinting" ]
How to rank DataFrame by subgroup
38,570,175
<p>If I have a DataFrame such as </p> <pre><code> col1 col2 col3 0 x1 typeA 3 1 x2 typeB 13 2 x3 typeB 3 3 x4 typeA 5 4 x5 typeB 1 5 x6 typeA 1 </code></pre> <p>is there a way of ranking the rows by col3 for each type in col2? For example this solution would look like</p> ...
1
2016-07-25T14:16:04Z
38,570,297
<p><code>transform</code> keeps the same shape as your original dataframe. Then use a <code>lambda</code> function to rank <code>col3</code> based on groupings from <code>col2</code>..</p> <pre><code>df['col4'] = df.groupby('col2').col3.transform(lambda group: group.rank()) &gt;&gt;&gt; df col1 col2 col3 col4 ...
1
2016-07-25T14:20:40Z
[ "python", "pandas" ]
Python pandas make new column from data in existing column and from another dataframe
38,570,198
<p>I have a DataFrame called 'mydata', and if I do</p> <pre><code>len(mydata.loc['2015-9-2']) </code></pre> <p>It counts the number of rows in mydata that have that date, and returns a number like</p> <pre><code>1067 </code></pre> <p>I have another DataFrame called 'yourdata' which looks something like</p> <pre><c...
0
2016-07-25T14:16:45Z
38,570,949
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow"><code>value_counts</code></a>, but first convert to dates by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="nofollow"><code>dt.date</code></...
0
2016-07-25T14:49:59Z
[ "python", "pandas", "dataframe" ]
Python pandas make new column from data in existing column and from another dataframe
38,570,198
<p>I have a DataFrame called 'mydata', and if I do</p> <pre><code>len(mydata.loc['2015-9-2']) </code></pre> <p>It counts the number of rows in mydata that have that date, and returns a number like</p> <pre><code>1067 </code></pre> <p>I have another DataFrame called 'yourdata' which looks something like</p> <pre><c...
0
2016-07-25T14:16:45Z
38,571,006
<pre><code>import numpy as np import pandas as pd mydata = pd.DataFrame({'timestamp': ['2015-06-22 16:48:00']*3 + ['2015-06-23 16:48:00']*2 + ['2015-06-24 16:48:00'] + ['2015-06-25 16:48:00']*4 + ...
1
2016-07-25T14:52:14Z
[ "python", "pandas", "dataframe" ]
How to get django queryset results with formatted datetime field
38,570,258
<p>I've Django model which has foreign keys associated with other models. Each model is having same field names(attributes) created_at and updated_at</p> <p>In every django queryset results I'll be getting datetime values.</p> <pre><code>Model.objects.all().values('created_at') </code></pre> <p>But I want to format ...
0
2016-07-25T14:19:06Z
38,570,415
<p>I don't think <code>values()</code> function would anything related to formatting datetime result. But why does that bother you? Can't you convert them to proper format when you try to display them? If you try to render them in the template, django has template filter <code>date</code> for formatting your datetime v...
0
2016-07-25T14:26:50Z
[ "python", "django", "datetime", "django-models" ]
How to get django queryset results with formatted datetime field
38,570,258
<p>I've Django model which has foreign keys associated with other models. Each model is having same field names(attributes) created_at and updated_at</p> <p>In every django queryset results I'll be getting datetime values.</p> <pre><code>Model.objects.all().values('created_at') </code></pre> <p>But I want to format ...
0
2016-07-25T14:19:06Z
38,582,438
<p>Got the solution.</p> <pre><code>data = list(Model.objects.extra(select={'date':"to_char(&lt;DATABASENAME&gt;_&lt;TableName&gt;.created_at, 'YYYY-MM-DD hh:mi AM')"}).values_list('date', flat='true') </code></pre> <p>It's not just tablename.attribute, it should be dbname_tablename.attribute when we have multiple da...
0
2016-07-26T06:25:57Z
[ "python", "django", "datetime", "django-models" ]
How to get django queryset results with formatted datetime field
38,570,258
<p>I've Django model which has foreign keys associated with other models. Each model is having same field names(attributes) created_at and updated_at</p> <p>In every django queryset results I'll be getting datetime values.</p> <pre><code>Model.objects.all().values('created_at') </code></pre> <p>But I want to format ...
0
2016-07-25T14:19:06Z
38,606,717
<p>Perhaps I misunderstood your question, but why not use something like <code>&lt;datetime_object&gt;.strftime('%d-%m-%Y %H:%M:%S')</code>?</p>
0
2016-07-27T07:39:05Z
[ "python", "django", "datetime", "django-models" ]
Python/Pandas - partitioning a pandas DataFrame in 10 disjoint, equally-sized subsets
38,570,268
<p>I want to partition a pandas DataFrame into ten disjoint, equally-sized, randomly composed subsets. </p> <p>I know I can randomly sample one tenth of the original pandas DataFrame using:</p> <pre><code>partition_1 = pandas.DataFrame.sample(frac=(1/10)) </code></pre> <p>However, how can I obtain the other nine par...
0
2016-07-25T14:19:25Z
38,570,355
<p>use <code>np.random.permutations</code> :</p> <p><code>df.loc[np.random.permutation(df.index)]</code> </p> <p>it will shuffle the dataframe and keep column names, after you could split the dataframe into 10.</p>
0
2016-07-25T14:23:38Z
[ "python", "python-2.7", "pandas", "dataframe", "partitioning" ]
Python/Pandas - partitioning a pandas DataFrame in 10 disjoint, equally-sized subsets
38,570,268
<p>I want to partition a pandas DataFrame into ten disjoint, equally-sized, randomly composed subsets. </p> <p>I know I can randomly sample one tenth of the original pandas DataFrame using:</p> <pre><code>partition_1 = pandas.DataFrame.sample(frac=(1/10)) </code></pre> <p>However, how can I obtain the other nine par...
0
2016-07-25T14:19:25Z
38,570,791
<p>Say <code>df</code> is your dataframe, and you want <code>N_PARTITIONS</code> partitions of roughly equal size (they will be of <em>exactly</em> equal size if <code>len(df)</code> is divisible by <code>N_PARTITIONS</code>).</p> <p>Use <code>np.random.permutation</code> to permute the array <code>np.arange(len(df))<...
0
2016-07-25T14:42:59Z
[ "python", "python-2.7", "pandas", "dataframe", "partitioning" ]
Python/Pandas - partitioning a pandas DataFrame in 10 disjoint, equally-sized subsets
38,570,268
<p>I want to partition a pandas DataFrame into ten disjoint, equally-sized, randomly composed subsets. </p> <p>I know I can randomly sample one tenth of the original pandas DataFrame using:</p> <pre><code>partition_1 = pandas.DataFrame.sample(frac=(1/10)) </code></pre> <p>However, how can I obtain the other nine par...
0
2016-07-25T14:19:25Z
38,571,305
<p>Starting with this.</p> <pre><code> dfm = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo']*2, 'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three']*2}) A B 0 foo one 1 bar one 2 foo two 3 bar three 4 foo two 5 bar ...
0
2016-07-25T15:05:26Z
[ "python", "python-2.7", "pandas", "dataframe", "partitioning" ]
How to extract specific words from a list as the list length changes?
38,570,487
<p>Let's assume that I have a sample of the following strings:</p> <ul> <li>string = 'http/1.1 <strong>abc-ad-sd-00</strong>.sad.sdsd.der.net (Server/1.2 [dsddsf did:t yy p sS]), http/1.1 <strong>asc-ad-sd-11</strong>.sad.sdsd.der.net (Server/1.2 [<strong>gfef srFw:t reri pSs</strong> ])'</li> <li>string1 = 'http/1.1 ...
0
2016-07-25T14:29:44Z
38,570,923
<p>I think regular expressions are your friend here. Something like <code>http\/1\.1 ([^\.]+)</code> works for this specific case.</p> <pre><code>import re match = re.compile('http\/1\.1 ([^\.]+)').search(string) value = match.group(1) </code></pre> <p>I would recommend splitting the strings with <code>string.split('...
0
2016-07-25T14:48:44Z
[ "python", "string", "parsing" ]
How to extract specific words from a list as the list length changes?
38,570,487
<p>Let's assume that I have a sample of the following strings:</p> <ul> <li>string = 'http/1.1 <strong>abc-ad-sd-00</strong>.sad.sdsd.der.net (Server/1.2 [dsddsf did:t yy p sS]), http/1.1 <strong>asc-ad-sd-11</strong>.sad.sdsd.der.net (Server/1.2 [<strong>gfef srFw:t reri pSs</strong> ])'</li> <li>string1 = 'http/1.1 ...
0
2016-07-25T14:29:44Z
38,570,998
<p>in my opinionm you can use regex to get substring. </p> <pre><code>import re pattern1 = r'\w+-\w+-\w+-\d+' pattern2 = r'\[tttts .+\]' #s is string you are checking #pattern 1 will find substring like abc-ad-sd-00 re.findall(pattern1,s) #pattern 2 will find substring like [tttts as t srFw:t reri pSs ] re.findall(pa...
0
2016-07-25T14:51:58Z
[ "python", "string", "parsing" ]
How to extract specific words from a list as the list length changes?
38,570,487
<p>Let's assume that I have a sample of the following strings:</p> <ul> <li>string = 'http/1.1 <strong>abc-ad-sd-00</strong>.sad.sdsd.der.net (Server/1.2 [dsddsf did:t yy p sS]), http/1.1 <strong>asc-ad-sd-11</strong>.sad.sdsd.der.net (Server/1.2 [<strong>gfef srFw:t reri pSs</strong> ])'</li> <li>string1 = 'http/1.1 ...
0
2016-07-25T14:29:44Z
38,571,019
<p>As you are working with a lot of text, then first thing to do is use/create an efficient memory-fiendly iterator over the strings. (let's assume you put it into function line_iterator)</p> <p>The second thing to do is use a regular expression for getting the required parts of strings (assume you written and compile...
0
2016-07-25T14:52:45Z
[ "python", "string", "parsing" ]
How to extract specific words from a list as the list length changes?
38,570,487
<p>Let's assume that I have a sample of the following strings:</p> <ul> <li>string = 'http/1.1 <strong>abc-ad-sd-00</strong>.sad.sdsd.der.net (Server/1.2 [dsddsf did:t yy p sS]), http/1.1 <strong>asc-ad-sd-11</strong>.sad.sdsd.der.net (Server/1.2 [<strong>gfef srFw:t reri pSs</strong> ])'</li> <li>string1 = 'http/1.1 ...
0
2016-07-25T14:29:44Z
38,571,155
<p>Checkout <a href="https://docs.python.org/2/library/re.html" rel="nofollow">positive lookbehind regular expression</a>. </p> <pre><code>import re p = """string = 'http/1.1 abc-ad-sd-00.sad.sdsd.der.net (Server/1.2 [dsddsf did:t yy p sS]), http/1.1 asc-ad-sd-11.sad.sdsd.der.net (Server/1.2 [tttts srFw:t reri pSs ])...
0
2016-07-25T14:58:58Z
[ "python", "string", "parsing" ]
How to extract specific words from a list as the list length changes?
38,570,487
<p>Let's assume that I have a sample of the following strings:</p> <ul> <li>string = 'http/1.1 <strong>abc-ad-sd-00</strong>.sad.sdsd.der.net (Server/1.2 [dsddsf did:t yy p sS]), http/1.1 <strong>asc-ad-sd-11</strong>.sad.sdsd.der.net (Server/1.2 [<strong>gfef srFw:t reri pSs</strong> ])'</li> <li>string1 = 'http/1.1 ...
0
2016-07-25T14:29:44Z
38,571,617
<p>Using regex you can compile an expression before your loop and get each id you want from each string as you loop over them. The first regex will get the first two ids which have the same format. <code>\w+</code> looks for at least one word and <code>\d+</code> looks for at least one digit. The second expression want...
0
2016-07-25T15:19:49Z
[ "python", "string", "parsing" ]
Advice on structuring a growing Django project (Models & API)
38,570,535
<p>I’m currently working on improving a Django project that is used internally at my company. The project is growing quickly so I’m trying to make some design choices now before it’s unmanageable to refactor. Right now the project has a two really important models the rest of the data in the database that support...
0
2016-07-25T14:31:34Z
38,571,117
<blockquote> <p>Would there be a distinct advantage in building models for all the tables that are populated via ETL processes so I can start using the Django ORM vs using SQLAlchemy and query strings?</p> </blockquote> <p>Yes, a centralized, consistent way of accessing the data, and of course, one less dependen...
2
2016-07-25T14:56:58Z
[ "python", "django", "django-rest-framework" ]
Advice on structuring a growing Django project (Models & API)
38,570,535
<p>I’m currently working on improving a Django project that is used internally at my company. The project is growing quickly so I’m trying to make some design choices now before it’s unmanageable to refactor. Right now the project has a two really important models the rest of the data in the database that support...
0
2016-07-25T14:31:34Z
39,083,902
<p>I would second @Av4t4r 's statement that building models for 'legacy' columns enforces:</p> <blockquote> <p>"a centralized, consistent way of accessing the data, and of course, one less dependency on the project."</p> </blockquote> <p>Additionally, this also allows you to define methods on your models to provide...
0
2016-08-22T15:55:38Z
[ "python", "django", "django-rest-framework" ]
Advice on structuring a growing Django project (Models & API)
38,570,535
<p>I’m currently working on improving a Django project that is used internally at my company. The project is growing quickly so I’m trying to make some design choices now before it’s unmanageable to refactor. Right now the project has a two really important models the rest of the data in the database that support...
0
2016-07-25T14:31:34Z
39,084,030
<p>I'm usually a huge proponent for DRF. It's simple to implement an easy use case, yet INCREDIBLY powerful for more complex uses. </p> <p>However, if you are not using Django models for all your data, I think JsonResponse might be easier. Running queries and manual manipulation (especially if it is only a single endp...
0
2016-08-22T16:02:57Z
[ "python", "django", "django-rest-framework" ]
Custom format ID mapping
38,570,743
<p>I have two databases (txt files). One is a two-column, tab-delimited one, that holds names and IDs.</p> <pre><code>name1 \t ID1 name1 \t ID2 name2 \t ID9 name2 \t ID40 name3 \t ID3 </code></pre> <p>The other database has the same IDs as the first one in the first column, while the second column lists IDs of the sa...
0
2016-07-25T14:40:57Z
38,572,013
<pre><code>import csv # Reading the first db is simple since there's only a fixed delimiter # Use csv module to split the lines and create a dictionary that maps id to name id_dictionary = {} with open('db_1.txt', 'r') as infile: reader = csv.reader(infile, delimiter='\t') for line in reader: id_dicti...
0
2016-07-25T15:37:46Z
[ "python", "bash" ]
Custom format ID mapping
38,570,743
<p>I have two databases (txt files). One is a two-column, tab-delimited one, that holds names and IDs.</p> <pre><code>name1 \t ID1 name1 \t ID2 name2 \t ID9 name2 \t ID40 name3 \t ID3 </code></pre> <p>The other database has the same IDs as the first one in the first column, while the second column lists IDs of the sa...
0
2016-07-25T14:40:57Z
38,572,556
<p>You can try this one line awk script:</p> <pre><code>awk -v FS="\t|," -v OFS="," 'FILENAME=="file_name.txt" {str[$2]=$1;next;} {for(i=2;i&lt;=NF;i++) {sub($i,str[$i],$i)};a=$1;$1="";print a"\t"$0}' file_name.txt fileID.txt|sed -e 's/,//' -e 's/,$//' </code></pre> <p>The "file_name.txt" for the awk is the txt file ...
0
2016-07-25T16:04:15Z
[ "python", "bash" ]
Custom format ID mapping
38,570,743
<p>I have two databases (txt files). One is a two-column, tab-delimited one, that holds names and IDs.</p> <pre><code>name1 \t ID1 name1 \t ID2 name2 \t ID9 name2 \t ID40 name3 \t ID3 </code></pre> <p>The other database has the same IDs as the first one in the first column, while the second column lists IDs of the sa...
0
2016-07-25T14:40:57Z
38,572,658
<pre><code>#suppose database files are f1.txt,f2.txt,f3.txt #use set to get key-value format datas def getArr(f): i=f.readline() arr=[] while i: i=i.replace('\n','') arr.append(i.split('\t')) i=f.readline() return arr if __name__=="__main__": f1=file("f1.txt") f2=file("f2...
0
2016-07-25T16:09:31Z
[ "python", "bash" ]
Best python way to return the initializing value of class if of that same class
38,570,919
<p>I have a class that I want it to accept an instance of that same class as initialization; in such case, it will simply return that instance.</p> <p>The reason is that I want this class to accept a myriad of initialization values and then the proceeding code can use this as an object with known properties, independe...
1
2016-07-25T14:48:37Z
38,571,749
<p>You probably want to use a factory (f.e. see this <a href="http://stackoverflow.com/questions/674304/pythons-use-of-new-and-init">question</a> for details or google). Or just use a class method for what you want, f.e.:</p> <pre><code>class C(object): @classmethod def new(cls, *args, **kwargs): if is...
1
2016-07-25T15:25:22Z
[ "python", "class", "oop", "initialization" ]
Best python way to return the initializing value of class if of that same class
38,570,919
<p>I have a class that I want it to accept an instance of that same class as initialization; in such case, it will simply return that instance.</p> <p>The reason is that I want this class to accept a myriad of initialization values and then the proceeding code can use this as an object with known properties, independe...
1
2016-07-25T14:48:37Z
38,572,240
<p>You can use a metaclass</p> <pre><code>class InstanceReturnMeta(type): # You should probably think of a better name def __call__(cls, *args, **kwargs): if args and isinstance(args[0], cls): return args[0] instance = cls.__new__(cls, *args, **kwargs) instance.__init__(*args, ...
1
2016-07-25T15:47:26Z
[ "python", "class", "oop", "initialization" ]
Best python way to return the initializing value of class if of that same class
38,570,919
<p>I have a class that I want it to accept an instance of that same class as initialization; in such case, it will simply return that instance.</p> <p>The reason is that I want this class to accept a myriad of initialization values and then the proceeding code can use this as an object with known properties, independe...
1
2016-07-25T14:48:37Z
38,572,327
<p>The standard way to do this is to simply not do your initialization in <code>__init__</code>. Do it in <code>__new__</code>.</p>
1
2016-07-25T15:52:47Z
[ "python", "class", "oop", "initialization" ]
Python: Find the total weights of a subgraph's outside edges
38,570,986
<p>I'm using python-igraph to extract a subgraph from a non-directed graph. Nodes are locations, and the subgraph represents all nodes/edges within a radius from a certain node. </p> <p>I need to find the weights that connect the outside nodes of the subgraph to the main graph, is there any simple way of doing this? I...
0
2016-07-25T14:51:35Z
38,731,159
<p>This is basically the total weight of the cut between your chosen set of nodes and the rest of the graph. You can try something like this:</p> <pre><code>your_nodes = [1, 2, 3] other_nodes = sorted(set(range(graph.vcount())) - set(your_nodes)) weight_of_cut = sum(graph.es.select(_between=(your_nodes, other_nodes))[...
0
2016-08-02T21:57:51Z
[ "python", "graph", "igraph" ]
Using Stanford CoreNLP Python Parser for specific output
38,571,004
<p>I'm using <a href="https://github.com/dasmith/stanford-corenlp-python" rel="nofollow">SCP</a> to get the parse CFG tree for English sentences. </p> <pre><code>from corenlp import * corenlp = StanfordCoreNLP() corenlp.parse("Every cat loves a dog") </code></pre> <p>My expected output is a tree like this: </p> <pre...
0
2016-07-25T14:52:07Z
38,571,865
<p>You can use <a href="http://www.nltk.org/howto/tree.html" rel="nofollow">nltk.tree</a> module from <a href="http://www.nltk.org/" rel="nofollow">NLTK</a>.</p> <pre><code>from nltk.tree import * def traverse(t): try: # Replace Labels if t.label() == "DT": t.set_label("DET") e...
1
2016-07-25T15:30:47Z
[ "python", "nlp", "stanford-nlp", "pos-tagger", "corenlp" ]
django- Use prefetch_related inside of another prefetch_related
38,571,076
<p>Closest thing to what I am asking can be found <a href="https://stackoverflow.com/questions/13092268/how-do-you-join-two-tables-on-a-foreign-key-field-using-django-orm">here</a></p> <p>Say I have the following models:</p> <pre><code>class Division(models.Model): name = models.TextField() state = models.Int...
1
2016-07-25T14:54:55Z
38,571,599
<p>You don't need <code>prefetch_related</code> here. You can follow the foreign keys from <code>Player</code> to <code>Team</code> to <code>Division</code> using <a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/#select-related" rel="nofollow"><code>select_related()</code></a>.</p> <pre><code>player...
2
2016-07-25T15:18:45Z
[ "python", "django", "django-templates", "django-views", "django-queryset" ]
Django: One-to-many relation for [0, 1] cardinality
38,571,157
<p>Imagine having two models:</p> <pre><code>class Service(models.Model): key_service_name = models.ForeignKey(Key_service_type, related_name='Service_key_service_names', null=False) service_hourly_wage_rate = models.DecimalField(max_digits=5, decimal_places=2, null=True) service_amount = models.DecimalField(max...
1
2016-07-25T14:59:22Z
38,601,758
<p>Replace your foreign key with a <a href="https://docs.djangoproject.com/en/1.9/topics/db/examples/one_to_one/" rel="nofollow">OneToOneField</a></p> <blockquote> <p>A one-to-one relationship. Conceptually, this is similar to a ForeignKey with unique=True, but the “reverse” side of the relation will directl...
1
2016-07-27T00:07:21Z
[ "python", "django", "django-models", "data-modeling" ]
How to deliberately build bad URL with url_for() in unit tests?
38,571,192
<p>Im writing unit tests for an API written in Python with Flask. Specifically, I want to test that the error handling for my routes work properly so I want to deliberately build URLs with missing parameters. I want to avoid hard-coding by using url_for() but that doesn't allow you to have missing parameters, so how to...
0
2016-07-25T15:00:57Z
38,578,033
<p>When it comes to <code>url_for</code> it generates two kinds of urls. If there are named routes, like</p> <pre><code>@app.route('/favorite/color/&lt;color&gt;') def favorite_color(color): return color[::-1] </code></pre> <p>Then the URL parameters are <strong>required</strong>:</p> <pre><code>url_for('favorit...
2
2016-07-25T21:56:08Z
[ "python", "unit-testing", "url", "flask" ]
Python 3 - number of letters in an encoded string
38,571,273
<p>I would like to get the number of letters in a given string. However, len(txt) returns the number of letters in the unicode form (I guess), but the actual number of letters is less then what I get.</p> <p>for example:</p> <pre><code>txt = שלום וברכה len(txt) # returns something different then 10 </code>...
-1
2016-07-25T15:04:03Z
38,573,093
<p>Probably, you are opening the file with the wrong encoding scheme, here is a demonstration:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.version '3.4.3 (default, Oct 14 2015, 20:28:29) \n[GCC 4.8.4]' &gt;&gt;&gt; &gt;&gt;&gt; s = '╫¬╫ñ╫¿╫ש╫ר ╫£╫ª╫ץ╫¥: ╫¢╫ת ╫¬╫ª╫Â...
0
2016-07-25T16:32:33Z
[ "python", "character-encoding", "python-3.4", "hebrew" ]
Mapping Window Drives Python: How to handle when the Win cmd Line needs input
38,571,274
<p>Good Afternoon,</p> <p>I used a version of this method to map a dozen drive letters:</p> <pre><code># Drive letter: M # Shared drive path: \\shared\folder # Username: user123 # Password: password import subprocess # Disconnect anything on M subprocess.call(r'net use * /del', shell=True) # Connect to shared drive...
1
2016-07-25T15:04:05Z
38,571,335
<p>To force disconnecting try it with <code>/yes</code> like so</p> <pre><code>subprocess.call(r'net use * /del /yes', shell=True) </code></pre> <hr> <p>In order to 'redirect' the question to the user you have (at least) 2 possible approaches: </p> <ul> <li>Read and write to the standard input / output stream of...
0
2016-07-25T15:06:59Z
[ "python", "subprocess", "net-use" ]
Django: reload variable's value in the template
38,571,334
<p>Imagine there is a Django HTML-template with a variable <code>foo</code>:</p> <pre><code>&lt;div&gt; {{ foo }} &lt;/div&gt; </code></pre> <p>Is it possible to reload <code>foo</code>'s value somehow without API call and without page reload?</p>
-1
2016-07-25T15:06:57Z
38,703,715
<p>After searching for an answer, I came to conclusion there is no way to update it without page reload or API-call. So, the solution is to change the approach.</p>
0
2016-08-01T16:26:56Z
[ "python", "django" ]
Python shell call to exiftool
38,571,336
<p>I have an image, 1.tiff, from which I want to copy the exif data to two other images, 2.tiff and 3.tiff. from the normal shell I can write the same exif data to multiple images by typing</p> <pre><code>exiftool -m -overwrite_original -TagsFromFile "1.tiff" {"2.tiff","3.tiff"} </code></pre> <p>For some reason, I am...
0
2016-07-25T15:07:03Z
38,571,478
<p><code>os.system</code> tends to act up like that, especially on Windows. You'll probably have more success with <a href="https://docs.python.org/2/library/subprocess.html#subprocess.call" rel="nofollow"><code>subprocess.call</code></a>:</p> <pre><code>subprocess.call(['exiftool','-m','-overwrite_original','-TagsFro...
1
2016-07-25T15:13:22Z
[ "python", "shell", "exiftool" ]
Python shell call to exiftool
38,571,336
<p>I have an image, 1.tiff, from which I want to copy the exif data to two other images, 2.tiff and 3.tiff. from the normal shell I can write the same exif data to multiple images by typing</p> <pre><code>exiftool -m -overwrite_original -TagsFromFile "1.tiff" {"2.tiff","3.tiff"} </code></pre> <p>For some reason, I am...
0
2016-07-25T15:07:03Z
38,571,580
<p>If your only purpose is to use exiftool in python then why not use <a href="https://smarnach.github.io/pyexiftool/" rel="nofollow">this module</a>? Sorry I do not have enough reputation to post comments yet. For example:</p> <pre><code> import exiftool files = ["a.jpg", "b.png", "c.tif"] with exiftool.ExifTool()...
0
2016-07-25T15:18:10Z
[ "python", "shell", "exiftool" ]
Python shell call to exiftool
38,571,336
<p>I have an image, 1.tiff, from which I want to copy the exif data to two other images, 2.tiff and 3.tiff. from the normal shell I can write the same exif data to multiple images by typing</p> <pre><code>exiftool -m -overwrite_original -TagsFromFile "1.tiff" {"2.tiff","3.tiff"} </code></pre> <p>For some reason, I am...
0
2016-07-25T15:07:03Z
38,572,429
<p>Inspired by <a href="http://stackoverflow.com/questions/22659579/curly-braces-in-python-popen">this</a> question and Rawing answer, the problem seems to be that /bin/sh that doesn't support this curly braces. The solution therefore is to set executable='/bin/bash' in subprocess.Popen</p> <pre><code>subprocess.Popen...
0
2016-07-25T15:57:41Z
[ "python", "shell", "exiftool" ]
Pandas Dataframe: How to parse integers into string of 0s and 1s?
38,571,348
<p>I have the following pandas DataFrame.</p> <pre><code>import pandas as pd df = pd.read_csv('filename.csv') print(df) sample column_A 0 sample1 6/6 1 sample2 0/4 2 sample3 2/6 3 sample4 12/14 4 sample5 15/21 5 sample6 ...
4
2016-07-25T15:07:26Z
38,571,544
<p>First, suppose you write a function:</p> <pre><code>def to_binary(s): n_d = s.split('/') n, d = int(n_d[0]), int(n_d[1]) return '1' * n + '0' * (d - n) </code></pre> <p>So that, </p> <pre><code>&gt;&gt;&gt; to_binary('4/5') '11110' </code></pre> <p>Now you just need to use <a href="http://pandas.pyda...
6
2016-07-25T15:16:12Z
[ "python", "regex", "parsing", "pandas" ]
Pandas Dataframe: How to parse integers into string of 0s and 1s?
38,571,348
<p>I have the following pandas DataFrame.</p> <pre><code>import pandas as pd df = pd.read_csv('filename.csv') print(df) sample column_A 0 sample1 6/6 1 sample2 0/4 2 sample3 2/6 3 sample4 12/14 4 sample5 15/21 5 sample6 ...
4
2016-07-25T15:07:26Z
38,571,969
<p>An alternative:</p> <pre><code>df2 = df['column_A'].str.split('/', expand=True).astype(int)\ .assign(ones='1').assign(zeros='0') df2 Out: 0 1 ones zeros 0 6 6 1 0 1 0 4 1 0 2 2 6 1 0 3 12 14 1 0 4 15 21 1 0 5 12 12 1 0 (df2[0] ...
4
2016-07-25T15:35:17Z
[ "python", "regex", "parsing", "pandas" ]
Pandas Dataframe: How to parse integers into string of 0s and 1s?
38,571,348
<p>I have the following pandas DataFrame.</p> <pre><code>import pandas as pd df = pd.read_csv('filename.csv') print(df) sample column_A 0 sample1 6/6 1 sample2 0/4 2 sample3 2/6 3 sample4 12/14 4 sample5 15/21 5 sample6 ...
4
2016-07-25T15:07:26Z
38,574,873
<p>Here are some alternative solutions using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow">extract()</a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.repeat.html" rel="nofollow">.str.repeat()</a> methods:</p> <pre><...
1
2016-07-25T18:20:21Z
[ "python", "regex", "parsing", "pandas" ]
Python3 Tkinter - Write input (y) to console for subprocess
38,571,439
<p>I've been looking around for an answer to my problem but have been unlucky. I would like for the answer to work with native python and hopefully be simple.</p> <p>My problem is that I'm using subprocess in my tkinter application, but one of the commands require you to write Y/N to be sure you want to proceed with t...
0
2016-07-25T15:12:06Z
38,571,880
<p>Many command line utilities have a flag that automatically answers yes to any prompts - if you have access to the source code of your particular command, adding such a flag if it doesn't have one (or simply making a custom version that never prompts) may be the easiest solution. Some commands automatically do this ...
0
2016-07-25T15:31:38Z
[ "python", "linux", "python-3.x", "input", "tkinter" ]
migrate python code to NodeJS
38,571,483
<p>I am a beginner in NodeJS. I have worked on some scripts in python which does some calculation on two csvs. Is there a easy way to migrate a python script to NodeJS? I don't know whether its a right way to do it. But I wanted to know is there any way for for it.</p> <p>Any suggestions will be encouragable. </p>
0
2016-07-25T15:13:36Z
38,571,665
<p><strong>Simple way :</strong> understand your code and rewrite it in <em>node.js</em> format.</p> <p>If you're a beginner in <em>node.js</em>, it's a good exercise to understand how <em>node.js</em> works.</p> <p>I recommand you this post which regroup a lot of ressources to begin <em>node.js</em> : <a href="http:...
0
2016-07-25T15:21:55Z
[ "python", "node.js" ]
migrate python code to NodeJS
38,571,483
<p>I am a beginner in NodeJS. I have worked on some scripts in python which does some calculation on two csvs. Is there a easy way to migrate a python script to NodeJS? I don't know whether its a right way to do it. But I wanted to know is there any way for for it.</p> <p>Any suggestions will be encouragable. </p>
0
2016-07-25T15:13:36Z
38,571,696
<p>If you simply want to convert the code to javascript there are tools available like <a href="http://www.transcrypt.org/" rel="nofollow">transcrypt</a> which converts the python code to javascript.</p>
2
2016-07-25T15:23:10Z
[ "python", "node.js" ]
The Concept Behind itertools's product Function
38,571,501
<p>so basically i want to understand the concept of product() function in itertools. i mean what is the different between yield and return. And can this code be shorten down anyway.</p> <pre><code> def product1(*args, **kwds): pools = map(tuple, args) * kwds.get('repeat', 1) n = len(pools) i...
-5
2016-07-25T15:14:13Z
38,571,626
<p>I would highly recommend using the well established and tested <code>itertools</code> <a href="https://docs.python.org/2/library/itertools.html#itertools.product" rel="nofollow">standard module</a>. Reinventing the wheel is never <em>advisable</em> as a programmer. That said, I would start by taking a look at the <c...
2
2016-07-25T15:20:04Z
[ "python", "recursion", "itertools" ]
The Concept Behind itertools's product Function
38,571,501
<p>so basically i want to understand the concept of product() function in itertools. i mean what is the different between yield and return. And can this code be shorten down anyway.</p> <pre><code> def product1(*args, **kwds): pools = map(tuple, args) * kwds.get('repeat', 1) n = len(pools) i...
-5
2016-07-25T15:14:13Z
38,571,978
<p>This code should do the work:</p> <pre><code>bytes = [i for i in range(2**(n))] AB= [] for obj in bytes: t = str(bin(obj))[2:] t= '0'*(n-len(t)) + t AB.append(t.replace('0','A').replace('1','B')) </code></pre> <p>n being the string size wanted</p>
1
2016-07-25T15:35:51Z
[ "python", "recursion", "itertools" ]
The Concept Behind itertools's product Function
38,571,501
<p>so basically i want to understand the concept of product() function in itertools. i mean what is the different between yield and return. And can this code be shorten down anyway.</p> <pre><code> def product1(*args, **kwds): pools = map(tuple, args) * kwds.get('repeat', 1) n = len(pools) i...
-5
2016-07-25T15:14:13Z
38,573,018
<p>First create a list with all the possible arrangements, that's easily achievable by summing binaries:</p> <pre><code>def generate_arrangements(n): return [bin(i)[2:].zfill(n) for i in range(2**n)] # 2**n is number of possible options (A,B) n times </code></pre> <p>The [2:] slices the string and remove '0b' fr...
0
2016-07-25T16:28:29Z
[ "python", "recursion", "itertools" ]
Python requests function: url formatting unexpected ascii output
38,571,534
<p>I am getting unexpected ASCII characters while using the <code>requests</code> library in Python 3. </p> <pre><code>search_terms = ["ö", "é", "ä"] url = "http://www.domain.com/search" for i in search_terms: r = requests.get(url, i) </code></pre> <p>Which returns:</p> <pre><code>http://www.domain.com/searc...
0
2016-07-25T15:15:37Z
38,571,982
<p>I assume that requests first encode the unicode strings as utf-8 and then quote them.</p> <pre><code>&gt;&gt;&gt; urllib.quote(u'ö'.encode('utf-8')) %C3%B6 </code></pre>
0
2016-07-25T15:36:07Z
[ "python", "python-requests" ]
Python requests function: url formatting unexpected ascii output
38,571,534
<p>I am getting unexpected ASCII characters while using the <code>requests</code> library in Python 3. </p> <pre><code>search_terms = ["ö", "é", "ä"] url = "http://www.domain.com/search" for i in search_terms: r = requests.get(url, i) </code></pre> <p>Which returns:</p> <pre><code>http://www.domain.com/searc...
0
2016-07-25T15:15:37Z
38,572,044
<p>That's because it's UTF-8 encoded.</p> <pre><code>&gt;&gt;&gt; u'ö'.encode() b'\xc3\xb6' &gt;&gt;&gt; u'é'.encode() b'\xc3\xa9' &gt;&gt;&gt; u'ä'.encode() b'\xc3\xa4' </code></pre> <p>What it seems you want is latin encoding. You can achieve it like this:</p> <pre><code># Python 3 &gt;&gt;&gt; from urllib.pars...
0
2016-07-25T15:39:02Z
[ "python", "python-requests" ]
Python requests function: url formatting unexpected ascii output
38,571,534
<p>I am getting unexpected ASCII characters while using the <code>requests</code> library in Python 3. </p> <pre><code>search_terms = ["ö", "é", "ä"] url = "http://www.domain.com/search" for i in search_terms: r = requests.get(url, i) </code></pre> <p>Which returns:</p> <pre><code>http://www.domain.com/searc...
0
2016-07-25T15:15:37Z
38,572,591
<p>I figured it out without any further import statements. I am using the <code>encode</code> method now.</p> <p>Old code:</p> <pre><code>for i in search_terms: r = requests.get(url, i) </code></pre> <p>New code:</p> <pre><code>for i in search_terms: r = requests.get(url, i.encode("iso-8859-1")) </code></pr...
0
2016-07-25T16:05:46Z
[ "python", "python-requests" ]
Using Python to download files from Box
38,571,667
<p>I'm trying to use Python to download an Excel file to my local drive from Box.</p> <p>Using the boxsdk I was able to authenticate via OAuth2 and successfully get the file id on Box.</p> <p>However when I use the <code>client.file(file_id).content()</code> function, it just returns a string, and if I use <code>clie...
0
2016-07-25T15:22:00Z
38,572,513
<p>You could use python <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">csv library</a>, along with dialect='excel' flag. It works really nice for exporting data to Microsoft Excel. The main idea is to use csv.writer inside a loop for writing each line. Try this and if you can't, post the code here...
0
2016-07-25T16:01:31Z
[ "python", "excel", "download", "box" ]
Repeating strings in pandas DF -- want to return list of unique strings
38,571,685
<p>I have a bunch of rows of data in a pandas DF that contain inconsistently offsetting string characters. For each Game ID (another column), the two string characters are unique to that Game ID, but do not switch off in a predicatble pattern. Regardless, I'm trying to write a helper function that takes each unique gam...
0
2016-07-25T15:22:33Z
38,571,805
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.unique.html" rel="nofollow"><code>SeriesGroupBy.unique</code></a>:</p> <pre><code>print (df.groupby('game_id')['team'].unique()) game_id 400827888 [ATL, DET] 400829117 [POR, DEN] Name: team, dtype: obj...
2
2016-07-25T15:27:38Z
[ "python", "pandas", "for-loop", "dataframe" ]
Python Import error while running through apache
38,571,690
<p>Actually I've included the python script inside CGI script with back-ticks. While i was running the script I have an error like "ImportError: No module named skimage" through apache web server. But when i run via command line it was working properly. </p> <p>OS: RHEL 6.5</p> <p>Python: 2.7.8</p> <p>$PYTHONPATH = ...
0
2016-07-25T15:22:55Z
38,574,305
<p>Maybe the library is installed only for you and not for root. Put the library script in the same folder of your main script and try. </p>
0
2016-07-25T17:46:27Z
[ "python", "apache", "cgi" ]
Evaluate statements from within Python logging YAML config file
38,571,701
<p>Consider the following snippet of a Python <code>logging</code> YAML config file:</p> <pre><code>version: 1 formatters: simple: format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' handlers: logfile: class: logging.handlers.TimedRotatingFileHandler level: DEBUG filename: some_fancy_imp...
1
2016-07-25T15:23:33Z
38,574,366
<p>You can add a custom constructor and mark the value with a special tag, so your constructor gets executed when loading it:</p> <pre><code>import yaml def eval_constructor(loader, node): return eval(loader.construct_scalar(node)) yaml.add_constructor(u'!eval', eval_constructor) some_value = '123' config = yaml...
1
2016-07-25T17:50:22Z
[ "python", "logging", "yaml" ]
Evaluate statements from within Python logging YAML config file
38,571,701
<p>Consider the following snippet of a Python <code>logging</code> YAML config file:</p> <pre><code>version: 1 formatters: simple: format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' handlers: logfile: class: logging.handlers.TimedRotatingFileHandler level: DEBUG filename: some_fancy_imp...
1
2016-07-25T15:23:33Z
38,591,392
<h1>Solution</h1> <p>Thanks to <a href="http://stackoverflow.com/a/38574366/366309">flyx's answer</a>, this is how I did it:</p> <pre><code>import logging import yaml from os import environ as env def constructor_logfilename(loader, node): value = loader.construct_scalar(node) return os.path.join(env.get('OP...
0
2016-07-26T13:35:11Z
[ "python", "logging", "yaml" ]
Split an numpy array into two numpy arrays
38,571,715
<p>I have a numpy array like this:</p> <pre><code>A=[(datetime.datetime(2016, 6, 8, 12, 37, 27, 826000), 3.0) (datetime.datetime(2016, 6, 8, 12, 37, 27, 827000), nan) (datetime.datetime(2016, 6, 8, 12, 37, 27, 832000), nan) (datetime.datetime(2016, 6, 8, 12, 37, 27, 833000), nan) (datetime.datetime(2016, 6...
0
2016-07-25T15:24:10Z
38,571,907
<p>If you just a have a vanilla array with <code>dtype=object</code>, I think your best recourse is to just construct the new arrays by iterating over the old one in a couple list-comprehensions:</p> <p>import numpy as np from numpy import nan import datetime</p> <pre><code>A=np.array([(datetime.datetime(2016, 6, 8, ...
1
2016-07-25T15:32:35Z
[ "python", "arrays", "datetime", "numpy" ]
Split an numpy array into two numpy arrays
38,571,715
<p>I have a numpy array like this:</p> <pre><code>A=[(datetime.datetime(2016, 6, 8, 12, 37, 27, 826000), 3.0) (datetime.datetime(2016, 6, 8, 12, 37, 27, 827000), nan) (datetime.datetime(2016, 6, 8, 12, 37, 27, 832000), nan) (datetime.datetime(2016, 6, 8, 12, 37, 27, 833000), nan) (datetime.datetime(2016, 6...
0
2016-07-25T15:24:10Z
38,572,024
<p>You likely want to slice the data. Inserting a <code>:</code> for that dimension will select all elements of that dimension.</p> <pre><code>B = A[:, 0] C = A[:, 1] </code></pre>
-1
2016-07-25T15:38:13Z
[ "python", "arrays", "datetime", "numpy" ]
How to separate stock picking in from out in odoo 8
38,571,757
<p>In openerp 7 stock_picking was separated in two items, stock_picking_in and stock_picking_out, now they created one item containing both and there's a field containing the type (in or out). I want to have the normal view for "in" items and a totally custom view for "out". Is it possible and how? Thanks.</p> <p>My p...
0
2016-07-25T15:25:58Z
38,582,642
<p>One way to achieve is to use <code>attrs</code> and based on picking type hide or show fields, if you want to make minor changes, for whole document its not a best solution.</p> <p>Second way is to create different views for them but only if you are using different menuitems for opening this objects, on the action ...
1
2016-07-26T06:37:58Z
[ "python", "xml", "openerp", "odoo-8" ]
How can I use "metrics.mutual_info" in scikit's feature.selection
38,571,783
<p>I would like to use other scoring functions then <code>chi2</code> etc., that are not listed on this page.</p> <p><a href="http://scikit-learn.org/stable/modules/feature_selection.html" rel="nofollow">http://scikit-learn.org/stable/modules/feature_selection.html</a></p> <p><a href="http://scikit-learn.org/stable/m...
1
2016-07-25T15:26:38Z
39,791,580
<p>The new scikit-learn version 0.18, has added support for Mutual information feature selection. So no need to use the <code>metrics.mutual_info</code>. You can use the new <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.mutual_info_classif.html" rel="nofollow">feature_selection.mut...
0
2016-09-30T12:29:56Z
[ "python", "machine-learning", "scikit-learn", "sentiment-analysis" ]
Run a command from Windows from Python code
38,571,814
<p>How can I run the following command from Python3 on Windows 7</p> <pre><code>gcc main.cpp -o main.out ./main.out </code></pre> <p>The purpose is to execute the main.cpp file from Python3.</p>
0
2016-07-25T15:28:06Z
38,572,035
<p>look <a href="https://docs.python.org/3/library/subprocess.html" rel="nofollow">subprocess call</a></p> <pre><code>import subprocess subprocess.run(["gcc", "main.cpp -o main.out"]) subprocess.run(["./main.out"]) </code></pre> <p>should work. But subprocess have more utilities that will be usefull for you.</p>
1
2016-07-25T15:38:46Z
[ "python", "c++", "windows" ]
python/django- number comparison (>) does not work
38,571,881
<p>This is really weird. I have a django program and I am calling this py file from views. The file will read from an excel and find the correct number index for a given number(target).</p> <p>It keeps telling me "Target Number out of Range" which it should not, so I print out the numbers. </p> <pre><code>for target ...
1
2016-07-25T15:31:41Z
38,572,273
<p>So as @Rawing mentioned in comments, I added </p> <p><code>print type(target), type(df[pin_num][end]), type(df[pin_num][0]) </code> </p> <p>and it showed target is a string. </p> <p>so I added :</p> <pre><code> target=float(target) </code></pre> <p>This solve my problem.</p>
0
2016-07-25T15:49:32Z
[ "python", "django" ]
How to add specific axes to matplotlib subplot?
38,571,905
<p>I am trying to make a matrix plot with matplotlib.</p> <p>The individual plots are made with a specific module <code>windrose</code> which subclasses <code>PolarAxes</code>. However there does not seem to be any projection defined in the module to be called as subplot kwargs. The standard <code>polar</code> project...
0
2016-07-25T15:32:32Z
38,586,528
<p>The github page from the <code>windrose</code> module actually provides an example of subplots: <a href="https://github.com/scls19fr/windrose/blob/master/samples/example_subplots.py" rel="nofollow">https://github.com/scls19fr/windrose/blob/master/samples/example_subplots.py</a>.</p> <p>The following works.</p> <pr...
0
2016-07-26T09:49:45Z
[ "python", "matplotlib", "subplot" ]
django rest framework: order of decorators, auth classes, dispatch to be called
38,572,049
<p>Very confused about the order of decorators, auth classes, dispatch to be called in djangorestframework. It seems that it is a little different from my django framework knowledge.</p> <p>Some codes:</p> <pre><code>#operation_logger: customized decorator class FileView(APIView): parser_classes = (MultiPartParse...
0
2016-07-25T15:39:13Z
38,573,691
<p>The <em>call</em> order is as you specified:</p> <ol> <li><code>@method_decorator(csrf_exempt)</code></li> <li><code>@method_decorator(operation_logger)</code> (#E)</li> <li><code>dispatch()</code> calls <code>initial()</code> which calls <code>check_permissions()</code> which evaluates <code>permission_classes</co...
0
2016-07-25T17:07:15Z
[ "python", "django", "django-rest-framework" ]
deploy flask application on ubuntu/apache2: virtual host configuration
38,572,059
<p>I'm trying to deploy a python/flask application on an apache2 installation on ubuntu (14.04), following the instructions at the <a href="https://www.digitalocean.com/community/tutorials/how-to-deploy-a-flask-application-on-an-ubuntu-vps" rel="nofollow">link</a></p> <p>The application seems to work and if I point th...
0
2016-07-25T15:39:46Z
38,572,394
<p>I think you missed that url in your controller. Perhaps you can add a index.html in FlaskApp folder to redirect to the correct url (or the other way around, if you leave ServerName mywebsite.com/FlaskApp, put an index file to redirect to FlaskApp). If index.html "hack" doesn't suit your needs, you may add another vi...
0
2016-07-25T15:55:57Z
[ "python", "apache", "ubuntu", "flask" ]
Python pandas - remove groups based on NaN count threshold
38,572,079
<p>I have a dataset based on different weather stations,</p> <pre><code>stationID | Time | Temperature | ... ----------+------+-------------+------- 123 | 1 | 30 | 123 | 2 | 31 | 202 | 1 | 24 | 202 | 2 | 24.3 | 202 | 3 | NaN | ... <...
1
2016-07-25T15:40:34Z
38,572,196
<p>IIUC you can do <code>df2.loc[df2.groupby('station')['Temperature'].filter(lambda x: len(x[pd.isnull(x)] ) &lt; 30).index]</code></p> <p>Example:</p> <pre><code>In [59]: df = pd.DataFrame({'id':[0,0,0,1,1,1,2,2,2,2], 'val':[1,1,np.nan,1,np.nan,np.nan, 1,1,1,1]}) df Out[59]: id val 0 0 1.0 1 0 1.0 2 0...
1
2016-07-25T15:45:34Z
[ "python", "pandas" ]
Python pandas - remove groups based on NaN count threshold
38,572,079
<p>I have a dataset based on different weather stations,</p> <pre><code>stationID | Time | Temperature | ... ----------+------+-------------+------- 123 | 1 | 30 | 123 | 2 | 31 | 202 | 1 | 24 | 202 | 2 | 24.3 | 202 | 3 | NaN | ... <...
1
2016-07-25T15:40:34Z
38,572,311
<p>You can create a column to give the the number of null values by station_id, and then use <code>loc</code> to select the relevant data for further processing.</p> <pre><code>df['station_id_null_count'] = \ df.groupby('stationID').Temperature.transform(lambda group: group.isnull().sum()) df.loc[df.station_id_nul...
0
2016-07-25T15:52:01Z
[ "python", "pandas" ]
Python pandas - remove groups based on NaN count threshold
38,572,079
<p>I have a dataset based on different weather stations,</p> <pre><code>stationID | Time | Temperature | ... ----------+------+-------------+------- 123 | 1 | 30 | 123 | 2 | 31 | 202 | 1 | 24 | 202 | 2 | 24.3 | 202 | 3 | NaN | ... <...
1
2016-07-25T15:40:34Z
38,573,238
<p>Using @EdChum setup: Since you dont mention your final output, adding this.</p> <pre><code> vals = df.groupby(['id'])['val'].apply(lambda x: (np.size(x)-x.count()) &lt; 2 ) vals[vals] id 0 True 2 True Name: val, dtype: bool </code></pre>
0
2016-07-25T16:39:52Z
[ "python", "pandas" ]
Redefining indexing in N-dimensional arrays
38,572,189
<p>So I have a N-dimensional array of values, let's call it A. Now, I can plot this in a contour map, with coordinate axes X and Y, using</p> <pre><code>plt.contourf(X,Y,A) </code></pre> <p>Now, I have to carry out a mapping of these points to another plane, so, basically another set of coordinates. Let the transform...
2
2016-07-25T15:45:07Z
38,691,159
<p>A friend helped me out with this. Seems to work perfectly.</p> <pre><code> for ii in xrange(A.shape[1]): for jj in xrange(A.shape[0]): H = ii - alpha_x[jj,ii] J = jj - alpha_y[jj,ii] if H &gt;= 0 and H&lt;= A.shape[1] and J &gt;= 0 and J &lt;= A.shape[0]: ...
0
2016-08-01T04:43:48Z
[ "python", "arrays", "numpy", "matplotlib", "indexing" ]
Flask 404 Page Not Rendering Template
38,572,231
<p>I'm trying to figure out why my 404 page template will not render correctly. I am able to get it to return text, but not a template. Here is my error handler function that doesn't work:</p> <pre><code>@app.errorhandler(404) def page_not_found(error): return render_template('error.html'), 404 </code></pre> <p>I...
0
2016-07-25T15:47:17Z
38,574,773
<p>I figured it out! The problem was not with the way I had routed my URLs, but how the language toggle was working on my site. </p> <p>I had been using this:</p> <pre><code>{% if session['lang_code']=='en' %} {% set new_lang_code='fr' %} {% else %} {% set new_lang_code='en' %} {% endif %} &lt;li&gt;&lt;a href="{...
0
2016-07-25T18:14:31Z
[ "python", "flask", "url-routing" ]
ImportError: No module named numpy - Google Cloud Dataproc when using Jupyter Notebook
38,572,287
<p>When starting Jupyter Notebook on Google Dataproc, importing modules fails. I have tried to install the modules using different commands. Some examples:</p> <pre><code>import os os.sytem("sudo apt-get install python-numpy") os.system("sudo pip install numpy") #after having installed pip os.system("sudo pip install ...
0
2016-07-25T15:50:46Z
38,572,627
<p>Did you try: pip install ipython[numpy]</p>
0
2016-07-25T16:07:39Z
[ "python", "importerror", "jupyter-notebook", "google-cloud-dataproc" ]
ImportError: No module named numpy - Google Cloud Dataproc when using Jupyter Notebook
38,572,287
<p>When starting Jupyter Notebook on Google Dataproc, importing modules fails. I have tried to install the modules using different commands. Some examples:</p> <pre><code>import os os.sytem("sudo apt-get install python-numpy") os.system("sudo pip install numpy") #after having installed pip os.system("sudo pip install ...
0
2016-07-25T15:50:46Z
38,589,114
<p>I found a solution.</p> <pre><code>import sys sys.path.append('/usr/lib/python2.7/dist-packages') os.system("sudo apt-get install python-pandas -y") os.system("sudo apt-get install python-numpy -y") os.system("sudo apt-get install python-scipy -y") os.system("sudo apt-get install python-sklearn -y") import panda...
0
2016-07-26T11:49:32Z
[ "python", "importerror", "jupyter-notebook", "google-cloud-dataproc" ]
ImportError: No module named numpy - Google Cloud Dataproc when using Jupyter Notebook
38,572,287
<p>When starting Jupyter Notebook on Google Dataproc, importing modules fails. I have tried to install the modules using different commands. Some examples:</p> <pre><code>import os os.sytem("sudo apt-get install python-numpy") os.system("sudo pip install numpy") #after having installed pip os.system("sudo pip install ...
0
2016-07-25T15:50:46Z
38,625,451
<p>Try <code>conda install numpy</code> as Google's jupyter init script is using conda. I personally prefer to have my own init scripts so I can have more control.</p>
0
2016-07-28T00:53:17Z
[ "python", "importerror", "jupyter-notebook", "google-cloud-dataproc" ]
ImportError: No module named numpy - Google Cloud Dataproc when using Jupyter Notebook
38,572,287
<p>When starting Jupyter Notebook on Google Dataproc, importing modules fails. I have tried to install the modules using different commands. Some examples:</p> <pre><code>import os os.sytem("sudo apt-get install python-numpy") os.system("sudo pip install numpy") #after having installed pip os.system("sudo pip install ...
0
2016-07-25T15:50:46Z
39,021,663
<pre><code> #!/usr/bin/env bash set -e ROLE=$(curl -f -s -H Metadata-Flavor:Google http://metadata/computeMetadata/v1/instance/attributes/dataproc-role) INIT_ACTIONS_REPO=$(curl -f -s -H Metadata-Flavor:Google http://metadata/computeMetadata/v1/instance/attributes/INIT_ACTIONS_REPO || true) INIT_ACT...
0
2016-08-18T15:06:39Z
[ "python", "importerror", "jupyter-notebook", "google-cloud-dataproc" ]
python functools.partial with fixed array valued argument
38,572,506
<p>I'm trying to vectorize the following function over the argument <code>tiling</code>:</p> <pre><code>def find_tile(x,tiling): """ Calculates the index of the closest element of 'tiling' to 'x'. tiling: array of grid positions x: variable of the same type as the elements of tiling """ return ...
0
2016-07-25T16:01:05Z
38,572,592
<p>You are passing in <code>x</code> as a <em>keyword argument</em>. <code>map()</code> passes in each element from <code>tilings</code> in as a <em>positional argument</em>. However, since your first positional argument is <code>x</code>, that clashes with the keyword argument. Using a name as a keyword argument does ...
1
2016-07-25T16:05:46Z
[ "python", "function", "vectorization" ]
pandas plot time-series with minimized gaps
38,572,534
<p>I recently started to explore into the depths of pandas and would like to visualize some time-series data which contains gaps, some of them rather large. an example <code>mydf</code>:</p> <pre><code> timestamp val 0 2016-07-25 00:00:00 0.740442 1 2016-07-25 01:00:00 0.842911 2 2016-07-25 02:0...
1
2016-07-25T16:02:49Z
38,574,247
<p>I built a new series and plotted it. This is not super elegant! But I believe gets you what you wanted.</p> <h3>Setup</h3> <p>Do this to get to your starting point</p> <pre><code>from StringIO import StringIO import pandas as pd text = """ timestamp val 2016-07-25 00:00:00 0.740442 2016-07-25...
1
2016-07-25T17:42:52Z
[ "python", "pandas", "matplotlib", "plot" ]
Most efficient way to convert datetime string (Jul 25, 2016 11:51:32 PM) into another string (YYYYMMDD) in python
38,572,569
<p>I have a string representing a datetime such as : "Jul 19, 2016 4:45:57 PM"</p> <p>I would like to convert this to the following string: "20160725" </p> <p>What is the most efficient way to do this in python? </p> <p>Thanks :)</p> <p>Note : I need to do this in order to input this date into a csv file later on...
1
2016-07-25T16:04:51Z
38,572,645
<p>You can use the <a href="https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior" rel="nofollow"><code>strptime</code></a> and <a href="https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior" rel="nofollow"><code>strftime</code></a> methods of the <code>datetime</code> module. ...
3
2016-07-25T16:08:42Z
[ "python", "string", "date", "datetime" ]
copy values from one dataframe to another dataframe(different length) by comparing row values in python
38,572,583
<p>I am new to python and working with dataframes. I have two dataframes, one with data for months and another with data for days in those months. I want the data from the monthly dataframe as a column in the daily dataframe, repeated for the number of days in that month. Thanks, I have tried to Provide with an illustr...
0
2016-07-25T16:05:23Z
38,573,927
<p>As <a href="http://stackoverflow.com/questions/38572583/copy-values-from-one-dataframe-to-another-dataframedifferent-length-by-compari/38573927#comment64535881_38572583">@Merlin has already mentioned</a> joining (using <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#database-style-dataframe-joining...
0
2016-07-25T17:23:04Z
[ "python", "pandas", "dataframe" ]
Removing encoded text from strings read from txt file
38,572,626
<p>Here's the problem:</p> <p>I copied and pasted this entire list to a txt file from <a href="https://www.cboe.org/mdx/mdi/mdiproducts.aspx" rel="nofollow">https://www.cboe.org/mdx/mdi/mdiproducts.aspx</a></p> <p>Sample of text lines:</p> <p><code>BFLY - The CBOE S&amp;P 500 Iron Butterfly Index BPVIX - CBOE/CME FX...
0
2016-07-25T16:07:35Z
38,573,097
<p>Why not use Regex?</p> <p>I think this will catch the letters in caps</p> <pre><code>"[A-Z]{1,}/?[A-Z]{1,}[0-9]?" </code></pre> <p>This is better. I got a list of all such symbols. Here's my result.</p> <pre><code>['BFLY', 'CBOE', 'BPVIX', 'CBOE/CME', 'FX', 'BPVIX1', 'CBOE/CME', 'FX', 'BPVIX2', 'CBOE/CME', 'FX']...
1
2016-07-25T16:32:45Z
[ "python", "html", "encoding", "utf-8", "decoding" ]
Unexpected behavior from python's relativedelta
38,572,812
<p>I'm getting a confusing result when using Python's timestamps and </p> <blockquote> <p>my_timestamp </p> </blockquote> <p><code>Timestamp('2015-06-01 00:00:00')</code></p> <blockquote> <p>my_timestamp + relativedelta(month = +4)</p> </blockquote> <p><code>Timestamp('2015-04-01 00:00:00')</code></p> <p>Natu...
0
2016-07-25T16:17:29Z
38,572,982
<p>The issue is that you are using the wrong keyword argument. You want <code>months</code> instead of <code>month</code>. </p> <p>Per <a href="http://dateutil.readthedocs.io/en/stable/relativedelta.html" rel="nofollow">the documentation</a>, <code>month</code> denotes absolute information (not relative) and simply ...
2
2016-07-25T16:26:30Z
[ "python", "datetime", "pandas", "timestamp", "relativedelta" ]
Pandas - Modify string values in each cell
38,572,815
<p>I have a panda dataframe and I need to modify all values in a given column. Each column will contains a string value of the same length. The user provides the index they want to be replaced for each value: ex: <code>[1:3]</code> and the replacement value <code>"AAA"</code>.</p> <p>This would replace the string fr...
1
2016-07-25T16:17:35Z
38,573,189
<p>IMO the most straightforward solution:</p> <pre><code>In [7]: df Out[7]: col 0 abcdefg 1 bbbbbbb 2 ccccccc 3 zzzzzzzz In [9]: df.col = df.col.str[:1] + 'AAA' + df.col.str[4:] In [10]: df Out[10]: col 0 aAAAefg 1 bAAAbbb 2 cAAAccc 3 zAAAzzzz </code></pre>
1
2016-07-25T16:37:16Z
[ "python", "pandas" ]
Pandas - Modify string values in each cell
38,572,815
<p>I have a panda dataframe and I need to modify all values in a given column. Each column will contains a string value of the same length. The user provides the index they want to be replaced for each value: ex: <code>[1:3]</code> and the replacement value <code>"AAA"</code>.</p> <p>This would replace the string fr...
1
2016-07-25T16:17:35Z
38,573,317
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.slice_replace.html" rel="nofollow"><code>str.slice_replace</code></a>:</p> <pre><code>df['B'] = df['B'].str.slice_replace(1, 3, 'AAA') </code></pre> <p>Sample Input:</p> <pre><code> A B 0 w abcdefg 1 x bbbbbbb 2 ...
3
2016-07-25T16:44:28Z
[ "python", "pandas" ]
Split Python Dataframe into multiple Dataframes (where chosen rows are the same)
38,572,816
<p>I would like to split one DataFrame into N Dataframes based on columns X and Z where they are the same (as eachother by column value).</p> <p>For example, this input:</p> <pre><code>df = NAME X Y Z Other 0 a 1 1 1 1 1 b 1 1 2 2 2 c 1 2 1 3 3 d 1 2 2 4 4 e 1 1 1 5 5 f 2 1 2 6 6 g 2 2...
2
2016-07-25T16:17:37Z
38,572,937
<p><code>groupby</code> generates an iterator of tuples with the first element be the group id, so if you iterate through the groupers and extract the second element from each tuple, you can get a list of data frames each having a unique group: </p> <pre><code>grouper = [g[1] for g in df.groupby(['X', 'Z'])] grouper[...
2
2016-07-25T16:24:15Z
[ "python", "pandas", "grouping" ]
Iterating through a dictionary and subtracting values based on keys
38,572,817
<p>So I have a dictionary like the one below, however, I am trying to subtract ART[0][0] - ART[1][0] and this has to be an iteration. </p> <p>This is what I have, but it doesn't seem to work. I keep getting the error: 'KeyError: 2'</p> <p>Any help would be appreciated.</p> <pre><code> for i in range(1, 5): #from ...
-1
2016-07-25T16:17:38Z
38,572,939
<p>Dictionaries are accessed by the key name. See <a href="https://developers.google.com/edu/python/dict-files" rel="nofollow">here</a> for examples.</p> <p>For example, <code>ART['U']</code> would return <code>(5, 6)</code>. In your code, you're trying to access a key <code>2</code>, because that's what <code>j</code...
0
2016-07-25T16:24:19Z
[ "python", "dictionary", "iteration" ]
Iterating through a dictionary and subtracting values based on keys
38,572,817
<p>So I have a dictionary like the one below, however, I am trying to subtract ART[0][0] - ART[1][0] and this has to be an iteration. </p> <p>This is what I have, but it doesn't seem to work. I keep getting the error: 'KeyError: 2'</p> <p>Any help would be appreciated.</p> <pre><code> for i in range(1, 5): #from ...
-1
2016-07-25T16:17:38Z
38,573,120
<p>It seems like you want to get all the combinations of keys from the dictionary. Dictionaries are unordered, so <code>ART[0]</code> does not have any meaning<sup>1)</sup>. Instead, you can iterate the keys directly:</p> <pre><code>for i in ART: for j in ART: if i != j: t = ART[j][0] - ART[i][...
0
2016-07-25T16:33:46Z
[ "python", "dictionary", "iteration" ]
Iterating through a dictionary and subtracting values based on keys
38,572,817
<p>So I have a dictionary like the one below, however, I am trying to subtract ART[0][0] - ART[1][0] and this has to be an iteration. </p> <p>This is what I have, but it doesn't seem to work. I keep getting the error: 'KeyError: 2'</p> <p>Any help would be appreciated.</p> <pre><code> for i in range(1, 5): #from ...
-1
2016-07-25T16:17:38Z
38,573,501
<p>You mention in comments that you want to call items in the dictionary by an index. This is not possible because dictionaries are unordered. Dictionaries are for mapping a particular 'key' to a value that you stored against that key. If you <code>print ART</code> several times, you will see different ordering. I don'...
0
2016-07-25T16:55:27Z
[ "python", "dictionary", "iteration" ]
django custom validation not showing up on button click
38,572,844
<p>I wrote a custom validation for my form in forms.py but it's not working. It doesn't show anything ("email not exist"), when I press the submit button it looks like refreshing the page. I would appreciate any help.</p> <p>here is my view.py:</p> <pre><code>def delete(request): if request.method == 'POST' and "...
0
2016-07-25T16:18:59Z
38,573,880
<p>You are simply not returning the validated form to the template. Everytime in your view, you return a new instance of LoginPageDelete() instead and discard the one with validation information.</p> <pre><code>def delete(request): if request.method == 'POST' and "DeleteButton" in request.POST: form = Logi...
0
2016-07-25T17:20:01Z
[ "python", "django", "django-validation" ]
Append and Truncating together in Python
38,572,880
<p>So, I am at exercise 16 of Zed Shaw's Python book.</p> <p>I thought of trying out both append and truncate on the same file. I know, this does not make sense. But, I am new and I am trying to learn what would happen if I used both.</p> <p>So, first I am opening the file in append mode and then truncating it and th...
0
2016-07-25T16:21:24Z
38,572,996
<p>The argument <code>'a'</code> opens the file for appending. You will need to use <code>'w'</code> instead.</p>
0
2016-07-25T16:27:22Z
[ "python", "append", "truncate" ]
Append and Truncating together in Python
38,572,880
<p>So, I am at exercise 16 of Zed Shaw's Python book.</p> <p>I thought of trying out both append and truncate on the same file. I know, this does not make sense. But, I am new and I am trying to learn what would happen if I used both.</p> <p>So, first I am opening the file in append mode and then truncating it and th...
0
2016-07-25T16:21:24Z
38,573,098
<blockquote> <p>Truncate the file’s size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position.</p> </blockquote> <p>When you open your file with 'a' mode, the position is at the <strong>end</strong> of the file.</p> <p>You can do someth...
0
2016-07-25T16:32:45Z
[ "python", "append", "truncate" ]
Examples of Python Objects That Have An __index__() method?
38,572,999
<p>What are some examples of Python objects that have an <code>__index__()</code> method other than an <code>int</code>?</p> <p>For example, the <a href="https://docs.python.org/3.4/library/functions.html#hex" rel="nofollow">Hex</a> documentation state:</p> <blockquote> <p>If <code>x</code> is not a Python int obje...
1
2016-07-25T16:27:41Z
38,573,210
<p>Mostly, these are types from mathematical libraries like <a href="http://www.numpy.org/" rel="nofollow">NumPy</a> or <a href="http://www.sympy.org/en/index.html" rel="nofollow">SymPy</a>. These libraries have their own integer types (for good reason), but thanks to <code>__index__</code>, their special integers can ...
2
2016-07-25T16:38:17Z
[ "python", "indexing", "int", "hex" ]
edit django form widget rendering
38,573,006
<p>I have a Django form where one of the fields is defined as:</p> <pre><code>widgets = { 'name': forms.CheckboxSelectMultiple() } </code></pre> <p>The template renders them in a loop with:</p> <pre><code>{% for field in form %} &lt;fieldset class="article-form__field"&gt; {{ field.label_tag }} {{ fi...
1
2016-07-25T16:28:05Z
38,573,937
<pre><code>{% for field in form %} &lt;fieldset class="article-form__field"&gt; {% if field.name != "category-name" %} {{ field.label_tag }} {{ field }} {% else %} {{ field.label_tag }} &lt;ul id={{ field.auto_id }}&gt; {% for checkbox in field %} &lt;li&gt; ...
1
2016-07-25T17:23:39Z
[ "python", "django", "django-forms", "jinja2", "multi-model-forms" ]
Global variables aren't working
38,573,025
<p>My global variables are not working in my code. I'm fairly new to this and I can't seem to figure this out: I have set variables (only showing gna for this), which can be manipulated by an entry field, triggered by a corresponding button. For some reason, it's not taking the changes within the loop. I'm trying to ma...
-3
2016-07-25T16:28:52Z
38,573,173
<pre><code>gna = gnaEntry.get() </code></pre> <p><code>Entry.get</code> returns a string, which is probably an unsuitable type for the arithmetic you're doing in <code>graph</code>. Try converting to a number first.</p> <pre><code>gna = float(gnaEntry.get()) #or perhaps `int` if it's always an integer </code></pre>
2
2016-07-25T16:36:29Z
[ "python", "loops", "variables", "global" ]
tkinter overrideredirect stops entry working
38,573,178
<p>I would like to create a "Borderless" window in python and my code works without overrideredirect, however when I use this the input is disallowed. I can not click into the Entry box</p> <p>*This is the code which needs to be figured out, it is currently in a function and there is another 500 lines of code to go wi...
0
2016-07-25T16:36:46Z
38,578,749
<p>Here is minimal code that works on Windows with Python 3.6 and tk 8.6. The popup is in its default position, the upper left corner the screen.</p> <pre><code>import tkinter as tk root = tk.Tk() tag = tk.Label(root, text='Popup entry contents: ') var = tk.StringVar(root, 'var') label = tk.Label(root, textvariabl...
0
2016-07-25T23:11:20Z
[ "python", "html", "user-interface", "tkinter" ]
Calculating cosine distance between the rows of matrix
38,573,213
<p>I'm trying to calculate cosine distance in python between the rows in matrix and have couple a questions.So I'm creating matrix matr and populating it from the lists, then reshaping it for analysis purposes:</p> <pre><code>s = [] for i in range(len(a)): for j in range(len(b_list)): s.append(a[i].count(...
1
2016-07-25T16:38:21Z
38,573,583
<p>You said "calculate cosine from first row to every other else in the d matrix" [sic]. If I understand correctly, you can do that with <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html" rel="nofollow"><code>scipy.spatial.distance.cdist</code></a>, passing the first row as...
2
2016-07-25T17:00:17Z
[ "python", "numpy", "matrix", "scipy", "cosine" ]
Calculating cosine distance between the rows of matrix
38,573,213
<p>I'm trying to calculate cosine distance in python between the rows in matrix and have couple a questions.So I'm creating matrix matr and populating it from the lists, then reshaping it for analysis purposes:</p> <pre><code>s = [] for i in range(len(a)): for j in range(len(b_list)): s.append(a[i].count(...
1
2016-07-25T16:38:21Z
38,573,620
<p>You can just use a simple for loop with <code>scipy.spatial.distance.cosine</code>:</p> <pre><code>dists = [] for row in matr: dists.append(scipy.spatial.distance.cosine(matr[0,:], row)) </code></pre>
2
2016-07-25T17:02:33Z
[ "python", "numpy", "matrix", "scipy", "cosine" ]
Calculating cosine distance between the rows of matrix
38,573,213
<p>I'm trying to calculate cosine distance in python between the rows in matrix and have couple a questions.So I'm creating matrix matr and populating it from the lists, then reshaping it for analysis purposes:</p> <pre><code>s = [] for i in range(len(a)): for j in range(len(b_list)): s.append(a[i].count(...
1
2016-07-25T16:38:21Z
38,575,393
<p>Here's how you might calculate it easily by hand:</p> <pre><code>from numpy import array as a from numpy.random import random_integers as randi from numpy.linalg.linalg import norm from numpy import set_printoptions M = randi(10, size=a([5,5])); # create demo matrix # dot products of rows against themselves Dot...
1
2016-07-25T18:51:38Z
[ "python", "numpy", "matrix", "scipy", "cosine" ]
Pulling the Next Value Under the Same Column Header
38,573,287
<p>I am using Python's <code>csv</code> module to read ".csv" files and parse them out to MySQL insert statements. In order to maintain syntax for the statements I need to determine the type of the values listed under each column header. However, I have run into a problem as some of the rows start with a <code>null</co...
0
2016-07-25T16:42:38Z
38,574,470
<p>Rather than pull the next value from the column as the title suggests, I found it easier to just skip rows that contained any <code>null</code> values. There are two different ways to do this:</p> <p>Use a loop to scan each row and see if it contains a <code>null</code> value, and jump to the next row until one is ...
1
2016-07-25T17:56:41Z
[ "python", "mysql", "python-3.x", "csv" ]
Terminology: A user-defined function object attribute?
38,573,353
<p>According to Python 2.7.12 documentation, <a href="https://docs.python.org/2.7/reference/datamodel.html#the-standard-type-hierarchy" rel="nofollow">User-defined methods</a>:</p> <blockquote> <p>User-defined method objects may be created when getting an attribute of a class (perhaps via an instance of that class...
0
2016-07-25T16:46:53Z
38,573,851
<p>When you do</p> <pre><code>class Foo(object): def meth(self): pass </code></pre> <p>you are defining a class <code>Foo</code> with a method <code>meth</code>. However, when this class definition is executed, no method object is created to represent the method. The <code>def</code> statement creates an o...
1
2016-07-25T17:17:53Z
[ "python", "oop", "methods", "language-lawyer", "terminology" ]
Use __get__, __set__ with dictionary item?
38,573,405
<p>Is there a way to make a dictionary of functions that use set and get statements and then use them as set and get functions?</p> <pre><code>class thing(object): def __init__(self, thingy) self.thingy = thingy def __get__(self,instance,owner): return thingy def __set__(self,instance,value...
0
2016-07-25T16:49:47Z
38,573,617
<p>No, because to execute <code>theDict["bob"] = 10</code>, the Python runtime doesn't call any methods at all of the previous value of <code>theDict["bob"]</code>. It's not like when <code>myObject.mydescriptor = 10</code> calls the descriptor setter.</p> <p>Well, maybe it calls <code>__del__</code> on the previous v...
1
2016-07-25T17:02:27Z
[ "python", "dictionary" ]
Use __get__, __set__ with dictionary item?
38,573,405
<p>Is there a way to make a dictionary of functions that use set and get statements and then use them as set and get functions?</p> <pre><code>class thing(object): def __init__(self, thingy) self.thingy = thingy def __get__(self,instance,owner): return thingy def __set__(self,instance,value...
0
2016-07-25T16:49:47Z
38,574,345
<p><code>theDict["bob"] = 10</code> is just assign <code>10</code> to the key <code>bob</code> for <code>theDict</code>. I think you should know about the magic methods <code>__get__</code> and <code>__set__</code> first. Go to: <a href="https://docs.python.org/2.7/howto/descriptor.html" rel="nofollow">https://docs.py...
0
2016-07-25T17:49:11Z
[ "python", "dictionary" ]
Use __get__, __set__ with dictionary item?
38,573,405
<p>Is there a way to make a dictionary of functions that use set and get statements and then use them as set and get functions?</p> <pre><code>class thing(object): def __init__(self, thingy) self.thingy = thingy def __get__(self,instance,owner): return thingy def __set__(self,instance,value...
0
2016-07-25T16:49:47Z
38,574,478
<p>You could do it if you can (also) use a specialized version of the dictionary which is aware of your <code>Thing</code> class and handles it separately:</p> <pre><code>class Thing(object): def __init__(self, thingy): self._thingy = thingy def _get_thingy(self): return self._thingy def _s...
1
2016-07-25T17:57:01Z
[ "python", "dictionary" ]
How can I check if each row in a matrix is equal to an array and return a Boolean array containing the result?
38,573,577
<p>How can I check if each row in a matrix is equal to an array and return a Boolean array containing the result using NumPy? e.g.</p> <pre><code>a = np.array([[1,2,3],[4,5,6],[7,8,9]]) b = np.array([4,5,6]) # Expected Result: [False,True,False] </code></pre>
0
2016-07-25T16:59:51Z
38,573,578
<p>The neatest way I've found of doing this, is:</p> <pre><code>result = np.all(a==b, axis=1) </code></pre>
3
2016-07-25T16:59:51Z
[ "python", "arrays", "numpy", "matrix" ]