question_id
int64
1.48k
40.1M
title
stringlengths
15
142
question_body
stringlengths
46
12.1k
question_type
stringclasses
5 values
question_date
stringlengths
20
20
34,206,921
Converting date using to_datetime
<p>I am still quite new to Python so please excuse perhaps basic question.</p> <p>After reset of pandas grouped dataframe I get:</p> <pre><code> year month pl 0 2010 1 27.4376 1 2010 2 29.2314 2 2010 3 33.5714 3 2010 4 37.2986 4 2010 5 36.6971 5 2010 6 35.9329 </code></pre> <p>I would like to merge year and month to one column in padas datetime format.</p> <p>I am trying:</p> <pre><code>C3['date']=pandas.to_datetime(C3.year + C3.month, format='%Y-%m') </code></pre> <p>but it gives me date like this:</p> <pre><code> year month pl date 0 2010 1 27.4376 1970-01-01 00:00:00.000002011 </code></pre> <p>What is the correct way? Thank you.</p>
howto
2015-12-10T16:26:14Z
34,243,214
Pivot Pandas Dataframe with a Mix of Numeric and Text Fields
<p>I have this dataframe</p> <pre><code>Athlete Race Distance Rank Time M.Smith A 400m. 1 48.57 A.Moyet A 400m. 2 49.00 C.Marconi B 800m 5 104.12 M.Smith B 800m. 3 102.66 </code></pre> <p>and want to turn it into</p> <pre><code>Athlete Race#1 Distance#1 Rank#1 Time#1 Race#2 Distance#2 Rank#2 Time#2 M.Smith A 400m 1 48.57 B 800m 3 102.66 A.Moyet A 400m 2 49.00 NaN NaN NaN NaN C.Marconi B 800m 5 104.12 NaN NaN NaN NaN </code></pre> <p>Thanks for your answers!</p>
howto
2015-12-12T18:07:44Z
34,244,726
Computing 16-bit checksum of ICMPv6 header
<p>I would like to ask if my solution of computing 16 bit checksum according to ICMPv6 protocol is correct. I try to follow <a href="https://en.wikipedia.org/wiki/Internet_Control_Message_Protocol_version_6#Message_checksum" rel="nofollow">Wikipedia</a>, but I am not sure mainly about two things. </p> <p>First is what <code>the packet length</code> means - is it the packet length of the whole ICMPv6 packet without checksum, or only the payload? Is it in octets as in IPv6? What is the length of this ICMPv6 echo request?</p> <pre><code>6000 # beginning of IPv6 packet 0000 0000 3a00 FE80 0000 0000 0000 0202 B3FF FE1E 8329 FE80 0000 0000 0000 0202 B3FF FE1E 8330 8000 xxxx # this is beginning of the ICMP packet - type and checksum a088 0000 0001 # from here including this line I compute the length 0203 0405 0607 0809 0a0b 0c0d 0e0f 1011 1213 1415 1617 1819 1a1b 1c1d 1e1f 2021 2223 2425 2627 2829 2a2b 2c2d 2e2f 3031 3233 </code></pre> <p>Does it mean that the length of the above is 56 octets as I state in the code below?</p> <p>Then I have problem understanding this (again from wiki).</p> <blockquote> <p>Following this pseudo header, the checksum is continued with the ICMPv6 message in which the checksum is initially set to zero. The checksum computation is performed according to Internet protocol standards using 16-bit ones' complement summation, followed by complementing the checksum itself and inserting it into the checksum field</p> </blockquote> <p>Does it mean I should add the whole ICMPv6 frame with 0000 on the checksum field to the checksum too? </p> <p>I tried to write a simple program for this in Python:</p> <pre><code># START OF Pseudo header # we are doing 16 bit checksum hence quadruplets ## source IP sip = ['FE80', '0000', '0000', '0000', '0202', 'B3FF', 'FE1E', '8329'] ## destination IP dip = ['FE80', '0000', '0000', '0000', '0202', 'B3FF', 'FE1E', '8330'] ## next header - 32 bits, permanently set to (58)_dec ~ (88)_hex nh = ['0000', '0088'] ## packet length -&gt; see my question above: (56)_dec ~ (38)_hex lng = ['0038'] png = "8000 0000 a088 0000 0001 0203 0405 0607 0809 0a0b 0c0d 0e0f 1011 1213 1415 1617 1819 1a1b 1c1d 1e1f 2021 2223 2425 2627 2829 2a2b 2c2d 2e2f 3031 3233".split(" ") # END OF PSEUDO HEADER tot = sip + dip + lng + nh + png # from what the sum is going to be counted stot = sum([int(x, 16) for x in tot]) % 65535 # we are in 16 bits world rstot = 65535 - stot # wrap around res = hex(rstot) # convert to hex print(stot, rstot) print(res) check = bin(rstot + stot) print(check) # all ones </code></pre> <p>that is for the following ICMPv6 ping requests (with IPv6 header):</p> <pre><code>d392 30fb 0001 d393 30fb 0001 86dd 6000 0000 0000 3a00 FE80 0000 0000 0000 0202 B3FF FE1E 8329 FE80 0000 0000 0000 0202 B3FF FE1E 8330 8000 xxxx a088 0000 0001 0203 0405 0607 0809 0a0b 0c0d 0e0f 1011 1213 1415 1617 1819 1a1b 1c1d 1e1f 2021 2223 2425 2627 2829 2a2b 2c2d 2e2f 3031 3233 </code></pre> <p>and it gives output:</p> <pre><code>27741 37794 0xe672 # correct? 0b1111111111111111 </code></pre> <p>So I should just replace <code>xxxx</code> with <code>e672</code>. Is it correct? When I try to compute this with wireshark, I get a different answer.</p>
howto
2015-12-12T20:38:05Z
34,260,522
Selection of rows by condition
<p>I have a pandas data frame:</p> <pre><code>df_total_data2 </code></pre> <p>which have the following columns:</p> <pre><code>df_total_data.columns Index([u'BBBlink', u'Name', u'_type'], dtype='object') </code></pre> <p>I want to drop the all the rows which don't satisfy a given condition, in this case the condition is that the column can't contain the word <code>secure</code> I want to drop the row at the place, not to have a function that return <code>None</code> if the condition isn't meet.</p> <p>So I write this function:</p> <pre><code>df_total_data.apply(lambda x: 'secure' not in x['BBBlink'],1 ).values </code></pre> <p>Which return a boolean array, but I don't know how to used it to drop the row.</p> <p>Edit:</p> <p>I got an array:</p> <pre><code>array([ True, True, True, True, True,False....True]) </code></pre> <p>Now, how can I use this array to drop the columns?</p>
howto
2015-12-14T05:44:43Z
34,271,014
Using pandas to plot data
<p>I am new to stackoverflow. My data frame is similar to the one given below. I want to plot this data such that I can get a plot for <code>A</code>'s activity, <code>B</code>'s activity and <code>C</code>'s activity separately. </p> <p>How can I accomplish this using pandas?</p> <pre><code>Name Date Activity A 01-02-2015 1 A 01-03-2015 2 A 01-04-2015 3 A 01-04-2015 1 B 01-02-2015 1 B 01-02-2015 2 B 01-03-2015 1 B 01-04-2015 5 C 01-31-2015 1 </code></pre>
howto
2015-12-14T15:41:16Z
34,286,165
python click usage of standalone_mode
<p>This question is about the Python <a href="http://click.pocoo.org/dev/python3/" rel="nofollow">Click</a> library.</p> <p>I want click to gather my commandline arguments. When gathered, I want to reuse these values. I dont want any crazy chaining of callbacks, just use the return value. By default, click disables using the return value and calls <code>sys.exit()</code>. </p> <p>I was wondering how to correctly invoke <code>standalone_mode</code> (<a href="http://click.pocoo.org/5/exceptions/#what-if-i-don-t-want-that" rel="nofollow">http://click.pocoo.org/5/exceptions/#what-if-i-don-t-want-that</a>) in case <strong>I want to use the decorator style</strong>. The above linked doc only shows the usage when (manually) creating Commands using click. Is it even possible? A minimal example is shown below. It illustrates how click calls <code>sys.exit()</code> directly after returning from <code>gatherarguments</code></p> <pre><code>import click @click.command() @click.option('--name', help='Enter Name') @click.pass_context def gatherarguments(ctx, name): return ctx def usectx(ctx): print("Name is %s" % ctx.params.name) if __name__ == '__main__': ctx = gatherarguments() print(ctx) # is never called usectx(ctx) # is never called </code></pre> <p><code>$ python test.py --name Your_Name</code></p> <p>I would love this to be stateless, meaning, without any <code>click.group</code> functionality - I just want the results, without my application exiting. </p>
howto
2015-12-15T10:03:26Z
34,301,088
Reading/Writing out a dictionary to csv file in python
<p>Pretty new to python, and the documentation for csv files are a bit confusing.</p> <p>I have a dictionary that looks like the following:</p> <p>key1: (value1, value2)</p> <p>key2: (value1, value2)</p> <p>key3: (value1, value2) ....</p> <p>I would like to write these out to a csv file in the format where each line contains the key, followed by the two values.</p> <p>I would also like to be able to read them back into a dictionary from the file at a later date.</p>
howto
2015-12-15T23:01:35Z
34,338,341
Regex for getting all digits in a string after a character
<p>I am trying to parse the following string and return all digits after the last square bracket:</p> <pre><code>C9: Title of object (foo, bar) [ch1, CH12,c03,4] </code></pre> <p>So the result should be: </p> <pre><code>1,12,03,4 </code></pre> <p>The string and digits will change. The important thing is to get the digits after the '[' regardless of what character (if any) precede it. (I need this in python so no atomic groups either!) I have tried everything I can think of including:</p> <pre><code> \[.*?(\d) = matches '1' only \[.*(\d) = matches '4' only \[*?(\d) = matches include '9' from the beginning </code></pre> <p>etc</p> <p>Any help is greatly appreciated!</p> <p>EDIT: I also need to do this without using str.split() too.</p>
howto
2015-12-17T15:32:33Z
34,358,278
Django filter JSONField list of dicts
<p>I run Django 1.9 with the new JSONField and have the following Test model :</p> <pre><code>class Test(TimeStampedModel): actions = JSONField() </code></pre> <p>Let's say the action JSONField looks like this :</p> <pre><code>[ { "fixed_key_1": "foo1", "fixed_key_2": { "random_key_1": "bar1", "random_key_2": "bar2", } }, { "fixed_key_1": "foo2", "fixed_key_2": { "random_key_3": "bar2", "random_key_4": "bar3", } } ] </code></pre> <p>I want to be able to filter the foo1 and foo2 keys for every item of the list. When I do :</p> <pre><code>&gt;&gt;&gt; Test.objects.filter(actions__1__fixed_key_1="foo2") </code></pre> <p>The Test is in the queryset. But when I do :</p> <pre><code>&gt;&gt;&gt; Test.objects.filter(actions__0__fixed_key_1="foo2") </code></pre> <p>It isn't, which makes sense. I want to do something like :</p> <pre><code>&gt;&gt;&gt; Test.objects.filter(actions__values__fixed_key_1="foo2") </code></pre> <p>Or</p> <pre><code>&gt;&gt;&gt; Test.objects.filter(actions__values__fixed_key_2__values__contains="bar3") </code></pre> <p>And have the Test in the queryset.</p> <p>Any idea if this can be done and how ?</p>
howto
2015-12-18T14:52:28Z
34,371,807
How to determine if a decimal fraction can be represented exactly as Python float?
<p>From the Python <a href="https://docs.python.org/3.5/tutorial/floatingpoint.html#floating-point-arithmetic-issues-and-limitations" rel="nofollow">tutorial</a>: </p> <blockquote> <p>Unfortunately, most decimal fractions cannot be represented exactly as binary fractions. A consequence is that, in general, the decimal floating-point numbers you enter are only approximated by the binary floating-point numbers actually stored in the machine.</p> </blockquote> <p>I wonder how can I check if a given decimal fraction will be represented exactly as a Python <code>float</code>. For instance, <code>0.25</code> can be represented exactly while <code>0.1</code> can't:</p> <pre><code>&gt;&gt;&gt; 0.1 + 0.1 + 0.1 == 0.3 False &gt;&gt;&gt; 0.25 + 0.25 + 0.25 == 0.75 True </code></pre>
howto
2015-12-19T14:25:04Z
34,374,393
Python find which order element is in in a list
<p>I have a program which asks the user for a sentence, gets each word, and stores it in a list called words.</p> <pre><code>text = raw_input("") words = map(lambda x:x.lower(), re.sub("[^\w]", " ", text).split()) </code></pre> <p>Like this.</p> <p>Now, I want to see which word has the word "name". I have written:</p> <pre><code>for listelement in words: if listelement == "name": name = listelement[This is what I want to find] </code></pre> <p>How should I find it? Speed is not really a concern, though the faster it is, the better.</p> <p><strong>EDIT</strong>: I'm trying to get the user's name by putting the sentence "My name is * ", separating it by words, detecting where the word "name" is in the list, add 2 to the position of "name" and saving it as the variable uname.</p>
howto
2015-12-19T19:12:12Z
34,382,144
Changing number representation in IDLE
<p>I use Python IDLE a lot in my day-to-day job, mostly for short scripts and as a powerful and convenient calculator. </p> <p>I usually have to work with different numeric bases (mostly decimal, hexadecimal, binary and less frequently octal and other bases.)</p> <p>I know that using <code>int()</code>, <code>hex()</code>, <code>bin()</code>, <code>oct()</code> is a convenient way to move from one base to another and prefixing <a href="https://docs.python.org/3/reference/lexical_analysis.html#integer-literals" rel="nofollow">integer literals</a> with the right prefix is another way to express an number.</p> <p>I find it quite inconvenient to have to put a calculation in a function just to see the result in the right base (and the resulting ouput of <code>hex()</code> and similar functions is a string) , so what I'm trying to achieve is to have either a function (or maybe a statement?) that set the internal IDLE number representation to a known base (2, 8, 10, 16).</p> <p>Example :</p> <pre><code>&gt;&gt;&gt; repr_hex() # from now on, all number are considered hexadecimal, in input and in output &gt;&gt;&gt; 10 # 16 in dec &gt;&gt;&gt; 0x10 # now output is also in hexadecimal &gt;&gt;&gt; 1e + 2 &gt;&gt;&gt; 0x20 # override should be possible with integer literal prefixes # 0x: hex ; 0b: bin ; 0n: dec ; 0o: oct &gt;&gt;&gt; 0b111 + 10 + 0n10 # dec : 7 + 16 + 10 &gt;&gt;&gt; 0x21 # 33 dec # still possible to override output representation temporarily with a conversion function &gt;&gt;&gt; conv(_, 10) # conv(x, output_base, current_base=internal_base) &gt;&gt;&gt; 0n33 &gt;&gt;&gt; conv(_, 2) # use prefix of previous output to set current_base to 10 &gt;&gt;&gt; 0b100001 &gt;&gt;&gt; conv(10, 8, 16) # convert 10 to base 8 (10 is in base 16: 0x10) &gt;&gt;&gt; 0o20 &gt;&gt;&gt; repr_dec() # switch to base 10, in input and in output &gt;&gt;&gt; _ &gt;&gt;&gt; 0n16 &gt;&gt;&gt; 10 + 10 &gt;&gt;&gt; 0n20 </code></pre> <p>Implementing those features doesn't seem to be difficult, what I don't know is:</p> <ul> <li>Is it possible to change number representation in IDLE?</li> <li>Is it possible to do this without having to change IDLE (source code) itself? I looked at <a href="https://docs.python.org/3/library/idle.html#extensions" rel="nofollow">IDLE extensions</a>, but I don't know where to start to have access to IDLE internals from there.</li> </ul> <p>Thank you.</p>
howto
2015-12-20T14:41:22Z
34,400,455
Updating a value in a dictionary inside a dictionary
<p>If I have a list of contact dictionaries like this:</p> <pre><code>{'name': 'Rob', 'phoneNumbers': [{'phone': '123-3214', 'type': 'home'}, {'phone': '456-3216', 'type': 'work'}]} </code></pre> <p>how could I update this dictionary to remove the dashes from the phone numbers in a list of contact dictionaries pythonically?</p>
howto
2015-12-21T16:41:47Z
34,403,494
How to write variable and array on the same line for a text file?
<p>I have an array called 'thelist' and it holds some numbers which I want to output to a file on the same line delimited with commas. I did this using:</p> <pre><code>thelist = [1,6,5,2,7] thefile = open('test.txt', 'w') name = "bob" for item in thelist: thefile.write("%s,"%(item)) </code></pre> <p>output:</p> <pre><code>1,6,5,2,7, </code></pre> <p>However, I want to be able to write the name and the array on the same line. So it'd look something similar to <code>bob 1,6,5,2,7</code></p> <p>I tried to use <code>thefile.write("%s %s,"%(name,item))</code> but that unfortunately does not work. I tried to search for an answer but I didn't find a solution. Any ideas? Is this even possible?</p>
howto
2015-12-21T20:03:53Z
34,410,358
Splitting a string based on a certain set of words
<p>I have a list of strings like such, </p> <pre><code>['happy_feet', 'happy_hats_for_cats', 'sad_fox_or_mad_banana','sad_pandas_and_happy_cats_for_people'] </code></pre> <p>Given a keyword list like <code>['for', 'or', 'and']</code> I want to be able to parse the list into another list where if the keyword list occurs in the string, split that string into multiple parts.</p> <p>For example, the above set would be split into </p> <pre><code>['happy_feet', 'happy_hats', 'cats', 'sad_fox', 'mad_banana', 'sad_pandas', 'happy_cats', 'people'] </code></pre> <p>Currently I've split each inner string by underscore and have a for loop looking for an index of a key word, then recombining the strings by underscore. Is there a quicker way to do this?</p>
howto
2015-12-22T07:15:17Z
34,419,926
How to make QtGui window process events whenever it is brought forward on the screen?
<p>I'm using <code>PyQt</code> for Python, and am building a gui. I had a problem a few weeks ago where I had a function outside of the gui module modifying widgets within the gui (advanced progress bar, updating strings, etc.), and those modifications were not reflected in the gui until the function that had made the changes finished running. </p> <p>The solution to this was to simply call <code>app.processEvents()</code> after doing whatever modifications I wanted, which would immediately update the graphics of the window. </p> <p>But now I am wondering, is there a way to do this everytime the window is brought forward?</p> <p>Let's say I have called a function that will be modifying the progress bar, but this function takes quite a while to run. Inbetween calling the function, and the progress bar modification, the <code>app</code> processes no events. So, it during this time, I pull up a Chrome window (or anything else), and then close it, my gui window is blank, just gray, until <code>app.processEvents()</code> is called again. </p> <p>Is ther functionality in <code>PyQt</code> that allows me to detect whenever the window is brought to the front of all current windows?</p>
howto
2015-12-22T16:07:43Z
34,428,730
In python convert day of year to month and fortnight
<p>I want to convert day (say 88) and year (say 2004) into its constituent month and nearest number out of 2 possibilities:</p> <p>If the day of month ranges from 1 to 14, then return 1, else return 15</p> <p>I am doing this:</p> <pre><code>datetime.datetime(year, 1, 1) + datetime.timedelta(days - 1) </code></pre> <p>However, this is only part of the way to the soln. The end result for day 88 and year 2004 should be:</p> <p>March 15 (Month is March and closest day is 15th march).</p> <p>-- EDIT: Changed question to reflect that I mean day of year and not julian day</p>
howto
2015-12-23T04:38:38Z
34,437,284
Sum of product of combinations in a list
<p>What is the Pythonic way of summing the product of all combinations in a given list, such as:</p> <pre><code>[1, 2, 3, 4] --&gt; (1 * 2) + (1 * 3) + (1 * 4) + (2 * 3) + (2 * 4) + (3 * 4) = 35 </code></pre> <p>(For this example I have taken all the two-element combinations, but it could have been different.)</p>
howto
2015-12-23T13:58:22Z
34,438,901
finding the last occurrence of an item in a list python
<p>I wish to find the last occurrence of an item 'x' in sequence 's', or to return None if there is none and the position of the first item is equal to 0</p> <p>This is what I currently have:</p> <pre><code>def PositionLast (x,s): count = len(s)+1 for i in s: count -= 1 if i == x: return count for i in s: if i != x: return None </code></pre> <p>When I try:</p> <pre><code>&gt;&gt;&gt;PositionLast (5, [2,5,2,3,5]) &gt;&gt;&gt; 4 </code></pre> <p>This is the correct answer. However when I change 'x' to 2 instead of 5 I get this:</p> <pre><code>&gt;&gt;&gt;PositionLast(2, [2,5,2,3,5]) &gt;&gt;&gt; 5 </code></pre> <p>The answer here should be 2. I am confused as to how this is occurring, if anyone could explain to what I need to correct I would be grateful. I would also like to complete this with the most basic code possible.</p> <p>Thank you.</p>
howto
2015-12-23T15:30:57Z
34,439,723
setting unique abbreviation for every column in python
<p>I have data like this in a csv file </p> <pre class="lang-none prettyprint-override"><code>Ad Group Annuity Calculator Tax Deferred Annuity Annuity Tables annuities calculator annuity formula Annuities Explained Deferred Annuies Calculator Current Annuity Rates Forbes.com Annuity Definition fixed income Immediate fixed Annuities Deferred Variable Annuities 401k Rollover Deferred Annuity Rates Deferred Annuities Immediate Annuities Definition Immediate Variable Annuities Variable Annuity Aig Annuities Retirement Income retirment system Online Financial Planner Certified Financial Planner </code></pre> <p>I want to set a unique abbreviation for each column. For example:</p> <ul> <li>Annuity Calculator = annca</li> <li>annuities calculator = annsca</li> </ul> <p>Can you please help me to figure out whats gonna be the best way to do it in python.</p> <p>Thanks</p>
howto
2015-12-23T16:16:11Z
34,444,319
How to split a string by a string except when the string is in quotes in python?
<p>I'd like to split the following string by the word 'and' except when the word 'and' is within quotes</p> <pre><code>string = "section_category_name = 'computer and equipment expense' and date &gt;= 2015-01-01 and date &lt;= 2015-03-31" </code></pre> <p>Desired Result</p> <pre><code>["section_category_name = 'computer and equipment expense'","date &gt;= 2015-01-01","date &lt;= 2015-03-31"] </code></pre> <p>I can't seem to find the correct regex pattern that splits the string correctly so that 'computer and equipment expense' is not split. </p> <p>Here's what I tried: </p> <pre><code>re.split('and',string) </code></pre> <p>Result</p> <pre><code>[" section_category_name = 'computer "," equipment expense' ",' date &gt;= 2015-01-01 ',' date &lt;= 2015-03-31'] </code></pre> <p>As you can see the result has split 'computer and equipment expense' into different items on the list.</p> <p>I've also tried the following from <a href="http://stackoverflow.com/questions/20256066/python-split-string-by-spaces-except-when-in-quotes-but-keep-the-quotes">this question</a>: </p> <pre><code>r = re.compile('(?! )[^[]+?(?= *\[)' '|' '\[.+?\]') r.findall(s) </code></pre> <p>Result: </p> <pre><code>[] </code></pre> <p>I've also tried the following from this <a href="http://stackoverflow.com/questions/9644784/python-splitting-on-spaces-except-between-certain-characters">question</a></p> <pre><code>result = re.split(r"and+(?=[^()]*(?:\(|$))", string) </code></pre> <p>Result: </p> <pre><code>[" section_category_name = 'computer ", " equipment expense' ", ' date &gt;= 2015-01-01 ', ' date &lt;= 2015-03-31'] </code></pre> <p>The challenge is that the prior questions on this topic do not address how to split a string by a word within quotes, since they address how to split a string by a special character or a space.</p> <p>I was able to get the desired result if I modified the string to the following</p> <pre><code>string = " section_category_name = (computer and equipment expense) and date &gt;= 2015-01-01 and date &lt;= 2015-03-31" result = re.split(r"and+(?=[^()]*(?:\(|$))", string) </code></pre> <p>Desired Result</p> <pre><code>[' section_category_name = (computer and equipment expense) ', ' date &gt;= 2015-01-01 ', ' date &lt;= 2015-03-31'] </code></pre> <p>However I need the function to not split on 'and' within apostrophes instead of parenthesis </p>
howto
2015-12-23T21:54:07Z
34,445,707
PLY YACC pythonic syntax for accumulating list of comma-separated values
<p>I'm using YACC for the first time and getting used to using BNF grammar.</p> <p>I'm currently building a <code>list</code> of <code>type</code>s from a comma separated list (eg. <code>int</code>, <code>float</code>, <code>string</code>):</p> <pre><code>def p_type(p): '''type : primitive_type | array | generic_type | ID''' p[0] = p[1] def p_type_list(p): '''type_list : type | type COMMA type_list''' if not isinstance(p[0], list): p[0] = list() p[0].append(p[1]) if len(p) == 4: p[0] += p[3] </code></pre> <p>The rules work, but I'm getting the sense that my <code>p_type_list</code> logic is a bit of a kludge and could be simplified into a one-liner.</p> <p>I haven't found any PLY specific examples of this online. Any help would be greatly appreciated!</p>
howto
2015-12-24T00:26:52Z
34,452,644
Parse Specific Text File to CSV Format with Headers
<p>I have a log file that is updated every few milliseconds however the information is currently saved with four(4) different delimitors. The log files contain millions of lines so the chances of performing the action in excel null.</p> <p>What I have left to work on resembles:</p> <pre><code>Sequence=3433;Status=true;Report=223313;Profile=xxxx; Sequence=0323;Status=true;Header=The;Report=43838;Profile=xxxx; Sequence=5323;Status=true;Report=6541998;Profile=xxxx; </code></pre> <p>I would like these set to:</p> <pre><code>Sequence,Status;Report;Header;Profile 3433,true,Report=223313,,xxxx 0323,true,Report=43838,The,xxxx 5323,true,Report=6541998,,xxxx </code></pre> <p>Meaning that I would the need the creation of a header using all portions with the equal "=" symbol following it. All of the other operations within the file are taken care of and this will be used to perform a comparative check between files and replace or append fields. As I am new to python, I only need the assistance with this portion of the program I am writing.</p> <p>Thank you all in advance!</p>
howto
2015-12-24T12:13:15Z
34,456,661
Checkbox to determine if an action is completed or not
<p>I have a list of dictionaries of clients in a format like this:</p> <pre><code>dict_list = [{'Name of Business' : 'Amazon', 'Contact Name' : 'Jeff Bezos', 'Email' : 'Jeff@Amazon.com'}, {'Name of Business' : 'Microsoft', 'Contact Name' : 'Bill Gates', 'Email' : 'Bill@Microsoft.com'}] </code></pre> <p>and will be using <code>tkinter</code> to build rows for each client with a <code>checkbox</code> next to each. I will later add a <code>button</code> that, when pressed, will send an email to each client based on the information it pulls from the list.</p> <p>Currently I am doing something like: </p> <pre><code>ClientCount = len(dict_list) CurrentCount = 0 while CurrentCount &lt; ClientCount: for i in range(ClientCount): currentClient = Label(text='Client: ' + dict_list[i]['Client']).grid(row=[i], column=1) currentContactName = Label(text='Contact Name: ' + dict_list[i]['Contact Name']).grid(row=[i], column=2) currentEmail = Label(text='Contact Email: ' + dict_list[i]['Email']).grid(row=[i], column=3) CurrentCount += 1 </code></pre> <p>First, I am sure there is an easier way to do this and will take any suggestions towards that but the main issue is adding a checkbox that will, when selected, determine whether or not to send an email to that client.<br> (A button, added later, will call a command that will check if each client is checked and only send to those that return true etc.)</p> <p>I am not sure whether I should be creating a new variable to be checked, adding a key and a value to each dictionary to be read at a later point, etc.</p>
howto
2015-12-24T18:31:58Z
34,463,966
How do I obtain the reference of a getter/setter method created through @property in Python?
<p>I want to bind some QWidgets to the attributes of an existing class in <strong>Python 3</strong> so that any changes made through the GUI are applied to the underlying data objects in a clean and simple fashion.</p> <p>My existing class looks like this (simplified):</p> <pre><code>class Player: def __init__(self): self._health = 100 @property def health(self): return self._health @health.setter def health(self, value): self._health = value </code></pre> <p><strong>PyQt5</strong> allows connecting Qt signals to any method, so I can easily achieve my goal by calling <code>someWidget.valueChanged.connect(player.someSetterMethod)</code>.</p> <p>However, I use <code>@property</code> and thus, the setter name is identical to the attribute name. When I try using <code>player.health</code>, it is interpreted as an integer (as expected, but obviously not what I want here).</p> <p>I am aware that I could define getter/setter methods with custom names and then use <code>property()</code> instead of <code>@property</code>, but I am hoping there is a way of obtaining the reference to the setter method so that I can pass it to <code>connect()</code>.</p> <p>Thank you!</p> <p>Edit: I doubt it is relevant to this question, but perhaps I should add that in the next step, I want to report changes that are not applied as received back to the GUI.</p>
howto
2015-12-25T15:13:20Z
34,468,751
Get value to 2 attribute from a xpath node for anchor tag
<p>I have the following extracted with the help of xpath:</p> <pre><code>In [206]: list = tree.xpath('/html/body/div[@id="gs_top"]/div[@id="gs_bdy"]/div[@id="gs_ccl"]/div[@id="gsc_ccl"]/div[@class="gsc_1usr gs_scl"]/div[@class="gsc_1usr_text"]/h3[@class="gsc_1usr_name"]/a') In [208]: for item in list: print(etree.tostring(item, pretty_print=True)) .....: &lt;a href="/citations?user=lMkTx0EAAAAJ&amp;amp;hl=en&amp;amp;oe=ASCII"&gt;Jason Weston&lt;/a&gt; &lt;a href="/citations?user=RhFhIIgAAAAJ&amp;amp;hl=en&amp;amp;oe=ASCII"&gt;Pierre Baldi&lt;/a&gt; &lt;a href="/citations?user=9DXQi8gAAAAJ&amp;amp;hl=en&amp;amp;oe=ASCII"&gt;Yair Weiss&lt;/a&gt; &lt;a href="/citations?user=J8YyZugAAAAJ&amp;amp;hl=en&amp;amp;oe=ASCII"&gt;Peter Belhumeur&lt;/a&gt; &lt;a href="/citations?user=ORr4XJYAAAAJ&amp;amp;hl=en&amp;amp;oe=ASCII"&gt;Serge Belongie&lt;/a&gt; </code></pre> <p>Now I can either extract the href by appending <code>/@href</code> or the text with the help of <code>text()</code>. But how can I get both of them in one go, as shown in an answer here: <a href="http://stackoverflow.com/questions/6029232/how-to-select-two-attributes-from-the-same-node-with-one-expression-in-xpath">How to select two attributes from the same node with one expression in XPath?</a> </p>
howto
2015-12-26T05:26:01Z
34,468,983
How to check if all elements in a tuple or list are in another?
<p>For example, I want to check every elements in tuple <code>(1, 2)</code> are in tuple <code>(1, 2, 3, 4, 5)</code>. I don't think use loop is a good way to do it, I think it could be done in one line.</p>
howto
2015-12-26T06:09:27Z
34,478,011
Using descriptor class to raise RuntimeError when user tries to change object's value
<p>I have written a Circle class using descriptors that allows the user to set the values for x, y and r of a circle and checks if the values for x and y are integers. If the user inputs a non integer number, then a TypeError is raised, now I want to make another descriptor class that allows a user to get the value for the area and circumference of the circle, but not be able to set it. I think I have the <code>__get__</code> method working correct, but the <code>__set__</code> method isn't.</p> <pre><code>class Integer: def __init__(self, name): self.name = name # stores name of the managed object's attribute def __get__(self, instance, cls): if instance is None: return self else: return instance.__dict__[self.name] def __set__(self, instance, value): if not isinstance(value, int): raise TypeError('Expected an int') else: instance.__dict__[self.name] = value class Computations(object): def __init__(self, name): self.name = name # default value for area, circumference, distance to origin def __get__(self, instance, cls): if instance is None: print('this is the __get__ if statement running') return self else: print('this is the __get__ else statement running') return instance.__dict__[self.name] def __set__(self, instance, value): if isinstance(value, int): raise RuntimeError('Cant set formulas') else: instance.__dict__[self.name] = value class Circle: x = Integer('_x') # Use _x and _y as the __dict__ key of a Point y = Integer('_y') # These will be the storage names for a Point r = Integer('_r') area = Computations('_area') # class variable of Computations circumference = Computations('_circumference') distance_to_origin = Computations('_distance_to_origin') def __init__(self, x, y, r): self.x = x # invokes Integer.x.__set__ self.y = y # invokes Integer.y.__set__ self.r = r # for radius/invokes Integer.r. self.area = pi * self.r * self.r self.circumference = 2 * pi * self.r self.distance_to_origin = abs(sqrt((self.x - 0)*(self.x - 0) + (self.y - 0) * (self.y - 0)) - self.r) # Testing code if __name__ == '__main__': circle = Circle(x=3, y=4, r=5) print(circle.x) print(circle.y) print(circle.r) print(circle.area) # circle.area = 12 print(circle.area) print(circle.circumference) print(circle.distance_to_origin) tests = [('circle.x = 12.3', "print('Setting circle.x to non-integer fails')"), ('circle.y = 23.4', "print('Setting circle.y to non-integer fails')"), ('circle.area = 23.4', "print('Setting circle.area fails')"), ('circle.circumference = 23.4', "print('Setting circle.circumference fails')"), ('circle.distance_to_origin = 23.4', "print('Setting circle.distance_to_origin fails')"), ('circle.z = 5.6', "print('Setting circle.z fails')"), ('print(circle.z)', "print('Printing circle.z fails')")] for test in tests: try: exec(test[0]) except: exec(test[1]) </code></pre> <p>The program runs, but it allows area, circumference and distance_to_origin to be set, which isn't what I want it to do. I know that the line <code>"if isinstance(value, int): raise RuntimeError('Can't set formulas')"</code> means that if the value that the user puts is not an integer than it raises an error. I'm just not sure what to put in place of it so that it throws an error and doesn't allow the user to change the value.</p> <p>The correct output of the testing code is as follows:</p> <pre><code>78.53981633974483 31.41592653589793 0.0 Setting circle.x to non-integer fails Setting circle.y to non-integer fails Setting circle.area fails Setting circle.circumference fails Setting circle.distance_to_origin fails 5.6 </code></pre>
howto
2015-12-27T06:00:18Z
34,503,246
List names of all available MS SQL databases on server using python
<p>Trying to list the names of the databases on a remote MS SQL server using Python (Just like the Object Explorer in MS SQL Server Management Studio). </p> <p><strong>Current solution</strong>: The required query is <code>SELECT name FROM sys.databases;</code>. So current solution is using SQLAlchemy and Pandas, which works fine as below. </p> <pre><code>import pandas from sqlalchemy import create_engine #database='master' engine = create_engine('mssql+pymssql://user:password@server:port/master') query = "select name FROM sys.databases;" data = pandas.read_sql(query, engine) </code></pre> <p>output: </p> <pre><code> name 0 master 1 tempdb 2 model 3 msdb </code></pre> <p><strong>Question:</strong> How to list the names of the databases on the server using SQLAlchemy's <code>inspect(engine)</code> similar to listing table names under a database? Or any simpler way without importing Pandas? </p> <pre><code>from sqlalchemy import inspect #trial 1: with no database name engine = create_engine('mssql+pymssql://user:password@server:port') #this engine not have DB name inspector = inspect(engine) inspector.get_table_names() #returns [] inspector.get_schema_names() #returns [u'dbo', u'guest',...,u'INFORMATION_SCHEMA'] #trial 2: with database name 'master', same result engine = create_engine('mssql+pymssql://user:password@server:port/master') inspector = inspect(engine) inspector.get_table_names() #returns [] inspector.get_schema_names() #returns [u'dbo', u'guest',...,u'INFORMATION_SCHEMA'] </code></pre>
howto
2015-12-29T01:36:32Z
34,505,283
Sorting a list with a dictionary at items
<p>I am trying to sort this list by date. Does anyone know a way that I can sort by the dictionary value inside of the list? I'm using this for a Flask table, by the way. I'm open to any new methods that would make this easier.</p> <pre><code>def Fights(self): fights = [] for fight in self.fighter["Fights"]: fights.append(dict(Opponent=str(fight["Opponent"]), Location=str(fight["Location"]), Date=(fight["Date"]), Result=str(fight["Result"]), Round=str(fight["Round"]), Time=str(fight["Time"]), Win=str(fight["Win"]))) return fights </code></pre>
howto
2015-12-29T05:56:50Z
34,512,219
Inserting a folder containing specific routes to a bottle application in Python
<p>Let us say that we have the following directory structure ...</p> <pre><code>+-- main.py | +--+ ./web | | | +--- ./web/bottleApp.py </code></pre> <p>Currently, I want to organize the files so that the I can separate different functionality in different areas. Template <code>main.py</code> and <code>./web/bottleApp.py</code> look like the following ...</p> <p>This is the <code>./web/bottleApp.py</code> file:</p> <pre><code>import bottle app = bottle.Bottle() @app.route('/') def root(): return 'This is the root application' # some additional functions here ... </code></pre> <p>And this is the <code>main.py</code> file ...</p> <pre><code>from web import bottleApp as app with app.app as report: # Some random routes here ... report.run(host = 'localhost', port=8080) </code></pre> <p>Now I want to add another folder which can handle some functions which I may optionally use is a bunch of my projects, (for example configuration file handling via the web interface just created)</p> <p>Let us say we want to insert the following folder/file configuration ...</p> <pre><code>+-- main.py | +--+ ./web | | | +--- ./web/bottleApp.py | +--+ ./configure | +--- ./configure/config.py </code></pre> <p>Given the original <code>app = bottle.Bottle()</code> I want to create the following sample route in the file <code>./configure/config.py</code>:</p> <pre><code>@app.route('/config/config1') def config1(): return 'some config data' </code></pre> <p>How do I even go about doing this? Once I run the <code>main.py</code> file, how do I make sure that the other routes are available?</p>
howto
2015-12-29T13:35:56Z
34,514,629
New Python Gmail API - Only Retrieve Messages from Yesterday
<p>I've been updating some scripts to the new Python Gmail API. However, I am confused as how to update the following so that I only retrieve messages from yesterday. Can anyone show me how to do this?</p> <p>The only way I can currently see is to loop through all messages and only parse those with epochs in the correct time range. However, that seems horribly inefficient if I have 1000's of messages. There must be a more efficient way to do this.</p> <pre><code>from apiclient import discovery import oauth2client from oauth2client import client from oauth2client import tools import os import httplib2 import email from apiclient.http import BatchHttpRequest import base64 from bs4 import BeautifulSoup import re import datetime try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None SCOPES = 'https://www.googleapis.com/auth/gmail.readonly' CLIENT_SECRET_FILE = '/Users/sokser/Downloads/client_secret.json' APPLICATION_NAME = 'Gmail API Python Quickstart' def get_credentials(): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json') store = oauth2client.file.Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials def visible(element): if element.parent.name in ['style', 'script', '[document]', 'head', 'title']: return False elif re.match('&lt;!--.*--&gt;', str(element)): return False return True def main(): """Shows basic usage of the Gmail API. Creates a Gmail API service object and outputs a list of label names of the user's Gmail account. """ credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) #Get yesterdays date and the epoch time yesterday = datetime.date.today() - datetime.timedelta(1) unix_time= int(yesterday.strftime("%s")) messages = [] message = service.users().messages().list(userId='me').execute() for m in message['messages']: #service.users().messages().get(userId='me',id=m['id'],format='full') message = service.users().messages().get(userId='me',id=m['id'],format='raw').execute() epoch = int(message['internalDate'])/1000 msg_str = str(base64.urlsafe_b64decode(message['raw'].encode('ASCII')),'utf-8') mime_msg = email.message_from_string(msg_str) #print(message['payload']['parts'][0]['parts']) #print() mytext = None for part in mime_msg.walk(): mime_msg.get_payload() #print(part) #print() if part.get_content_type() == 'text/plain': soup = BeautifulSoup(part.get_payload(decode=True)) texts = soup.findAll(text=True) visible_texts = filter(visible,texts) mytext = ". ".join(visible_texts) if part.get_content_type() == 'text/html' and not mytext: mytext = part.get_payload(decode=True) print(mytext) print() if __name__ == '__main__': main() </code></pre>
howto
2015-12-29T16:02:41Z
34,521,703
Python Flatten Dataframe With Multiple Columns all n-length
<p>I am looking to flatten out a <code>DataFrame</code> where there are multiple groups (below: <code>['a', 'b', 'c']</code>) of columns, each n columns long (below: n=2). There is also stagnant data which does not need to be flattened (below: ['Misc', 'Year']). Below is an example <code>DataFrame</code>:</p> <pre><code>df = pd.DataFrame({ 'Misc': ['A', 'R', 'B'], 'Year': [1991, 1992, 1993], 'a1': [10, 20, 30], 'a2': [40, 50, 60], 'b1': ['h', 'i', 'j'], 'b2': ['k', 'l', 'm'], 'c1': [4.1, 4.2, 4.3], 'c2': [4.4, 4.5, 4.6] }) </code></pre> <p>Produces the following:</p> <pre><code>In [244]: df Out[244]: Misc Year a1 a2 b1 b2 c1 c2 0 A 1991 10 40 h k 4.1 4.4 1 R 1992 20 50 i l 4.2 4.5 2 B 1993 30 60 j m 4.3 4.6 </code></pre> <p>I want the output to be:</p> <pre><code>In [4]: df1 Out[4]: Misc Year a b c 0 A 1991 10 h 4.1 1 A 1991 40 k 4.4 2 R 1992 20 i 4.2 3 R 1992 50 l 4.5 4 B 1993 30 j 4.3 5 B 1993 60 m 4.6 </code></pre> <p>So <code>[ai, bi, ci]</code> moves to a single <code>row</code> while keeping [Misc, Year]. I am working with thousands of 20,000 row datasets so performance is a big issue. I currently am looping per row to separate them, but was hoping there is a better python function for flattening. I have seen panda's 'melt' function but it seems to only work if there is a single group. </p> <p>Ultimately I want to create a helper function which would accept an arbitrary number of 'group' columns, 'stagnant' columns, and value for 'n'. </p> <p>I am currently using pandas but am open to other solutions as well. Thanks for the help! :)</p>
howto
2015-12-30T01:32:20Z
34,527,388
How to click on the text button using selenium python
<p>Hi I'm trying to click on select button using xpath and css selector but it doesn't works</p> <pre><code>browser.find_elements_by_xpath('//div[@class="section-select-all"]').click() browser.find_elements_by_css_selector('#results-container &gt; form &gt; ul &gt; li:nth-child(1) &gt; div &gt; div &gt; button').click() browser.find_elements_by_xpath('//*[@id="results-container"]/form/ul/li[1]/div/div/button').click() </code></pre> <p>please let me know how it would be here is the code </p> <pre><code>&lt;div class="section-actions"&gt;&lt;button type="button" class="section-select-all"&gt;Select 50&lt;span class="screen-reader-text"&gt; for section Dec 11, 2015&lt;/span&gt;&lt;/button&gt;&lt;/div&gt; </code></pre>
howto
2015-12-30T10:12:08Z
34,543,513
Find maximum with limited length in a list
<p>I'm looking for maximum absolute value out of chunked list.</p> <p>For example, the list is:</p> <pre><code>[1, 2, 4, 5, 4, 5, 6, 7, 2, 6, -9, 6, 4, 2, 7, 8] </code></pre> <p>I want to find the maximum with lookahead = 4. For this case, it will return me:</p> <pre><code>[5, 7, 9, 8] </code></pre> <p>How can I do simply in Python?</p> <pre><code>for d in data[::4]: if count &lt; LIMIT: count = count + 1 if abs(d) &gt; maximum_item: maximum_item = abs(d) else: max_array.append(maximum_item) if maximum_item &gt; highest_line: highest_line = maximum_item maximum_item = 0 count = 1 </code></pre> <p>I know I can use for loop to check this. But I'm sure there is an easier way in python.</p>
howto
2015-12-31T08:35:34Z
34,546,949
Send HEX values to SPI on a Raspberry PI B+
<p>I have a LED strip that I want to control with my Raspberry PI. I have connected it to the GPIO10 (MOSI) and GPIO11 (CLK). The SPI module is loaded in Raspbian.</p> <p>I have created a file that I send to <em>/dev/spidev-0.0</em>, when i do that i can control the LEDs.</p> <p>If i send a file that looks like the one below i turn the LED off.</p> <pre><code>00000000 00 00 00 00 80 00 80 00 80 00 80 00 80 00 80 00 ................ 00000010 80 00 80 00 80 00 80 00 80 00 80 00 80 00 80 00 ................ 00000020 80 00 80 00 80 00 80 00 80 00 80 00 80 00 80 00 ................ 00000030 80 00 80 00 80 00 80 00 80 00 80 00 80 00 80 00 ................ 00000040 80 00 80 00 80 00 80 00 80 00 80 00 80 00 80 00 ................ 00000050 80 00 80 00 80 00 80 00 80 00 80 00 80 00 80 00 ................ 00000060 80 00 80 00 80 00 80 00 80 00 .......... </code></pre> <p>If i send a file that looks like the one below i turn the LED on.</p> <pre><code>00000000 00 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF ................ 00000010 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................ 00000020 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................ 00000030 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................ 00000040 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................ 00000050 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................ 00000060 FF FF FF FF FF FF FF FF FF FF .......... </code></pre> <p>My problem is how do i do this in Python? I want to create this strings on the fly and send them to the SPI interface.</p>
howto
2015-12-31T13:05:22Z
34,556,645
how to get the class type in lua / translation from python
<p>I am trying to find something analogous to the class in lua. In python, I would do:</p> <pre><code>a = {} type(a) &gt;&gt;&gt;&gt; dict </code></pre> <p>So I have the object vocab in lua. When I print the object, I get:</p> <pre><code>print(vocab) &gt;&gt;&gt; { 3 : 20 o : 72 m : 70 d : 61 ( : 9 } </code></pre> <p>how can I get lua to spit the object, something analogous to the type() in python? - which will give you the class of the object</p>
howto
2016-01-01T13:46:57Z
34,563,454
Django ImageField upload_to path
<p>I'm having trouble understanding and using Django's ImageField.</p> <p>I have a model:</p> <pre><code>class BlogContent(models.Model): title = models.CharField(max_length=300) image = models.ImageField(upload_to='static/static_dirs/images/') description = models.TextField() </code></pre> <p>My file system is currently:</p> <pre><code>src |---main_project |---app_that_contains_blog_content_model |---static |---static_dirs |---images </code></pre> <p>When I run the server and go to the Admin page, I can add BlogContent objects. After choosing an image for the image field, the image has a temporary name. However, after I save this object I can't find the image in the folder specified by the upload_to path. </p> <p>What is the correct way to do this?</p>
howto
2016-01-02T06:54:41Z
34,569,966
Remove duplicates in python list but remember the index
<p>How can I remove duplicates in a list, keep the original order of the items and remember the first index of any item in the list?</p> <p>For example, removing the duplicates from <code>[1, 1, 2, 3]</code> yields <code>[1, 2, 3]</code> but I need to remember the indices <code>[0, 2, 3]</code>.</p> <p>I am using Python 2.7.</p>
howto
2016-01-02T19:43:35Z
34,576,433
Copy 2D array to a 3D one - Python / NumPy
<p>I programmed a little bit when I was younger but I was never really good. I find Python perfect for what I want to do.</p> <p>I have an Excel file which contains data (64 columns, 18496 lines) that I read using the numpy genfromtxt function. I want to put everything in a 3D matrix named H. I use three loops to do so but I know that this is not the most efficient.</p> <pre><code>data = np.genfromtxt(filename, delimiter = ";",skiprows = 11) H = np.zeros((N,N,Nt)) for k in np.arange(N): for l in np.arange(N): for m in np.arange(Nt): H[k,l,m] = data[m+Nt*k,l] </code></pre> <p>Is there a cleaver (faster computing wise) to do so. I though about using numpy shape but I'm not able to do it.</p> <p>Thanks</p>
howto
2016-01-03T12:15:33Z
34,585,582
how to mask the specific array data based on the shapefile
<h3>Here is my question:</h3> <ul> <li>the 2-d numpy array data represent some property of each grid space</li> <li>the shapefile as the administrative division of the study area(like a city). </li> </ul> <h3>For example:</h3> <p><img src="http://i4.tietuku.com/84ea2afa5841517a.png" alt=""></p> <p>The whole area has 40x40 grids network, and I want to extract the data inside the purple area. In other words , I want to mask the data outside the administrative boundary into np.nan. </p> <h3>My early attempt</h3> <p>I label the grid number and select the specific array data into np.nan. </p> <p><img src="http://i4.tietuku.com/523df4783bea00e2.png" alt=""> </p> <pre><code> value[0,:] = np.nan value[1,:] = np.nan . . . . </code></pre> <p>Can Someone show me a easier method to achieve the target? </p> <h3>Add</h3> <p>Found an answer <a href="http://basemaptutorial.readthedocs.org/en/latest/clip.html" rel="nofollow">here</a> which can plot the raster data into shapefile, but the data itself doesn't change. </p> <h3>Update -2016-01-16</h3> <p>I have already solved this problem inspired by some answers.<br> Someone which are interested on this target, check this two posts which I have asked:<br> 1. <a href="http://stackoverflow.com/questions/34825074/testing-point-with-in-out-of-a-vector-shapefile">Testing point with in/out of a vector shapefile</a><br> 2. <a href="http://stackoverflow.com/questions/25701321/how-to-use-set-clipped-path-for-basemap-polygon/34224925#34224925">How to use set clipped path for Basemap polygon</a> </p> <p>The key step was to test the point within/out of the shapefile which I have already transform into shapely.polygon. </p>
howto
2016-01-04T06:09:59Z
34,587,346
Python: Check if a string contains chinese character?
<p>A string maybe this </p> <pre><code>ipath= "./data/NCDC/上海/虹桥/9705626661750dat.txt" </code></pre> <p>or this</p> <pre><code>ipath = './data/NCDC/ciampino/6240476818161dat.txt' </code></pre> <p>How do I know the first string contains <strong>chinese</strong>?</p> <p>I find this answer maybe helpful: <a href="http://stackoverflow.com/questions/2718196/find-all-chinese-text-in-a-string-using-python-and-regex">Find all Chinese text in a string using Python and Regex</a></p> <p>but it didn't work out: </p> <pre><code>import re ipath= "./data/NCDC/上海/虹桥/9705626661750dat.txt" re.findall(ur'[\u4e00-\u9fff]+', ipath) # =&gt; [] </code></pre>
howto
2016-01-04T08:42:43Z
34,596,082
Writing to a specific column of a text file in python
<p>I have an array of 6 string characters which are of the datatype string and I have to write them in 1,16,19,22,51,54th position of a line respectively in a text file using python to be properly read by a software. </p> <p>The array looks like </p> <pre><code>[ABCD, 1, P, 15-06-2015, 0, Name of the account] </code></pre> <p>The first element of the array is always a 4 or 5 letter string. (should start from 1st position of the line or first column of the line) The second element is always a single digit ( should start at 16) The third element is always a single alphabet (should start at 19) The fourth element is a date (should start at 22) The fifth element is again a single digit (should start at 51) The sixth element is a varying string which contains comments about the array (should start at 54)</p> <p>Also after the sixth element there should be white spaces till 134th column </p> <p>How can I do this in python automatically because I have to similarly write 200 lines.</p> <p>Thanks in advance.</p>
howto
2016-01-04T17:00:47Z
34,598,020
Consolidate duplicate rows of an array
<p>I have a numpy array that I need to consolidate by combining the rows with duplicate entries (based on the first column), while preserving any positive values of the other columns. My array looks like this.</p> <pre><code>array([[117, 0, 1, 0, 0, 0], [163, 1, 0, 0, 0, 0], [117, 0, 0, 0, 0, 1], [120, 0, 1, 0, 0, 0], [189, 0, 0, 0, 1, 0], [117, 1, 0, 0, 0, 0], [120, 0, 0, 1, 0, 0]]) </code></pre> <p>I'm trying to make the output look like this:</p> <pre><code>array([[117, 1, 1, 0, 0, 1], [120, 0, 1, 1, 0, 0], [163, 1, 0, 0, 0, 0], [189, 0, 0, 0, 1, 0]]) </code></pre> <p>I've been able to use <code>unique</code> on column zero to filter out the duplicates, but I can't seem to preserve the values of the other columns. I would appreciate any input! </p>
howto
2016-01-04T19:02:41Z
34,600,056
Using Pandas to fill NaN entries based on values in a different column, using a dictionary as a guide
<p>I have a large dataframe where I'm trying to populate the NaN entries of column B based on the values in column A, using a dictionary as a guide. For example:</p> <pre><code>df = A B 0 Red 628 1 Red 149 2 Red NaN 3 Green 575 4 Green 687 5 Green NaN 6 Blue 159 7 Blue NaN </code></pre> <p>and the dictionary is (for example)</p> <pre><code>dict = {"Red": 123, "Green": 456, "Blue": 789} </code></pre> <p>I am curious as to the best way to replace each NaN with the corresponding number from the dictionary using Pandas. I'm not sure how to use the .fillna() or .isnull() methods in this situation. I'm new to Pandas so any help is appreciated! Thanks. </p>
howto
2016-01-04T21:20:05Z
34,601,770
Create numpy array based on magnitude of difference between arrays
<p>I have 2 numpy arrays:</p> <pre><code>import numpy as np arr_a = np.random.rand(10) arr_b = np.random.rand(10) </code></pre> <p>I want to create an array which contains <code>1</code> in specific position if the difference in magnitude between <code>arr_a</code> and <code>arr_b</code> is greater than specified percentage (say 30%). Right now, I can create the array which contains <code>1</code> if <code>arr_a</code> is greater than <code>arr_b</code> and <code>0</code> otherwise.</p> <pre><code>arr_c = numpy.where(arr_a &gt; arr_b, 1.0, 0.0) </code></pre>
howto
2016-01-04T23:31:14Z
34,607,271
Is it possible to download apk from google play programmatically to PC?
<p>I 'd like to download a lot of apk from google play to PC and install apk on phone for test. I have seen <a href="http://apk-dl.com/" rel="nofollow">http://apk-dl.com/</a> can down apk to pc, so is it possible to do the same thing by using java or python or have some code examples? thanks </p>
howto
2016-01-05T08:35:01Z
34,637,002
Fast and pythonic way to find out if a string is a palindrome
<p>[Edit: as someone pointed out I have used improperly the palindrom concept, now I have edited with the correct functions. I have done also some optimizations in the first and third example, in which the for statement goes until it reach half of the string] </p> <p>I have coded three different versions for a method which checks if a string is a palindrome. The method are implemented as extensions for the class "str"</p> <p>The methods also convert the string to lowercase, and delete all the punctual and spaces. Which one is the better (faster, pythonic)?</p> <p>Here are the methods:</p> <p>1) This one is the first solution that I thought of:</p> <pre><code> def palindrom(self): lowerself = re.sub("[ ,.;:?!]", "", self.lower()) n = len(lowerself) for i in range(n//2): if lowerself[i] != lowerself[n-(i+1)]: return False return True </code></pre> <p>I think that this one is the more faster because there aren't transformations or reversing of the string, and the for statement breaks at the first different element, but I don't think it's an elegant and pythonic way to do so</p> <p>2) In the second version I do a transformation with the solution founded here on stackoverflow (using advanced slicing string[::-1])</p> <pre><code># more compact def pythonicPalindrom(self): lowerself = re.sub("[ ,.;:?!]", "", self.lower()) lowerReversed = lowerself[::-1] if lowerself == lowerReversed: return True else: return False </code></pre> <p>But I think that the slicing and the comparision between the strings make this solution slower.</p> <p>3) The thirds solution that I thought of, use an iterator:</p> <pre><code># with iterator def iteratorPalindrom(self): lowerself = re.sub("[ ,.;:?!]", "", self.lower()) iteratorReverse = reversed(lowerself) for char in lowerself[0:len(lowerself)//2]: if next(iteratorReverse) != char: return False return True </code></pre> <p>which I think is way more elegant of the first solution, and more efficient of the second solution</p>
howto
2016-01-06T15:39:45Z
34,638,457
How to determine type of nested data structures in Python?
<p>I am currently translating some Python to F#, specifically <a href="https://github.com/mnielsen/neural-networks-and-deep-learning" rel="nofollow">neural-networks-and-deep-learning </a>.</p> <p>To make sure the data structures are correctly translated the details of the nested types from Python are needed. The <a href="https://docs.python.org/2/library/functions.html#type" rel="nofollow">type()</a> function is working for simple types but not for nested types.</p> <p>For example in Python:</p> <pre class="lang-py prettyprint-override"><code>&gt; data = ([[1,2,3],[4,5,6],[7,8,9]],["a","b","c"]) &gt; type(data) &lt;type 'tuple'&gt; </code></pre> <p>only gives the type of the first level. Nothing is known about the arrays in the tuple.</p> <p>I was hoping for something like what F# does</p> <pre class="lang-ml prettyprint-override"><code>&gt; let data = ([|[|1;2;3|];[|4;5;6|];[|7;8;9|]|],[|"a";"b";"c"|]);; val data : int [] [] * string [] = ([|[|1; 2; 3|]; [|4; 5; 6|]; [|7; 8; 9|]|], [|"a"; "b"; "c"|]) </code></pre> <p>returning the signature independent of the value</p> <blockquote> <p>int [] [] * string [] </p> <pre><code>* is a tuple item separator int [] [] is a two dimensional jagged array of int string [] is a one dimensional array of string </code></pre> </blockquote> <p>Can or how is this done in Python?</p> <p>TLDR;</p> <p>Currently I am using PyCharm with the debugger and in the variables window clicking the view option for an individual variable to see the details. The problem is that the output contains the values along with the types intermixed and I only need the type signature. When the variables are like (float[50000][784], int[50000]) the values get in the way. Yes I am resizing the variables for now, but that is a workaround and not a solution.</p> <p>e.g.</p> <p>Using <a href="https://www.jetbrains.com/pycharm/" rel="nofollow">PyCharm Community</a></p> <pre><code>(array([[ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], ..., [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.]], dtype=float32), array([7, 2, 1, ..., 4, 5, 6])) </code></pre> <p>Using <a href="https://github.com/spyder-ide/spyder" rel="nofollow">Spyder</a> </p> <p><a href="http://i.stack.imgur.com/XTivP.png" rel="nofollow"><img src="http://i.stack.imgur.com/XTivP.png" alt="Using Spyder variable viewer"></a></p> <p>Using <a href="https://www.visualstudio.com/en-us/products/visual-studio-community-vs.aspx" rel="nofollow">Visual Studio Community</a> with <a href="http://microsoft.github.io/PTVS/" rel="nofollow">Python Tools for Visual Studio</a></p> <pre><code>(array([[ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], ..., [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.]], dtype=float32), array([5, 0, 4, ..., 8, 4, 8], dtype=int64)) </code></pre> <p>EDIT:</p> <p>Since this question has been stared someone is apparently looking for more details, here is my modified version which can also handle <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.ndarray.html" rel="nofollow">numpy ndarray</a>. Thanks to <a href="http://stackoverflow.com/users/469220/vlad">Vlad</a> for the initial version.</p> <p>Also because of the use of a variation of <a href="https://en.wikipedia.org/wiki/Run-length_encoding" rel="nofollow">Run Length Encoding</a> there is no more use of ? for heterogeneous types.</p> <pre><code># Note: Typing for elements of iterable types such as Set, List, or Dict # use a variation of Run Length Encoding. def type_spec_iterable(iterable, name): def iterable_info(iterable): # With an iterable for it to be comparable # the identity must contain the name and length # and for the elements the type, order and count. length = 0 types_list = [] pervious_identity_type = None pervious_identity_type_count = 0 first_item_done = False for e in iterable: item_type = type_spec(e) if (item_type != pervious_identity_type): if not first_item_done: first_item_done = True else: types_list.append((pervious_identity_type, pervious_identity_type_count)) pervious_identity_type = item_type pervious_identity_type_count = 1 else: pervious_identity_type_count += 1 length += 1 types_list.append((pervious_identity_type, pervious_identity_type_count)) return (length, types_list) (length, identity_list) = iterable_info(iterable) element_types = "" for (identity_item_type, identity_item_count) in identity_list: if element_types == "": pass else: element_types += "," element_types += identity_item_type if (identity_item_count != length) and (identity_item_count != 1): element_types += "[" + `identity_item_count` + "]" result = name + "[" + `length` + "]&lt;" + element_types + "&gt;" return result def type_spec_dict(dict, name): def dict_info(dict): # With a dict for it to be comparable # the identity must contain the name and length # and for the key and value combinations the type, order and count. length = 0 types_list = [] pervious_identity_type = None pervious_identity_type_count = 0 first_item_done = False for (k, v) in dict.iteritems(): key_type = type_spec(k) value_type = type_spec(v) item_type = (key_type, value_type) if (item_type != pervious_identity_type): if not first_item_done: first_item_done = True else: types_list.append((pervious_identity_type, pervious_identity_type_count)) pervious_identity_type = item_type pervious_identity_type_count = 1 else: pervious_identity_type_count += 1 length += 1 types_list.append((pervious_identity_type, pervious_identity_type_count)) return (length, types_list) (length, identity_list) = dict_info(dict) element_types = "" for ((identity_key_type,identity_value_type), identity_item_count) in identity_list: if element_types == "": pass else: element_types += "," identity_item_type = "(" + identity_key_type + "," + identity_value_type + ")" element_types += identity_item_type if (identity_item_count != length) and (identity_item_count != 1): element_types += "[" + `identity_item_count` + "]" result = name + "[" + `length` + "]&lt;" + element_types + "&gt;" return result def type_spec_tuple(tuple, name): return name + "&lt;" + ", ".join(type_spec(e) for e in tuple) + "&gt;" def type_spec(obj): object_type = type(obj) name = object_type.__name__ if (object_type is int) or (object_type is long) or (object_type is str) or (object_type is bool) or (object_type is float): result = name elif object_type is type(None): result = "(none)" elif (object_type is list) or (object_type is set): result = type_spec_iterable(obj, name) elif (object_type is dict): result = type_spec_dict(obj, name) elif (object_type is tuple): result = type_spec_tuple(obj, name) else: if name == 'ndarray': ndarray = obj ndarray_shape = "[" + `ndarray.shape`.replace("L","").replace(" ","").replace("(","").replace(")","") + "]" ndarray_data_type = `ndarray.dtype`.split("'")[1] result = name + ndarray_shape + "&lt;" + ndarray_data_type + "&gt;" else: result = "Unknown type: " , name return result </code></pre> <p>I would not consider it done, but it has worked on everything I needed thus far.</p>
howto
2016-01-06T16:55:14Z
34,672,986
detecting POS tag pattern along with specified words
<p>I need to identify certain POS tags before/after certain specified words, for example the following tagged sentence: </p> <pre><code>[('This', 'DT'), ('feature', 'NN'), ('would', 'MD'), ('be', 'VB'), ('nice', 'JJ'), ('to', 'TO'), ('have', 'VB')] </code></pre> <p>can be abstracted to the form "would be" + Adjective</p> <p>Similarly: </p> <pre><code>[('I', 'PRP'), ('am', 'VBP'), ('able', 'JJ'), ('to', 'TO'), ('delete', 'VB'), ('the', 'DT'), ('group', 'NN'), ('functionality', 'NN')] </code></pre> <p>is of the form "am able to" + Verb </p> <p>How can I go about checking for these type of a pattern in sentences. I am using NLTK. </p>
howto
2016-01-08T08:59:02Z
34,683,678
Python - list of dicts into function that only accepts *dicts
<p>I have a function that takes as input multiple dictionaries:</p> <pre><code>def multi_dicts(*dicts): </code></pre> <p>I have a variable that is a list of multiple dictionaries:</p> <pre><code>list_of_dicts=[{'2014-09': 209.0, '2014-08': 243.0},{'2014-09': 40.0, '2014-08': 300.0},{'2014-09': 100.0, '2014-08': 2.0}] </code></pre> <p>Is there a way to use those dictionaries inside the list_of_dicts as arguments of <code>multi_dicts(*dicts)</code>, assuming that we do not know how many dictionaries will be inside list_of_dicts (it varies a lot)?</p> <p>In a gross manner, would look like this:</p> <pre><code>multi_dicts(*dictionaries_found_inside_list_of_dicts) </code></pre>
howto
2016-01-08T18:26:28Z
34,687,883
Starting/stopping a background Python process wtihout nohup + ps aux grep + kill
<p>I usually use:</p> <pre><code>nohup python -u myscript.py &amp;&gt; ./mylog.log &amp; # or should I use nohup 2&gt;&amp;1 ? I never remember </code></pre> <p>to start a background Python process that I'd like to continue running even if I log out, and:</p> <pre><code>ps aux |grep python # check for the relevant PID kill &lt;relevantPID&gt; </code></pre> <p>It works but it's a annoying to do all these steps.</p> <p>I've read some methods in which you need to save the PID in some file, but that's even more hassle.</p> <hr> <p><strong>Is there a clean method to easily start / stop a Python script?</strong> like:</p> <pre><code>startpy myscript.py # will automatically continue running in # background even if I log out # two days later, even if I logged out / logged in again the meantime stoppy myscript.py </code></pre> <p>Or could this long part <code>nohup python -u myscript.py &amp;&gt; ./mylog.log &amp;</code> be written in the shebang of the script, such that I could start the script easily with <code>./myscript.py</code> instead of writing the long nohup line?</p> <hr> <p><em>Note : I'm looking for a one or two line solution, I don't want to have to write a dedicated systemd service for this operation</em>.</p>
howto
2016-01-08T23:36:45Z
34,696,853
Convert list of strings to int
<p>I have a list of strings that I want to convert to int, or have in int from the start.</p> <p>The task is to extract numbers out of a text (and get the sum). What I did was this:</p> <pre><code>for line in handle: line = line.rstrip() z = re.findall("\d+",line) if len(z)&gt;0: lst.append(z) print (z) </code></pre> <p>Which gives me a list like <code>[['5382', '1399', '3534'], ['1908', '8123', '2857']</code>. I tried <code>map(int,...</code> and one other thing, but I get errors such as: </p> <pre><code>TypeError: int() argument must be a string, a bytes-like object or a number, not 'list' </code></pre>
howto
2016-01-09T17:48:40Z
34,715,227
how to write two elements into one row in Python
<p>The objective is very simple, suppose I have a data array <code>x</code>, and a label array <code>y</code>, they are two separated files. For example:</p> <pre><code>x= [['first sentence'],['second sentence'],['third sentence']] y= [1,0,1] </code></pre> <p>I want to get a combined 3*2 csv file as:</p> <pre><code>first sentence, 1 second sentence, 0 third sentence, 1 </code></pre> <p>Is there any easy way to do the job? My code is to import <code>csv</code> package and use a double loop, but I am sure there exist a simpler way.</p>
howto
2016-01-11T06:13:49Z
34,734,933
Python - Access contents of list after applying Counter from collections module
<p>I've applied the Counter function from the collections module to a list. After I do this, I'm not exactly clear as to what the contents of the new data structure would be characterized as. I'm also not sure what the preferred method for accessing the elements is.</p> <p>I've done something like:</p> <pre><code>theList = ['blue', 'red', 'blue', 'yellow', 'blue', 'red'] newList = Counter(theList) print newList </code></pre> <p>which returns:</p> <pre><code>Counter({'blue': 3, 'red': 2, 'yellow': 1}) </code></pre> <p>How do I access each element and print out something like:</p> <pre><code>blue - 3 red - 2 yellow - 1 </code></pre> <p>Any guidance would be much appreciated.</p> <p>Edit:</p> <p>Thanks to Andy, I think this is a solution to my problem:</p> <pre><code>for i,j in newList.most_common(): print i, j </code></pre>
howto
2016-01-12T03:08:36Z
34,755,636
Date removed from x axis on overlaid plots matplotlib
<p>I am trying to show time series lines representing an effort amount using matplotlib and pandas. </p> <p>I've got my DF's to all to overlay in one plot, however when I do python seems to strip the x axis of the date and input some numbers. (I'm not sure where these come from but at a guess, not all days contain the same data so python has reverted to using an index id number). If I plot any one of these they come up with date on the x-axis. </p> <p>Any hints or solutions to make the x axis show date for the multiple plot would be much appreciated. </p> <p>This is the single figure plot with time axis: <a href="http://i.stack.imgur.com/P954I.png" rel="nofollow"><img src="http://i.stack.imgur.com/P954I.png" alt="single figure plot with time axis"></a></p> <p>Code I'm using to plot is </p> <pre><code>fig = pl.figure() ax = fig.add_subplot(111) ax.plot(b342,color='black') ax.plot(b343,color='blue') ax.plot(b344,color='red') ax.plot(b345,color='green') ax.plot(b346,color='pink') ax.plot(fi,color='yellow') plt.show() </code></pre> <p>This is the multiple plot fig with weird x axis: <a href="http://i.stack.imgur.com/kqLwz.png" rel="nofollow"><img src="http://i.stack.imgur.com/kqLwz.png" alt="multiple plots without time axis"></a></p>
howto
2016-01-12T23:19:27Z
34,769,801
how to pick random items from a list while avoiding picking the same item in a row
<p>I want to iterate through list with random values. However, I want the item that has been picked to be removed from the list for the next trial, so that I can avoid picking the same item in a row; but it should be added back again after.</p> <p>please help me on showing that on this simple example. Thank you</p> <pre><code>import random l = [1,2,3,4,5,6,7,8] for i in l: print random.choice(l) </code></pre>
howto
2016-01-13T14:54:41Z
34,773,317
Python Pandas removing substring using another column
<p>I've tried searching around and can't figure out an easy way to do this, so I'm hoping your expertise can help.</p> <p>I have a pandas data frame with two columns</p> <pre><code>import numpy as np import pandas as pd pd.options.display.width = 1000 testing = pd.DataFrame({'NAME':[ 'FIRST', np.nan, 'NAME2', 'NAME3', 'NAME4', 'NAME5', 'NAME6'], 'FULL_NAME':['FIRST LAST', np.nan, 'FIRST LAST', 'FIRST NAME3', 'FIRST NAME4 LAST', 'ANOTHER NAME', 'LAST NAME']}) </code></pre> <p>which gives me</p> <pre><code> FULL_NAME NAME 0 FIRST LAST FIRST 1 NaN NaN 2 FIRST LAST NAME2 3 FIRST NAME3 NAME3 4 FIRST NAME4 LAST NAME4 5 ANOTHER NAME NAME5 6 LAST NAME NAME6 </code></pre> <p>what I'd like to do is take the values from the 'NAME' column and remove then from the 'FULL NAME' column if it's there. So the function would then return</p> <pre><code> FULL_NAME NAME NEW 0 FIRST LAST FIRST LAST 1 NaN NaN NaN 2 FIRST LAST NAME2 FIRST LAST 3 FIRST NAME3 NAME3 FIRST 4 FIRST NAME4 LAST NAME4 FIRST LAST 5 ANOTHER NAME NAME5 ANOTHER NAME 6 LAST NAME NAME6 LAST NAME </code></pre> <p>So far, I've defined a function below and am using the apply method. This runs rather slow on my large data set though and I'm hoping there's a more efficient way to do it. Thanks!</p> <pre><code>def address_remove(x): try: newADDR1 = re.sub(x['NAME'], '', x[-1]) newADDR1 = newADDR1.rstrip() newADDR1 = newADDR1.lstrip() return newADDR1 except: return x[-1] </code></pre>
howto
2016-01-13T17:35:36Z
34,776,651
Concatenate rows of pandas DataFrame with same id
<p>Say I have a pandas DataFrame such as:</p> <pre><code> A B id 0 1 1 0 1 2 1 0 2 3 2 1 3 0 2 1 </code></pre> <p>Say I want to combine rows with the same id so that the other elements in the rows get put together in a list, so that the above dataframe would become:</p> <pre><code> A B id 0 [1, 2] [1, 1] 0 1 [3, 0] [2, 2] 1 </code></pre> <p>as the first two rows, and the last two rows have the same id. Does pandas have a function to do this? I am aware of the pandas groupby command, but I would like the return type to be a dataframe as well. Thanks.</p>
howto
2016-01-13T20:43:01Z
34,777,323
Opening and closing files in a loop
<p>Say I have a list of tens of thousands of entries, and I want to write them to files. If the item in the list meets some criteria, I'd like to close the current file and start a new one. </p> <p>I'm having a couple of issues, I think they're stemming from the fact that I want to name the files be based on the first entry in that file. Also, the signal to start a new file is based on whether an entry has a field that is the same as the previous one. So, for example imagine I have the list:</p> <pre><code>l = [('name1', 10), ('name1', 30), ('name2', 5), ('name2', 7), ('name2', 3), ('name3', 10)] </code></pre> <p>I'd want to end up with 3 files, <code>name1.txt</code> should contain <code>10</code> and <code>30</code>, <code>name2.txt</code> should have <code>5</code>, <code>7</code> and <code>3</code>, and <code>name3.txt</code> should have <code>10</code>. The list is already sorted by the first element, so all I need to do is check if the first element is the same as the previous and if not, start a new file. </p> <p>At first I tried:</p> <pre><code>name = None for entry in l: if entry[0] != name: out_file.close() name = entry[0] out_file = open("{}.txt".format(name)) out_file.write("{}\n".format(entry[1])) else: out_file.write("{}\n".format(entry[1])) out_file.close() </code></pre> <p>There are a couple of problems with this as far as I can tell. First, the first time through the loop, there's no <code>out_file</code> to close. Second, I can't close the last <code>out_file</code> created, since it's defined inside the loop. The following solves the first problem, but seems clunky:</p> <pre><code>for entry in l: if name: if entry[0] != name: out_file.close() name = entry[0] out_file = open("{}.txt".format(name)) out_file.write("{}\n".format(entry[1])) else: out_file.write("{}\n".format(entry[1])) else: name = entry[0] out_file = open("{}.txt".format(name)) out_file.write("{}\n".format(entry[1])) out_file.close() </code></pre> <p>Is there a better way to do this? </p> <p>And also, this doesn't seem like it should solve the problem of closing the last file, though this code runs fine - am I misunderstanding the scope of <code>out_file</code>? I thought it would be restricted to inside the <code>for</code> loop. </p> <p>EDIT: I should probably have mentioned, my data is far more complex than indicated here... it's not actually in a list, it's a <a href="http://biopython.org/wiki/SeqRecord" rel="nofollow"><code>SeqRecord</code> from BioPython</a></p> <p>EDIT 2: OK, I thought I was simplifying in order to avoid distraction. Apparently had the opposite effect - <em>mea culpa</em>. The following is the equivalent of the second code block above, :</p> <pre><code>from re import sub from Bio import SeqIO def gbk_to_faa(some_genbank): source = None for record in SeqIO.parse(some_genbank, 'gb'): if source: if record.annotations['source'] != source: out_file.close() source = sub(r'\W+', "_", sub(r'\W$', "", record.annotations['source'])) out_file = open("{}.faa".format(source), "a+") write_all_record(out_file, record) else: write_all_record(out_file, record) else: source = sub(r'\W+', "_", sub(r'\W$', "", record.annotations['source'])) out_file = open("{}.faa".format(source), "a+") write_all_record(out_file, record) out_file.close() def write_all_record(file_handle, gbk_record): # Does more stuff, I don't think this is important # If it is, it's in this gist: https://gist.github.com/kescobo/49ab9f4b08d8a2691a40 </code></pre>
howto
2016-01-13T21:26:15Z
34,793,225
Extract from a match to next match if patten found in between
<p>I am beginner in python. I am struggling with a problem which is explained below. I am sharing incomplete python script also which does not work for this problem. I would be grateful if get support or instruction for my script. </p> <p>File looks like this:</p> <pre class="lang-xml prettyprint-override"><code>&lt;Iteration&gt; &lt;Iteration_hit&gt;Elememt1 Element1 abc1 hit 1 . . &lt;/Iteration&gt; &lt;Iteration&gt; &lt;Iteration_hit&gt;Elememt2 Element2 abc2 hit 1 . . &lt;/Iteration&gt; &lt;Iteration&gt; &lt;Iteration_hit&gt;Elememt3 Element3 abc3 hit 1 . . &lt;/Iteration&gt; &lt;Iteration&gt; &lt;Iteration_hit&gt;Elememt4 Element4 abc4 hit 1 . . &lt;/Iteration&gt; </code></pre> <p>I need from <code>&lt;Iteration&gt;</code> to <code>&lt;/Iteration&gt;</code> for Elements list match, which means for Element2 and Element4 the output file should look like this:</p> <pre class="lang-xml prettyprint-override"><code>&lt;Iteration&gt; &lt;Iteration_hit&gt;Elememt2 Element2 abc2 hit 1 . . &lt;/Iteration&gt; &lt;Iteration&gt; &lt;Iteration_hit&gt;Elememt4 Element4 abc4 hit 1 . . &lt;/Iteration&gt; </code></pre> <p>Script</p> <pre class="lang-python prettyprint-override"><code>#!/usr/bin/python x = raw_input("Enter your xml file name: ") xml = open(x) l = raw_input("Enter your list file name: ") lst = open(l) Id = list() ylist = list() import re for line in lst: stuff=line.rstrip() stuff.split() Id.append(stuff) for ele in Id: for line1 in xml: if line1.startswith(" &lt;Iteration_hit&gt;"): y = line1.split() # print y[1] if y[1] == ele: break </code></pre>
howto
2016-01-14T15:23:53Z
34,799,167
Conditionally and interatively calculate column based on value of three columns
<p>I am running Windows 10, Python 2.7 through the Spyder IDE.</p> <p>I have a pandas <code>DataFrame</code> called <code>df</code>:</p> <pre><code>df = pd.DataFrame({'fld1': ['x', 'x', 'x','y','y','y','z','z'] , 'fld2': ['x', 'y', 'z','x','y','z','x','y'] , 'relationship': [.25,.25,.50,.33,.33,.33,.5,.5]}) df Out[172]: fld1 fld2 relationship 0 x x 0.25 1 x y 0.25 2 x z 0.50 3 y x 0.33 4 y y 0.33 5 y z 0.33 6 z x 0.50 7 z y 0.50 </code></pre> <p>I would like build a <code>function</code> that iterates over the rows of a <code>Dataframe</code> <code>df</code> to produce a new column in <code>df</code>.</p> <p>This function would start by:</p> <p><strong>Step 1:</strong> take the <code>relationship</code> column where <code>fld1</code> = <code>x</code> and <code>fld2</code> = <code>x</code> and then </p> <p><strong>Step 2:</strong> check to see if cases where <code>fld1</code> = <code>x</code> has any more unique values of <code>fld2</code>. </p> <p><strong>Step 3:</strong> If there is another unique value of <code>fld2</code> associated with <code>fld1</code> = <code>x</code> (in this two more unique values exist, <code>x</code> and <code>y</code>), add the <code>relationship</code> value from <strong>Step 1</strong> to the <code>relationship</code> column of <code>fld1</code> = <code>x</code> and the next unique value of <code>fld2</code> (in this example <code>fld2</code> = <code>y</code> is the next unique value) multiplied by the inverse of the relationship (in this case <code>fld1</code> = <code>y</code> and <code>fld2</code> = <code>x</code>)</p> <p><strong>Step 4:</strong> repeat <strong>Step 2</strong> until all unique values of <code>fld2</code> with <code>fld1</code> = <code>x</code> have been calculated in this way</p> <p><strong>Step 4:</strong> repeat <strong>Step 1</strong> for the next unique value of <code>fld1</code>. In this case it would be <code>fld1</code> = <code>y</code></p> <p><strong>To explain this function logic another way</strong>, below is an example of how this would be done in <code>excel</code>: </p> <pre><code> A B C D 1 fld1 fld2 relationship Connection 2 x x 0.25 =C2+(C3*C5)+(C4*C8) 3 x y 0.25 =C3+(C4*C9) 4 x z 0.5 =C4+(C3*C7) 5 y x 0.33 =C5+(C7*C8) 6 y y 0.33 =C6+(C5*C3)+(C7*C9) 7 y z 0.33 =C7+(C5*C4) 8 z x 0.5 =C8+(C9*C5) 9 z y 0.5 =C9+(C8*C4) </code></pre> <p>The output of the function should product a <code>Dataframe</code> identical to <code>df2</code> below:</p> <pre><code>df2 = pd.DataFrame({'fld1': ['x', 'x', 'x','y','y','y','z','z'] , 'fld2': ['x', 'y', 'z','x','y','z','x','y'] , 'relationship': [.25,.25,.50,.33,.33,.33,.5,.5] , 'connection': [.5825,0.5,0.5825,0.495,0.5775,0.495,0.665,0.75]}) df2 Out[174]: connection fld1 fld2 relationship 0 0.5825 x x 0.25 1 0.5000 x y 0.25 2 0.5825 x z 0.50 3 0.4950 y x 0.33 4 0.5775 y y 0.33 5 0.4950 y z 0.33 6 0.6650 z x 0.50 7 0.7500 z y 0.50 </code></pre>
howto
2016-01-14T20:31:48Z
34,818,228
How to count number of repeated keys in several dictionaries?
<p>Let's say I have huge number of dictionaries (it could be 10'000 dictionaries). I would like to count number of each key in all dictionaries. I.e. if I have 3 dictionaries: </p> <ul> <li><code>{1: 'url1', 3: 'url2', 7: 'url3', 5: 'url4'}</code></li> <li><code>{1: 'url1', 7: 'url3'}</code></li> <li><code>{5: 'url4', 10: 'url5'}</code></li> </ul> <p>Then in result I should get <code>{1: [2, 'url1'], 10: [1, 'url5'], 3: [1, 'url2'], 5: [2, 'url4'], 7: [2, 'url3']}</code>.</p> <p>I came to the following code:</p> <pre><code>lists = [{1: 'url1', 3: 'url2', 7: 'url3', 5: 'url4'}, {1: 'url1', 7: 'url3'}, {5: 'url4', 10: 'url5'}] result = {} for l in lists: for i in l: if i in result: result[i][0] += 1 else: result[i] = [1, l[i]] </code></pre> <p>Is the any better (faster) way to do it?</p>
howto
2016-01-15T19:18:11Z
34,824,864
Python list and time
<p>I am trying to get the current time and store it when I run a certain OS command ( that runs once a second) so I can plot a graph of time vs output of the command.</p> <p>When I try to store the current time in a list using: (timeList is an empty list)</p> <pre><code>timeList.append (datetime.datetime.time(datetime.datetime.now())) </code></pre> <p>I get this:</p> <pre><code>[datetime.time(23, 57, 8, 86885), datetime.time(23, 57, 8, 87091), datetime.time(23, 57, 9, 90906), datetime.time(23, 57, 10, 95045), datetime.time(23, 57, 10, 95110), datetime.time(23, 57, 10, 95148), datetime.time(23, 57, 10, 95166), datetime.time(23, 57, 10, 95178)] </code></pre> <p>So in one second, instead of just one list item with current time, I get 2, or 3 items). How do I just capture time at that instant and store it in a list so I can use pyplot to plot this?</p>
howto
2016-01-16T08:03:42Z
34,837,194
renaming pcraster mapstack
<p>I have a folder filled with 20 years precipitation pcraster mapstack in days, I've managed to extract from the original netcdf file precipitation value for my interest area and rename it into this to avoid confusion</p> <pre><code>precip.19810101 precip.19810102 precip.19810103 precip.19810104 precip.19810105 ... precip.20111231 </code></pre> <p>but after that, I want to rename all of my files into pcraster mapstack based on this sequence of dates </p> <pre><code>precip00.001 precip00.002 precip00.003 precip00.004 ... </code></pre> <p>I'm a beginner in python, is there any help or example for me to figure it out how to do this? Thank you</p>
howto
2016-01-17T10:14:41Z
34,845,096
How can I sort a 2D list?
<p>I'm working with a 2D list of numbers similar to the example below I and am trying to reorder the columns:</p> <pre><code>D C B A 1 3 2 0 1 3 2 0 1 3 2 0 </code></pre> <p>The first row of the list is reserved for letters to reference each column. How can I sort this list so that these columns are placed in alphabetical order to achieve the following:</p> <pre><code>D C B A A B C D 1 3 2 0 0 2 3 1 1 3 2 0 0 2 3 1 1 3 2 0 0 2 3 1 </code></pre> <p>I've found examples that make use of lambdas for sorting, but have not found any similar examples that sort columns by characters.</p> <p>I'm not sure how to achieve this sorting and would really appreciate some help.</p>
howto
2016-01-17T23:32:21Z
34,859,683
Reorder a dictionary to fit a data frame
<p>I have I <code>dictionary</code> in this format:</p> <pre><code>d = {'Name 1': list_of_links,'Name 2': list_of_links,'Name 3': list_of_links} </code></pre> <p>need to put this data in a <code>DataFrame</code>, with two <code>columns</code>:</p> <pre><code>Names and Links Name 1 -&gt; Link Name 1 -&gt; Link ... ... Name 2 -&gt; Link Name 2 -&gt; Link ... .... Name 3 -&gt; Link Name 3 -&gt; Link </code></pre> <p>I've try this:</p> <pre><code>links = [] names = [] for key in d: names.append(key) links.append(d[key]) </code></pre> <p>and then to match the length</p> <pre><code>for i in range(len(names)): names[i] =[names[i]]*len(links[i]) </code></pre> <p>And finally copy all the values in two new lists, but it doesn't seem like a good aproach</p>
howto
2016-01-18T16:35:23Z
34,871,024
Combine methods with identical structure but different parameters
<p>How would I more efficiently combine these two methods into one?</p> <p>They have identical structure but different parameters ('key_A', 'key_B') and different storage variables (self.storage_a, self.storage_b)</p> <p>I could make key_X be an input to a generic method, but it seems tacky to pass in self.storage_X when self is already being passed.</p> <pre><code>def method_a(self): some_list = list(irrelevant_extraction_function('key_A', self.some_dict)) self.storage_a = [item['address'] for item in some_list] def method_b(self): some_list = list(irrelevant_extraction_function('key_B', self.some_dict)) self.storage_b = [item['address'] for item in some_list] </code></pre>
howto
2016-01-19T07:38:44Z
34,906,231
How to return both string and value within HttpResponse?
<p>I need the code to return a string and value in HttpResponse but it returns only first value(val). Why should I do to return both val and val2? String I will use as message and I need val in function return to use it as value in next function,something like this: </p> <pre><code>def func1(request): data = json.loads(request.body) val = "string" val2 = data['email'] return HttpResponse(val, val2) def func2(): val3 = func1 val4 = "client %s" % val2 if val4: return True else: return False </code></pre>
howto
2016-01-20T17:09:19Z
34,906,286
Groupby in a list for python
<p>Given a large dataset of one million records, I am looking for ways to do a group by. I am new to python, but i know in SQL there's a groupby function and i am guessing it might be applicable. </p> <p>What i want to achieve is this, </p> <p>From</p> <pre><code>["A", 4] ["B", 4] ["F", 3] ["A", 4] ["B", 1] </code></pre> <p>To</p> <pre><code>["A", (4,4)] ["B", (1,4)] ["F", (3)] </code></pre> <p>I am also looking for an efficient way to calculate the average of the list of ratings. So finally the output should be:</p> <pre><code>["A", 4] ["B", 2.5] ["F", 3] </code></pre> <p>I've tried to do a iterative approach to it but the error thrown was "there was too much data to unpack". Here is my solution which is not workng for the dataset. </p> <pre><code>len = max(key for (item, key) in results) newList = [[] for i in range(len+1)] for item, key in results: newList[key].append(item) </code></pre> <p>I am looking for efficient way to do it, is there a way to do a groupby in list comprehension? Thanks! </p>
howto
2016-01-20T17:11:54Z
34,910,228
Change object's variable from different file
<p>I want to access object (specifically its variables) from functions defined in different file. Let's see an example:</p> <p>File 1 - <code>grail.py</code></p> <pre><code>import enemies class Encounter: def __init__(self): self.counter = 1 self.number = 0 self.who = "We've encountered no one." def forward(self): if self.counter == 1: enemies.knightofni() elif self.counter == 2: enemies.frenchman() else: self.number = 42 self.who = "We've found the Grail!" self.counter += 1 knight = Encounter() for i in range(4): print(str(knight.number) + " " + knight.who) knight.forward() </code></pre> <p>File 2 - <code>enemies.py</code> (I probably need something in this file)</p> <pre><code>def knightofni(): Object.number = 1 Object.who = "We've encountered Knight of Ni." def frenchman(): Object.number = 4 Object.who = "We've encountered French." </code></pre> <p>Output should show:</p> <pre><code>0 We've encountered no one. 1 We've encountered Knight of Ni. 4 We've encountered French. 42 We've found the Grail! </code></pre> <p>I know you can achieve the output by returning something from functions in file <code>enemies.py</code>, for example function <code>frenchman()</code> could look like:</p> <pre><code>def frenchman(): return [4, "We've encountered French."] </code></pre> <p>and in <code>grail.py</code> I should change code to collect what the <code>frenchman()</code> returns:</p> <pre><code>... elif self.counter == 2: spam = enemies.frenchman() self.number = spam[0] self.who = spam[1] ... </code></pre> <p>but it uses additional resources, makes the code longer, and more cumbersome in more complicated situations.</p> <p>Is there a way to do the job directly on the object's variables but keeping functions in separate file?</p> <p>EDIT There are already answers to this question but maybe I will add clarification seeing doubt in one of the answers (citing comment to this answer):</p> <blockquote> <p>I want it to be possible to add other "enemies" without making lengthy code in this place (so <code>forward()</code> is kind of a wrapper, place where it is decided what to do in different situations). It is also more readable if this functions are in different file.</p> <p>Think of situation where there would be 100 "enemies" and each would need to change 100 variables which are lists with 1M entries each. Is there a better way than putting "enemies" into other file and changing variables directly in the file?</p> </blockquote>
howto
2016-01-20T20:48:51Z
34,914,655
Python C API - How to construct object from PyObject
<p>I'm looking to find out if there's a nice, "native" way to construct an object given a <code>PyObject*</code> that is known to be a type.</p> <p>Here is my code as it stands:</p> <h1>C++</h1> <pre><code>void add_component(boost::python::object&amp; type) { auto constructed_type = type(); // doesn't construct anything! } </code></pre> <h1>Python</h1> <pre><code>o = GameObject() o.add_component(CameraComponent) </code></pre> <p>My code is executing the entire function perfectly fine, but the constructor is never triggered for <code>CameraComponent</code>.</p> <p>So my question is, how do I, given a <code>PyObject*</code> that is known to a be a type, construct an instance of that type?</p> <p>Many thanks in advance.</p>
howto
2016-01-21T02:59:46Z
34,929,717
Get list of column names for columns that contain negative values
<p>This is a simple question but I have found "slicing" <code>DataFrames</code> in <code>Pandas</code> frustrating, coming from <code>R</code>. </p> <p>I have a <code>DataFrame</code> <code>df</code> below with 7 columns:</p> <pre><code>df Out[77]: fld1 fld2 fld3 fld4 fld5 fld6 fld7 0 8 8 -1 2 1 7 4 1 6 6 1 7 5 -1 3 2 2 5 4 2 2 8 1 3 -1 -1 7 2 3 2 0 4 6 6 4 2 0 5 2 5 -1 5 7 1 5 8 2 6 7 1 -1 0 1 8 1 7 6 2 4 1 2 6 1 8 3 4 4 5 8 -1 4 9 4 4 3 7 7 4 5 </code></pre> <p>How do I slice <code>df</code> in such a way that it produces a list of columns that contain at least one negative number?</p>
howto
2016-01-21T16:56:04Z
34,930,630
grouping an unknown number of arguments with argparse
<p>I am designing the user interface for a command line program that needs to be able to accept one or more groups of options. Each group is the same, but needs to be linked together, like so:</p> <pre><code>./myprogram.py --group1 name1,name2,pathA,pathB --group2 name3,name4,pathC,pathD </code></pre> <p>This seems very clunky for a user to deal with. I have considered using a <code>INI</code>-style <code>configparser</code> setup, but it is also clunky, because I have a lot of other arguments besides this that generally have default values, and then I lose all of the power of the <code>argparse</code> module for handling requirements, checking if files exist, etc.</p> <p>Does anyone have any ideas on how I could best structure my <code>ArgumentParser</code> so that I can get a user to provide the four required inputs for a given group, together? I am not married to the comma separated list, that was just an example. It would actually be far better if they could enter some sort of key-value pair, such as</p> <pre><code>./myprogram.py --group1 firstname:name1 secondname:name2 firstpath:pathA secondpath:pathB </code></pre> <p>But I know that argparse does not support the <code>dict</code> type, and any hack to allow it would be even less user-friendly.</p>
howto
2016-01-21T17:39:38Z
34,931,548
How to get the 'cardinal' day of the year in Pandas?
<p>My df looks like this, where 'O', is the ordinal date of the year.</p> <pre><code> Close O Date 1950-01-03 16.66 3 1950-01-04 16.85 4 1950-01-05 16.93 5 1950-01-06 16.98 6 1950-01-09 17.08 9 1950-01-10 17.03 10 1950-01-11 17.09 11 1950-01-12 16.76 12 1950-01-13 16.67 13 1950-01-16 16.71 16 </code></pre> <p>I would like to have the cardinal day of the year given the data set. The desired outcome is:</p> <pre><code> Close O C Date 1950-01-03 16.66 3 1 1950-01-04 16.85 4 2 1950-01-05 16.93 5 3 1950-01-06 16.98 6 4 1950-01-09 17.08 9 5 1950-01-10 17.03 10 6 1950-01-11 17.09 11 7 1950-01-12 16.76 12 8 1950-01-13 16.67 13 9 1950-01-16 16.71 16 10 </code></pre> <p>Note: Data set is many years long, so the key is that the count restarts every time there's a new year in the index.</p> <p>Thanks</p>
howto
2016-01-21T18:29:39Z
34,950,064
String slicing with delimiter changing in length
<p>Probably an easy one, but I didn't find a solution by now. My text file that I import into python has a space delimited structure such as</p> <pre><code>20.06.2009 05:00:00 2.6 20.06.2009 06:00:00 21.5 </code></pre> <p>I want to split this into a time and a value variable. Slicing the time component is straightforward</p> <pre><code>time = "" value = "" for i in lines: time += i[0:20] </code></pre> <p>But I can't find a solution for the value component as it contains mostly 3 digits, but sometimes 4, so the number of space delimiters change between time and value (that's why the <code>re</code> package doesn't work here). Any solutions?</p>
howto
2016-01-22T15:20:51Z
34,959,948
Parse valid JSON object or array from a string
<p>I have a string that can be one of two forms:</p> <pre><code>name multi word description {...} </code></pre> <p>or</p> <pre><code>name multi word description [...] </code></pre> <p>where <code>{...}</code> and <code>[...]</code> are any valid JSON. I am interested in parsing out just the JSON part of the string, but I'm not sure of the best way to do it (especially since I don't know which of the two forms the string will be). This is my current method:</p> <pre><code>import json string = 'bob1: The ceo of the company {"salary": 100000}' o_ind = string.find('{') a_ind = string.find('[') if o_ind == -1 and a_ind == -1: print("Could not find JSON") exit(0) index = min(o_ind, a_ind) if index == -1: index = max(o_ind, a_ind) json = json.loads(string[index:]) print(json) </code></pre> <p>It works, but I can't help but feel like it could be done better. I thought maybe regex, but I was having trouble with it matching sub objects and arrays and not the outermost json object or array. Any suggestions?</p>
howto
2016-01-23T05:22:38Z
34,962,104
Pandas: How can I use the apply() function for a single column?
<p>I have a pandas data frame with two columns. I need to change the values of the first column without affecting the second one and get back the whole data frame with just first column values changed. How can I do that using apply in pandas?</p>
howto
2016-01-23T10:04:27Z
34,970,283
What is the pythonic way to sort a list with multiple attributes, such that the first is sorted reversely but the second is not?
<p>Given a list</p> <pre><code>[ ['a','b'], ['x','y'], ['a','y'], ['x', 'b'] ] </code></pre> <p>How can I sort it in a way that the first element is sorted decreasingly, but the second element is sorted increasingly when the first element equal? The strings can be arbitrarily long in this list.</p> <p>The sorted list should be</p> <pre><code>[ ['x', 'b'], ['x', 'y'], ['a', 'b'], ['a', 'y'] ] </code></pre> <p>I'm thinking about using one single call of <code>sorted</code>, but making up a key to reflect this seems not working.</p>
howto
2016-01-23T23:31:46Z
34,977,252
Using Numba to improve finite-differences laplacian
<p>I am using Python to solve a reaction-diffusion system of equations (<a href="https://en.wikipedia.org/wiki/FitzHugh%E2%80%93Nagumo_model" rel="nofollow">Fitz-Hugh-Nagumo model</a>). I would like to learn how to use Numba in order to accelerate the calculation. I am currently importing the following laplacian.py module to my integration script:</p> <pre><code>def neumann_laplacian_1d(u,dx2): """Return finite difference Laplacian approximation of 2d array. Uses Neumann boundary conditions and a 2nd order approximation. """ laplacian = np.zeros(u.shape) laplacian[1:-1] = ((1.0)*u[2:] +(1.0)*u[:-2] -(2.0)*u[1:-1]) # Neumann boundary conditions # edges laplacian[0] = ((2.0)*u[1]-(2.0)*u[0]) laplacian[-1] = ((2.0)*u[-2]-(2.0)*u[-1]) return laplacian/ dx2 </code></pre> <p>Where <code>u</code> is a NumPy 1D array that stands for one of the fields. I tried to add the decorator <code>@autojit(target="cpu")</code> after importing <code>from numba import autojit</code>. I didn't see any improvement in the calculation. Could anyone give me a hint how to use Numba properly in this case?</p> <p>The input array I have used here is</p> <pre><code>a = random.random(252) </code></pre> <p>And so I've compared the performance with the line:</p> <pre><code>%timeit(neumann_laplacian_1d(a,1.0)) </code></pre> <p>With Numba I got:</p> <pre><code>%timeit(neumann_laplacian_1d(a,1.0)) The slowest run took 22071.00 times longer than the fastest. This could mean that an intermediate result is being cached 1 loops, best of 3: 14.1 µs per loop </code></pre> <p>Without Numba I got (!!):</p> <pre><code>%timeit(neumann_laplacian_1d(a,1.0)) The slowest run took 11.84 times longer than the fastest. This could mean that an intermediate result is being cached 100000 loops, best of 3: 9.12 µs per loop </code></pre> <p>Numba actually make it slower..</p>
howto
2016-01-24T14:58:49Z
34,980,059
Difference of elements to find same adjacent
<p>I just started learning Pythonby myself last night. I have accomplished a few simple things like getting a file from a user, opening and reading that file into a list line by line, calculating the number of integers per line, calculating the number of unique integers per line using set, and calculating the number that appears the most per line.</p> <p>An additional interesting concept that I am looking into and would like to accomplish is calculating the number of integers based on the number of adjacent integers. That might sound a bit confusing so I will explain below:</p> <p>Say I have a list with the values:</p> <pre><code>['1', '2', '2', '2', '2', '2', '3', '3', '4', '4', '4', '4', '5', '5', '6', '7', '7', '7', '1', '1\n'] </code></pre> <p>(I believe I would have to convert the strings to int?) The first integer is a 1 and the second integer is a 2. The difference is not 0 is the two integers are not the same so do not increment a counter. Take the next integer which is a 2 and the previous integer which is a 2. The difference is 0 so the two integers are the same so increment a counter. And so on. The final value would be 8 in this case.</p> <p>I looked in adjacent integer calculations on SO and the Internet, and only found subtraction algorithms which I thought could apply.</p> <p>Here is what I have so far without currently complicating with converting the strings to int (which I have a question on after pertaining to this, please):</p> <pre><code>x = [1,2,2,2,2,2,3,3,4,4,4,4,5,5,6,7,7,7,1,1] count = 0 xdiff = [x[n]-x[n-1] for n in range(1,len(x))] print xdiff all([xdiff[0] == xdiff[n] for n in range(1,len(xdiff))]) for n in range(1,len(xdiff)): last = x[n-1] if xdiff!=0: print "Different numbers" print last if xdiff==0: print "Same numbers" count+=1 </code></pre> <p>Here is the output:</p> <pre><code>[1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, -6, 0] Different numbers 7 </code></pre> <p>The first to prints are just for testing, but the last print should be 9 when the calculations are correct.</p> <p>Any suggestions of how to improve my algorithm to calculate the total number of integers in a list excluding the same adjacent integers (like I demonstrated above for clarification)? Also, since I just started teaching myself Python, any suggestions on general improvement for my code is greatly appreciated. Thank you.</p> <p>UPDATE: So I realized that my calculation value is incorrect and the total number should be 8 and not 9. Here is a better explanation: I have the following numbers in a list: [1,2,2,2,2,2,3,3,4,4,4,4,5,5,6,7,7,7,1,1] There are 20 elements total. The number of adjacent integers is 8. Start at 1 and look at 2. 1 and 2 are not the same so increment. Look at next value of 2 and previous value of 2. 2 and 2 are the same. Look at the next value of 2 and the previous value of 2. 2 and 2 are the same. Look at the next value of 2 and the previous value of 2. 2 and 2 are the same. Look at the next value of 2 and the previous value of 2. 2 and 2 are the same. Look at the next value of 3 and the previous value of 2. 3 and 2 are not the same so increment. And so on. </p> <p>Now all of the answers are one less than the correct answer, so is that due to the starting at data[0] and I just need to add one to my total?</p> <p>UPDATE: Output:</p> <pre><code>['1', '2', '3', '4', '5', '6', '5', '4', '5\n'] bursts: 0 ['14', '62', '48', '14\n'] bursts: 0 ['1', '3', '5', '7', '9\n'] bursts: 0 ['123', '456', '789', '1234', '5678\n'] bursts: 0 ['34', '34', '34', '34', '34\n'] bursts: 4 ['1\n'] bursts: 0 ['1', '2', '2', '2', '2', '2', '3', '3', '4', '4', '4', '4', '5', '5', '6', '7', '7', '7', '1', '1\n'] bursts: 12 </code></pre> <p>Code:</p> <pre><code>#Open the file corresponding to the name of the file #the user entered. Open and read the file. with open(filename, 'r') as file: #Read the file in line by line for line in file: #Remove all empty lines and lines that start with a # sign if line.strip() and not line.startswith("#"): #Calculate the number of integers per line names_list.append(line) #print "integers:", len(line.split()) print names_list #Calculate the number of bursts result = sum(int(names_list[i]) == int(names_list[i+1]) for i in range(len(names_list)-1)) print "bursts:", result </code></pre> <p>Output should be:</p> <pre><code>bursts:9 bursts:4 bursts:5 bursts:5 bursts:1 bursts:1 bursts:8 </code></pre>
howto
2016-01-24T19:01:17Z
34,982,928
Return rows only if all items of category are True
<p>After some work, I managed to simplify a dataframe that looks like the following: </p> <pre><code>Category | Boolean A | True A | True A | False B | True B | True C | True C | True B | False D | True C | True </code></pre> <p>Now, I would like to obtain the rows which categories only have True in column 'Boolean'. Another way of saying this would be: return rows only that for a given category only True is present in column 'Boolean'.</p> <p>From the example DF above, I would be looking to obtain: </p> <pre><code>Category | Boolean C | True C | True D | True C | True </code></pre> <p>No row with category A or B should be returned because at least one of the rows with this categories has a False. However, since for categories C and D all rows were True, we should return all rows with these categories. </p> <p>In my real dataframe there are more columns but none of them is unique and none of them is relevant for slicing it. If you do need an extra column for your solution please make up one instead of using index, if possible but not essential. </p> <p>Hope it is clear enough. Thank you in advance!</p>
howto
2016-01-24T23:33:34Z
35,005,907
re.split with spaces in python
<p>I have a string of text that looks like this:</p> <pre><code>' 19,301 14,856 18,554' </code></pre> <p>Where is a space.</p> <p>I'm trying to split it on the white space, but I need to retain all of the white space as an item in the new list. Like this:</p> <pre><code>[' ', '19,301',' ', '14,856', ' ', '18,554'] </code></pre> <p>I have been using the following code:</p> <pre><code>re.split(r'( +)(?=[0-9])', item) </code></pre> <p>and it returns: </p> <pre><code>['', ' ', '19,301', ' ', '14,856', ' ', '18,554'] </code></pre> <p>Notice that it always <strong>adds an empty element to the beginning of my list</strong>. It's easy enough to drop it, but I'm really looking to understand what is going on here, so I can get the code to treat things consistently. Thanks.</p>
howto
2016-01-26T02:03:58Z
35,011,168
How to call __setattr__() correctly in Python3 as part of a class?
<p>I want to call a function when an object attribute is set:</p> <pre><code>class MyClass(): myattrib = None def __setattr__(self, prop, val): self.myattrib = val print("setting myattrib") x = MyClass() x.myattrib = "something" </code></pre> <p>The problem is, that this creates an infinite recursion.</p> <p>The idea is to call a function when a member variable is set (and actually set that member variable), but at the same time run extra code (showcased with the <code>print()</code> statement in the example above).</p> <p>The other obvious way to do this, is using <code>set_attrib()</code> functions, as is common in Java, but I'd like to do it the <em>pythonic</em> way, and set the attributes directly, but at the same time running extra code.</p>
howto
2016-01-26T10:00:31Z
35,015,693
How do I transform a multi-level list into a list of strings in Python?
<p>I have a list that looks something like this:</p> <pre><code>a = [('A', 'V', 'C'), ('A', 'D', 'D')] </code></pre> <p>And I want to create another list that transforms <code>a</code> into:</p> <pre><code>['AVC', 'ADD'] </code></pre> <p>How would I go on to do this?</p>
howto
2016-01-26T14:06:08Z
35,017,035
Compare elements of a list of lists and return a list
<p>I have a list of lists, I don't know the length of the main list but each 'sublist' contains necessarily 6 floats. I need to compare each float of each sublist and keep the smaller one for the first three floats and the higher one for the last three and finally, I need to return all these values in a 6-float list in the same order.</p> <p>Here is an example:</p> <pre><code>list1 = [[-2.0, 0.0, -2.0, 2.0, 10.0, 2.0], [-1.0, 0.0, 2.0, 1.0, 5.0, 4.0]] # Compare list1[0][0] with list1[1][0] # Will return -2.0 (because the index is between 0 and 2 so it returns the lower float) # Compare list1[0][4] with list1[1][4] # Will return 10.0 (because the index is between 3 and 5 so it returns the higher float) # The final result which should be returned is: # [-2.0, 0.0, -2.0, 2.0, 10.0, 4.0] list2 = [[-2.0, 0.0, -2.0, 2.0, 10.0, 2.0], [-1.0, 0.0, 2.0, 1.0, 5.0, 4.0], [3.0, 0.0, -1.0, 4.0, 1.0, 0.0]] # Compare list2[0][2] with list2[1][2] with list2[2][2] # Will return -2.0 (because the index is between 0 and 2 so it returns the lower float) # The final result which should be returned is: # [-2.0, 0.0, -2.0, 4.0, 10.0, 4.0] </code></pre> <p>I read about <code>zip()</code>, sets, list comprehension and different topics on this site but I couldn't achieve what I want.</p>
howto
2016-01-26T15:07:32Z
35,020,513
Python & Beautifulsoup web scraping - select a paragraph with a specific child tag
<p>I'm trying to isolate the "text of interest" text from the last paragraph in the following sequence:</p> <pre><code>&lt;div class='div_name_class'&gt; &lt;p&gt; &lt;span class='class_name_1' title='title1'&gt;val1&lt;/span&gt; &lt;span class='class_name_1' title='title2'&gt;val2&lt;/span&gt; &lt;/p&gt; &lt;p&gt;&lt;span class='class_name_2'&gt;&lt;em&gt;text of no interest&lt;/em&gt;&lt;/span&gt;text of interest&lt;/p&gt; </code></pre> <p></p> <p>I tried so far with:</p> <pre><code>print soup.find('span', attrs={'class': 'class_name_2'}).parent.text print soup.find('em').parent.parent.text </code></pre> <p>but both return: "text of no interesttext of interest"</p> <p>I'm aware that the "text of interest" can be separated from the above result but it doesn't look like an elegant solution.</p> <p>Thanks for suggestions. </p>
howto
2016-01-26T17:52:32Z
35,025,400
Sort list with multiple criteria in python
<p>Currently I'm trying to sort a list of files which were made of version numbers. For example:</p> <pre><code>0.0.0.0.py 1.0.0.0.py 1.1.0.0.py </code></pre> <p>They are all stored in a list. My idea was to use the <code>sort</code> method of the list in combination with a lambda expression. The lambda-expression should first remove the <code>.py</code> extensions and than split the string by the dots. Than casting every number to an integer and sort by them.</p> <p>I know how I would do this in c#, but I have no idea how to do this with python. One problem is, how can I sort over multiple criteria? And how to embed the lambda-expression doing this?</p> <p>Can anyone help me?</p> <p>Thank you very much!</p>
howto
2016-01-26T22:37:12Z
35,061,363
convert xlsx files to xls inside folders and subfolders in Excel VBA or Python
<p>I am trying to convert xlsx files into xls using vba macro or python code.So far,I could get some help on converting files in a single folder using the below code:</p> <pre><code>Sub ProcessFiles() Dim Filename, Pathname, saveFileName As String Dim wb As Workbook Dim initialDisplayAlerts As Boolean Pathname = "" Filename = Dir(Pathname &amp; "*.xlsx") initialDisplayAlerts = Application.DisplayAlerts Application.DisplayAlerts = False Do While Filename &lt;&gt; "" Set wb = Workbooks.Open(Filename:=Pathname &amp; Filename, _ UpdateLinks:=False) wb.CheckCompatibility = False saveFileName = Replace(Filename, ".xlsx", ".xls") wb.SaveAs Filename:=Pathname &amp; saveFileName, _ FileFormat:=xlExcel8, Password:="", WriteResPassword:="", _ ReadOnlyRecommended:=False, CreateBackup:=False wb.Close SaveChanges:=False Filename = Dir() Loop Application.DisplayAlerts = initialDisplayAlerts End Sub </code></pre> <p>I am now trying to generalize this to all subfolders inside the given folder.</p> <p>On a larger note,I am trying to build a macro which does the following:</p> <ol> <li>Run this in batch mode where the parent folder is constant.</li> <li>Process the code at background and put all the converted files in respective folders.</li> </ol> <p>For example, Max is my main folder inside which there may be Med ,Det,Vis,Liv sub-folders.Inside each subfolder,there will be thousands of xlsx files which need to be converted and placed at the same location where the parent file is stored.</p> <p>Please help.</p> <p>Thanks, Maddy</p>
howto
2016-01-28T12:22:04Z
35,078,261
Sort a list of dictionary provided an order
<p>I've a list</p> <pre><code>order = [8,7,5,9,10,11] </code></pre> <p>and a list of dictionaries</p> <pre><code>list_of_dct = [{'value':11}, {'value':8}, {'value':5}, {'value':7}, {'value':10}, {'value':9}] </code></pre> <p>I want to sort this list_of_dct by the order given in <code>order</code> list, ie the output should be the following.</p> <pre><code>list_of_dct = [{'value':8}, {'value':7}, {'value':5}, {'value':9}, {'value':10}, {'value':11}] </code></pre> <p>I know how to sort by a given <code>key</code>, but not when an order is already given. How can I sort it?</p> <p>PS: I already have an O(n^2) solution. Looking for a better solution.</p>
howto
2016-01-29T06:31:59Z
35,083,540
Using a loop to make a dictionary
<p>I'm trying to make a binary2acii and vise versa <code>Dictonary</code> via Python shell. I'm a bit stuck: </p> <ol> <li>I make a new <code>Dictonary</code></li> <li>I need to declare, that it goes from 0-127</li> <li>Make a loop to go through all options</li> </ol> <p>I'm new to this.</p> <pre><code>binary2ascii = {}, format (127,"08b") for i in range(0,127): chr(i) </code></pre>
howto
2016-01-29T11:35:33Z
35,097,130
Django order by highest number of likes
<p>I'm trying to create a page where people can see the highest rated article, there is one problem which is when I filter the number of likes on an article that is also liked by another person it creates a copie of the liked article.</p> <p>here is an image to be more precise.</p> <p><a href="http://i.stack.imgur.com/Z3FNd.png" rel="nofollow"><img src="http://i.stack.imgur.com/Z3FNd.png" alt="enter image description here"></a></p> <p>What I want is to <strong>order</strong> the articles of the blog <strong>by</strong> likes. </p> <p>here is the code : </p> <p><strong>models.py</strong></p> <pre><code>class Article(models.Model): user = models.ForeignKey(User, default='1') [... unrelated fields ...] likes = models.ManyToManyField(User, related_name="likes") [... unrelated function ...] </code></pre> <p><strong>views.py</strong></p> <pre><code>def article_ordered_by_likes(request): context = {'article': Article.objects.order_by('-likes')} return render(request, 'article_ordered_by_likes.html', context) </code></pre> <p><strong>article_ordered_by_likes.html</strong></p> <pre><code>{% for a in article %} [... unrelated html ...] &lt;h2&gt;{{ a.titre }}&lt;/h2&gt; &lt;span id="count{{ a.id }}"&gt;{{ a.total_likes }}&lt;/span&gt; &lt;input type="button" class="like" id="{{ a.id }}" value="Like" /&gt; {% endfor %} </code></pre> <hr> <p>________ <em>Like Button</em> ________</p> <p><strong>views.py</strong></p> <pre><code>def like_button(request): if request.method == 'POST': user = request.user id = request.POST.get('pk', None) article = get_object_or_404(Article, pk=id) if article.likes.filter(id=user.id).exists(): article.likes.remove(user) else: article.likes.add(user) context = {'likes_count': article.total_likes} return HttpResponse(json.dumps(context), content_type='application/json') </code></pre> <p>Why Django is creating multiple same posts? How can I order the articles by likes without having this problem ?</p>
howto
2016-01-30T01:59:22Z
35,104,102
eliminate malformed records from a large .csv file
<p>I have a large <code>.csv</code> file and I want to processes it with, perhaps a python script, and find all the values that are "malformed", e.g. those that have more or less values than the number of headers, and eliminate them. </p> <p>What's the best way to do this? </p>
howto
2016-01-30T16:25:21Z
35,108,136
Get object attribute in class based view
<p>I wonder if it is possible to get the attribute of an object in Django Class Based Views.</p> <p>What I try to do is the following:</p> <p>I have an <code>UpdateView</code>:</p> <pre><code>class FooUpdate(UpdateView): model = Foo page_title = &lt;foo-object's name should go here&gt; </code></pre> <p><code>page_title</code> is processed by the template with</p> <pre><code>... &lt;title&gt; {{ view.page_title }} &lt;/title&gt; ... </code></pre> <p>(this technique is described <a href="http://reinout.vanrees.org/weblog/2014/05/19/context.html" rel="nofollow">here</a>)</p> <p><code>urls.py</code> looks like this:</p> <pre><code>... url(r'^edit/(?P&lt;pk&gt;[0-9]+)/$', views.FooUpdate.as_view(), name="edit") ... </code></pre> <p>How can I set <code>page_title</code> in the view?</p> <p>I am aware that there are plenty other ways to achieve this, but setting a variable in the view was really convenient (up to now) ...</p>
howto
2016-01-30T22:45:04Z
35,115,138
How do I check if a network is contained in another network in Python?
<p>How can I check if a network is wholly contained in another network in Python, e.g. if <code>10.11.12.0/24</code> is in <code>10.11.0.0/16</code>? </p> <p>I've tried using <code>ipaddress</code> but it doesn't work:</p> <pre><code>&gt;&gt;&gt; import ipaddress &gt;&gt;&gt; ipaddress.ip_network('10.11.12.0/24') in ipaddress.ip_network('10.11.0.0/16') False </code></pre>
howto
2016-01-31T14:48:56Z
35,118,265
Dot notation string manipulation
<p>Is there a way to manipulate a string in Python using the following ways?</p> <p>For any string that is stored in dot notation, for example:</p> <pre><code>s = "classes.students.grades" </code></pre> <p>Is there a way to change the string to the following:</p> <pre><code>"classes.students" </code></pre> <p>Basically, remove everything up to and including the last period. So <code>"restaurants.spanish.food.salty"</code> would become <code>"restaurants.spanish.food"</code>.</p> <p>Additionally, is there any way to identify what comes after the last period? The reason I want to do this is I want to use <code>isDigit()</code>. </p> <p>So, if it was <code>classes.students.grades.0</code> could I grab the <code>0</code> somehow, so I could use an if statement with <code>isdigit</code>, and say if the part of the string after the last period (so <code>0</code> in this case) is a digit, remove it, otherwise, leave it.</p>
howto
2016-01-31T19:20:50Z
35,119,291
find an empty value gap in a list and allocate a group of strings
<p>I am new in Python and I am looking for an elegant way to do this:</p> <pre><code>list0 = ["text1","text2","","","text3","","text4","text5","","text6"] </code></pre> <p>I want to group together the non-empty strings that are detected after the gap in indices 2 and 3, and allocate this group starting at a specific index (e.g. index 5). The new list should look like <em>list1</em>. (To see <em>list1</em>) <a href="http://i.stack.imgur.com/SPXz3.png" rel="nofollow">click here:</a> </p>
howto
2016-01-31T20:49:13Z
35,153,942
How to run Django management commands against Google Cloud SQL
<p>Currently , I have deployed my django project on google app engine. I need to run <code>python manage.py migrate</code> command so that <code>auth_user</code> table should be created on my google cloud instance . But don't know where to run this command. </p>
howto
2016-02-02T12:46:56Z
35,159,791
Two windows: First Login after that main program
<p>i have this program </p> <pre><code>class loginWindow(): def __init__(self, master): self.master = master self.frame = Frame(master) master.title(u"Geometry Calc - Login") Button(master, text="Login", command=self.login).pack() def login(self): self.newWindow = Toplevel(self.master) main(self.newWindow) self.master.withdraw() class main(): def __init__(self, master): # Nastavení nového okna master.title(u"Geometry Calc") # Nadpis master.geometry("695x935") # Rozmery v px master.config(background="white") master.resizable(width=FALSE, height=FALSE) # Zakážeme změnu rozměrů uživatelem - zatím.. menubar = Menu(master) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label="Konec", command=master.quit) menubar.add_cascade(label="Soubor", menu=helpmenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label="O programu", command=self.createAbout) menubar.add_cascade(label="Pomoc", menu=helpmenu) master.config(menu=menubar) canvas = Canvas(master, width=691, height=900) canvas.pack(expand=1, fill=BOTH) self.showImage(canvas, 347, 454, "geometry_table.jpg") root = Tk() app = loginWindow(root) root.mainloop() ` </code></pre> <p>and i have this problem. When i run my program, i can see <strong>login window</strong>, when i hit login button I get window <strong>main</strong>, but window <strong>login</strong> is only withdrawed. So when i close window <strong>main</strong> my program still run. And i need make this. First run program <strong>main</strong>, but will be invisible or something. And i see only login window (maybe Toplevel). When i hit button login the window <strong>loginWindow</strong> will get destroy() and the window <strong>main</strong> will be visible</p>
howto
2016-02-02T17:18:58Z
35,164,333
Efficient way of creating a permutated 2D array with a range of integers
<p>I'm trying to find an efficient way to generate a set of x-y coordinates that identifies every position in a square lattice, such that, if the lattice is made up of <code>NxN</code> grids, where</p> <pre><code>N = 100; x = range(N) </code></pre> <p>I want to compute a set of arrays such as <code>array([[0,0], [0,1], [0,2] ..[0,100], [1,0], [1,1], [1,2], ..[1,100], ...[100,0], [100,1], [100,2], ..[100,100]])</code>. The ordering does not matter. So far I've tried using <code>itertools.product(x, repeat=2)</code>, however, the output itertools object is not easy to convert to the above 2D array. Any suggestion would really helpful.</p>
howto
2016-02-02T21:42:46Z