title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
cannot calculate MACD via python pandas
38,270,524
<p>I have made a script to get stock-info for a list of stocks. For the stocks involved (groups in groupby), I need to calculate MACD.</p> <p>So as to not mix the price for one stock with the other I use a pandas groupby.</p> <pre><code># -*- coding: utf-8 -*- import pandas as pd from pandas.io.data import DataReade...
0
2016-07-08T15:35:39Z
38,272,687
<p>So it looks to me like you did more work than you really needed to here. The answer is a little simpler. You don't need to define your own moving average function, and this is in fact what is causing your problem. </p> <p>Change <code>moving_average</code> to:</p> <pre><code>def moving_average(group, n=9): sm...
1
2016-07-08T17:49:22Z
[ "python", "pandas" ]
Consolidating a ton of mostly blank columns into one column (Postgres and Python)
38,270,546
<p>I have a raw data table with over 500 columns that I am importing to a different database. Most of these columns are null (for example: <code>session1</code>, <code>session2</code>, <code>session3</code> ~ <code>session120</code>). I didn't design this table, but there are 3 column types with over 100 columns each. ...
0
2016-07-08T15:36:58Z
38,271,588
<p>I depends on what you want to do with these columns, but options include</p> <ul> <li>arrays</li> <li>non-relational storage: hstore, json, xml</li> <li>turning the columns into rows in another table</li> </ul>
1
2016-07-08T16:33:39Z
[ "python", "postgresql" ]
Load data from Essbase into SQL database
38,270,552
<p>I'm currently using a mix of smart view and power query(sql) to load data into Excel models however my excel always crashes when smart view is used. I'm required to work in Excel but I'm know looking at finding a way to periodically load data from Essbase into my SQL server database and only use power query(sql) for...
0
2016-07-08T15:37:23Z
38,299,572
<p>There are a couple of ways to go. The most straightforward is to export all of the data from your Essbase database using column export, then designing a process to load the data into SQL Server (such as using the import functionality or <code>BULK IMPORT</code>, or SSIS...). </p> <p>Another approach is to use the <...
0
2016-07-11T05:15:20Z
[ "python", "sql-server", "excel", "hyperion", "essbase" ]
Python 3.4.3 asyncio keywords SyntaxError
38,270,559
<p>Terminal output is worth a thousand words, I guess</p> <pre><code>[~] $ python Python 3.4.3 (default, Jun 22 2016, 16:03:29) [GCC 4.9.3] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import asyncio &gt;&gt;&gt; async def fun(): File "&lt;stdin&gt;", line 1 async ...
1
2016-07-08T15:37:56Z
38,270,630
<p>The <code>async</code> keyword was added in Python 3.5.</p>
1
2016-07-08T15:41:03Z
[ "python", "python-asyncio" ]
Python 3.4.3 asyncio keywords SyntaxError
38,270,559
<p>Terminal output is worth a thousand words, I guess</p> <pre><code>[~] $ python Python 3.4.3 (default, Jun 22 2016, 16:03:29) [GCC 4.9.3] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import asyncio &gt;&gt;&gt; async def fun(): File "&lt;stdin&gt;", line 1 async ...
1
2016-07-08T15:37:56Z
38,270,674
<p>The <code>async</code> and <code>await</code> syntax was introduced in Python 3.5. (<a href="https://docs.python.org/3/reference/compound_stmts.html#coroutines" rel="nofollow">https://docs.python.org/3/reference/compound_stmts.html#coroutines</a>)</p> <p>In Python 3.4 you need to use the <code>@asyncio.coroutine</c...
4
2016-07-08T15:42:38Z
[ "python", "python-asyncio" ]
Creating a dynamic Form Django
38,270,598
<p>Consider these Django models: </p> <pre><code>class MonitorSession(models.Model): agent = models.ForeignKey(Agent, on_delete=models.CASCADE) date = models.DateTimeField() contact_motive = models.ForeignKey(ContactMotive) customer_number = models.CharField(max_length=65) protocole_number = models...
0
2016-07-08T15:39:43Z
38,272,952
<p>The above suggestion is giving me part of the solution: This would be the code of my Form:</p> <pre><code>class MonitorSessionForm(forms.Form): agent = forms.ModelChoiceField(queryset=Agent.objects.all()) date = forms.DateField() contact_motive =forms.ModelChoiceField(queryset=ContactMotive.objects.all(...
0
2016-07-08T18:08:26Z
[ "python", "django", "forms" ]
Using Pyserial to read and write data
38,270,679
<p>I am trying to understand how Pyserial is interfacing with my windows machine. I am using this basic code from the pyserial website.</p> <pre><code>import serial ser = serial.Serial('COM1') # open serial port print(ser.name) # check which port was really useds ser.write(b'hello') # write a string ser.c...
-1
2016-07-08T15:42:43Z
38,270,746
<p>You should open the connection first with <code>ser.open()</code>. You can write the command like you are doing, but to read it, you need to use <code>ser.readlines()</code>. Then you can close the connection. <a href="http://pyserial.readthedocs.io/en/latest/pyserial_api.html" rel="nofollow">This</a> page has a lot...
0
2016-07-08T15:47:09Z
[ "python", "pyserial" ]
Extract lines from (oddly deliminated) txt file and write to new file with Python
38,270,716
<p>I have .txt files (one per image) that is formatted as can be seen below. However, the deliminator used in the file is very strange. I cannot figure out how to extract the information I am interested in.</p> <pre><code>ExifTool Version Number : 10.20 File Name : R0010023.tiff Directory...
0
2016-07-08T15:45:17Z
38,270,970
<p>When you're calling <code>readline(1)</code> you're recieving 1 character of the first line. When you're calling <code>readline(2)</code> you're recieving the <strong>next</strong> 2 characters of the first line and so on. When you hit a new line it will continue on the second line.</p> <p>Call <code>readline()</co...
2
2016-07-08T15:59:00Z
[ "python", "gps" ]
Extract lines from (oddly deliminated) txt file and write to new file with Python
38,270,716
<p>I have .txt files (one per image) that is formatted as can be seen below. However, the deliminator used in the file is very strange. I cannot figure out how to extract the information I am interested in.</p> <pre><code>ExifTool Version Number : 10.20 File Name : R0010023.tiff Directory...
0
2016-07-08T15:45:17Z
38,271,047
<p>As Scott Hunter pointed out (obliquely), you're not reading the file line by line. If you checked out the docs for readline, you'd see that calling it with no argument reads a whole line, while calling it with a numeric argument reads that many <em>bytes</em>, not <em>lines</em>. </p> <p>So <code>sfile.readline(1)...
0
2016-07-08T16:03:12Z
[ "python", "gps" ]
Extract lines from (oddly deliminated) txt file and write to new file with Python
38,270,716
<p>I have .txt files (one per image) that is formatted as can be seen below. However, the deliminator used in the file is very strange. I cannot figure out how to extract the information I am interested in.</p> <pre><code>ExifTool Version Number : 10.20 File Name : R0010023.tiff Directory...
0
2016-07-08T15:45:17Z
38,271,096
<p>It is delimited by new lines.</p> <p>Try <code>sfile.readlines()</code></p> <p>Then to get the File Name, you should turn that into a dictionary. So loop through each item of the list you made:</p> <pre><code>dict={} for i in list: dict[i.split(':')[0]] = ''.join(i.split(':')[1:])} </code></pre> <p>or if yo...
0
2016-07-08T16:05:43Z
[ "python", "gps" ]
Extract lines from (oddly deliminated) txt file and write to new file with Python
38,270,716
<p>I have .txt files (one per image) that is formatted as can be seen below. However, the deliminator used in the file is very strange. I cannot figure out how to extract the information I am interested in.</p> <pre><code>ExifTool Version Number : 10.20 File Name : R0010023.tiff Directory...
0
2016-07-08T15:45:17Z
38,271,098
<p>Try the following, Open your file</p> <pre><code> File = opem("R001.txt", "r") </code></pre> <p>and then read in the data into a list,</p> <pre><code> lstGPSData = File.readlines() </code></pre> <p>and then use the split function to get into different lines and then you can use the index if you'd like to a...
0
2016-07-08T16:05:52Z
[ "python", "gps" ]
How do I use a python 3 turtle twice
38,270,838
<p>I am wondering how to use a turtle twice i use the desired turtle as normal, which works and when I use the same turtle again (after resetting the turtle) every thing goes wrong. What am I doing wrong? </p> <pre><code>import turtle import time title = turtle.Turtle() title.hideturtle() title.left(180) title.forward...
1
2016-07-08T15:52:11Z
38,271,370
<p>It seems that everything goes wrong because of line 13</p> <pre><code>turtle.bye() </code></pre> <p>This shuts the turtlegraphics window and then when you want to show again the turtle in line 34 with </p> <pre><code>title.showturtle() </code></pre> <p>this raises an error cause you can't show the turtle when g...
2
2016-07-08T16:20:27Z
[ "python", "python-3.x", "turtle-graphics" ]
How to get only the numbers(without whitespaces) from a text file in python
38,270,853
<p>Hello i have this text file:</p> <pre><code>1 2 3 4 5 6 1 1 1 1 1 1 -1 1 -1 -1 -1 1 2 3 5 6 1 6 10 0 0.5 1 0 0 0 30 5 3 0 0 0 0 0 0 0 5 80 90 6 5,4 8 5 65 58 2 9,7 1 1 83 60 4 7,2 4 7 40 80 10 7,5 7 10 52 72 6 2 3 8 94 96 7 3,6 5 6 </code></pre> <p>I want to append the 7 first lines in 7 different lists( with a fo...
-2
2016-07-08T15:52:41Z
38,270,919
<p><code>shlex</code> is your friend there <a href="https://docs.python.org/2/library/shlex.html" rel="nofollow">https://docs.python.org/2/library/shlex.html</a></p> <pre><code>with open("c.txt") as file: lines = [] for line in file: # The rstrip method gets rid of the "\n" at the end of each line lines.append(shlex...
0
2016-07-08T15:56:49Z
[ "python", "list", "append", "text-files" ]
How to get only the numbers(without whitespaces) from a text file in python
38,270,853
<p>Hello i have this text file:</p> <pre><code>1 2 3 4 5 6 1 1 1 1 1 1 -1 1 -1 -1 -1 1 2 3 5 6 1 6 10 0 0.5 1 0 0 0 30 5 3 0 0 0 0 0 0 0 5 80 90 6 5,4 8 5 65 58 2 9,7 1 1 83 60 4 7,2 4 7 40 80 10 7,5 7 10 52 72 6 2 3 8 94 96 7 3,6 5 6 </code></pre> <p>I want to append the 7 first lines in 7 different lists( with a fo...
-2
2016-07-08T15:52:41Z
38,271,063
<p>If you really want your lists to look like this:</p> <pre><code>a = [1, 2, 3, 4, 5, 6] </code></pre> <p>Then the items have to be numbers (integer or float).</p> <p>However, your input file has some items that look like this:</p> <p><code>5,4</code></p> <p>And that is neither an integer nor a float.</p> <p>So,...
0
2016-07-08T16:03:59Z
[ "python", "list", "append", "text-files" ]
How to get only the numbers(without whitespaces) from a text file in python
38,270,853
<p>Hello i have this text file:</p> <pre><code>1 2 3 4 5 6 1 1 1 1 1 1 -1 1 -1 -1 -1 1 2 3 5 6 1 6 10 0 0.5 1 0 0 0 30 5 3 0 0 0 0 0 0 0 5 80 90 6 5,4 8 5 65 58 2 9,7 1 1 83 60 4 7,2 4 7 40 80 10 7,5 7 10 52 72 6 2 3 8 94 96 7 3,6 5 6 </code></pre> <p>I want to append the 7 first lines in 7 different lists( with a fo...
-2
2016-07-08T15:52:41Z
38,271,454
<pre><code>final_list = [] with open("c.txt") as f: count = 0 for line in f: line_list = [float(n) for n in line.rstrip().replace(',', '.').split(" ")] if count &lt; 7: final_list.append(line_list) else: if count == 7: final_list.append([]) ...
0
2016-07-08T16:25:32Z
[ "python", "list", "append", "text-files" ]
How do you pickle figure objects in matplotlib?
38,270,861
<p>I am getting the following error: </p> <blockquote> <p>ImportError: No module named gdbm </p> </blockquote> <p>I'm using this to pickle: </p> <pre><code>pickle.dump(fig1, file('test_1.pickle','wb')) </code></pre> <p>where fig1 is just a figure object in matplotlib:</p> <pre><code>fig1 = plt.figure() </code></...
0
2016-07-08T15:53:00Z
38,271,304
<p>I don't think the error message you get has anything to do with the code you are showing. Python can't find the module <code>gdbm</code>. Maybe you want to use <code>dbm</code> instead of <code>gdbm</code>?</p>
0
2016-07-08T16:17:00Z
[ "python", "numpy", "matplotlib", "pickle" ]
Should I trust "python -3" as returning an exhaustive result?
38,270,882
<p>As you can read in "man python" :</p> <blockquote> <p>-3 Warn about Python 3.x incompatibilities that 2to3 cannot trivially fix.</p> </blockquote> <p>This command allready help me in the past to avoid incompatibility between code for Python 2.x &amp; 3.x. </p> <p>However, i don't have any warning for <a hre...
0
2016-07-08T15:54:29Z
38,270,975
<p>No, you should not treat that warning as exhaustive. The following code behaves differently on python2.x and python3.x but emits no warnings:</p> <pre><code>from __future__ import print_function class test(object): def __nonzero__(self): return False t = test() if t: print('Hello') </code></pre> ...
1
2016-07-08T15:59:14Z
[ "python", "compatibility" ]
Finding an unkown string within a string
38,270,905
<p>This question is going to be similar, but looking for something completely different than one I asked a few days ago. </p> <p>I have a string that is known, but is a portion of code, and it varies, I currently find it by using:</p> <pre><code>for num, line in enumerate(code, 1): if re.match("function (.*) {", ...
0
2016-07-08T15:55:57Z
38,270,947
<p>You mean the text between <code>(</code> and <code>)</code>?</p> <p>Use capturing groups:</p> <pre><code>m = re.match("function (.*) {", line): if m: print m.group(1) </code></pre>
2
2016-07-08T15:57:57Z
[ "python" ]
Finding an unkown string within a string
38,270,905
<p>This question is going to be similar, but looking for something completely different than one I asked a few days ago. </p> <p>I have a string that is known, but is a portion of code, and it varies, I currently find it by using:</p> <pre><code>for num, line in enumerate(code, 1): if re.match("function (.*) {", ...
0
2016-07-08T15:55:57Z
38,271,409
<p>The match object object which is returned contains all contents of groups. I would use re.search if 'function' isn't always at the beginning of a line and '.+' to match functions with at least one character.</p> <pre><code>line_to_fn = {} for num, line in enumerate(code, 1): match = re.search("function (.+) {...
0
2016-07-08T16:22:35Z
[ "python" ]
pyspark crashed at dataframe.collect() with error message "Py4JNetworkError: An error occurred while trying to connect to the Java server"
38,271,017
<p>I have a function my_function which has a for loop iteration. There is a part in the for loop which requires to call a dataframe collect(). It works for the first few loops, but it always crashed at the fifth iteration. Do you guys have any idea why this happens?</p> <pre><code> File "my_code.py", line 189, in my_...
0
2016-07-08T16:01:30Z
38,295,523
<p>Perhaps the JVM is overflowing. Try adding memory to Driver, or running <code>df.take(10)</code> instead of <code>df.collect()</code> to test if the problem is the amount of data that you are returning.</p>
1
2016-07-10T19:05:24Z
[ "python", "pyspark", "spark-dataframe" ]
Workaround for preserveNullAndEmptyArrays in MongoDB 2.6
38,271,137
<p>I am using a Python script to query a MongoDB collection. The collection contains embedded documents with varying structures.</p> <p>I am trying to simply "$unwind" an array contained in several documents. However, the array is not in ALL documents.</p> <p>That means only the documents that contain the field are r...
1
2016-07-08T16:08:15Z
38,272,790
<p>We can still preserve all the documents where the array field is missing by playing with the <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/ifNull/" rel="nofollow"><code>$ifNull</code></a> operator and use a logical <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/cond...
1
2016-07-08T17:55:56Z
[ "python", "mongodb", "aggregation-framework" ]
python command-line error ('python' is not defined)
38,271,218
<p>I am very new to programming with python. (I am using Windows 10)</p> <p>So I recently installed Python 3.5.2 and I am trying to write a simple command in the python command line (name of program: Python 3.5): </p> <pre><code>python -h </code></pre> <p>What I get:</p> <p>Traceback (most recent call last):</p> <...
-1
2016-07-08T16:12:36Z
38,271,642
<p>You can type in your program and then the command, for example <code>$ ./example.py [-h]</code>. You can also use <code>-?</code> or <code>--help</code> instead of <code>-h</code></p> <p>EDIT: In command line,</p> <pre><code> $./programName.py [-h] -z </code></pre> <p>It should show you an error saying that <c...
0
2016-07-08T16:37:13Z
[ "python" ]
pandas how to truncate minutes, seconds pandas.tslib.Timestamp
38,271,224
<p>I work with Cloudera VM 5.2 and pandas 0.18.0.</p> <p>I have the following data</p> <pre><code>adclicksDF = pd.read_csv('/home/cloudera/Eglence/ad-clicks.csv', parse_dates=['timestamp'], skipinitialspace=True).assign(adCount=1) adclicksDF.head(n=5) Out[107]: timestamp txId use...
1
2016-07-08T16:13:10Z
38,271,317
<p>You can use:</p> <pre><code>adclicksDF["timestamp"] = pd.to_datetime(adclicksDF["timestamp"]) .apply(lambda x: x.replace(minute=0, second=0)) print (adclicksDF) timestamp txId userSessionId teamId userId adId adCategory 0 2016-05-26 15:00:00 5974 5809 ...
2
2016-07-08T16:18:20Z
[ "python", "pandas", "timestamp", "truncate", "seconds" ]
pandas how to truncate minutes, seconds pandas.tslib.Timestamp
38,271,224
<p>I work with Cloudera VM 5.2 and pandas 0.18.0.</p> <p>I have the following data</p> <pre><code>adclicksDF = pd.read_csv('/home/cloudera/Eglence/ad-clicks.csv', parse_dates=['timestamp'], skipinitialspace=True).assign(adCount=1) adclicksDF.head(n=5) Out[107]: timestamp txId use...
1
2016-07-08T16:13:10Z
38,271,325
<p>Try:</p> <pre><code>pd.to_datetime(adclicksDF.timestamp).dt.strftime('%Y-%m-%d %H') </code></pre> <p>After assignment:</p> <pre><code>adclicksDF.timestamp = pd.to_datetime(adclicksDF.timestamp).dt.strftime('%Y-%m-%d %H') adclicksDF </code></pre> <p><a href="http://i.stack.imgur.com/ySdKM.png" rel="nofollow"><im...
1
2016-07-08T16:18:35Z
[ "python", "pandas", "timestamp", "truncate", "seconds" ]
Getting time information from string with pandas and datatime in Python
38,271,232
<p>I am doing test excersises for summer school and this is my first experience with python. It is said, that i can get my time information with folowing code:</p> <pre><code>import pandas as pd from datetime import datetime def print_time_range(times): print('Time from: {0}, to: {1}'.format(datetime.fromtimestam...
4
2016-07-08T16:13:25Z
38,271,253
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.time.html" rel="nofollow"><code>dt.time</code></a>:</p> <pre><code>print_time_range(train_likes_df.time.dt.time) </code></pre> <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_dateti...
1
2016-07-08T16:14:24Z
[ "python", "visual-studio", "pandas", "methods", "windows-10" ]
Getting time information from string with pandas and datatime in Python
38,271,232
<p>I am doing test excersises for summer school and this is my first experience with python. It is said, that i can get my time information with folowing code:</p> <pre><code>import pandas as pd from datetime import datetime def print_time_range(times): print('Time from: {0}, to: {1}'.format(datetime.fromtimestam...
4
2016-07-08T16:13:25Z
38,273,611
<p>In the first hand your error is relative to the <strong>datetime module</strong> and in the other hand according to github (today) , <a href="https://github.com/pydata/pandas/tree/v0.18.1/pandas" rel="nofollow">pandas <em>branch 0.18.1</em></a> is marked with "<strong>BUG: More followups on to_datetime exceptions</s...
1
2016-07-08T18:55:47Z
[ "python", "visual-studio", "pandas", "methods", "windows-10" ]
tox can't detect python interpreter in D:\python27 path
38,271,311
<p>My tox.ini file looks like this</p> <pre><code>[tox] envlist=py27 [testenv] deps= pytest </code></pre> <p>This fails to find my base python installation which is at D:\python27 and not the standard c:\python27 location</p> <p>If I change tox.ini to this, it works but looks ugly.</p> <pre><code>[tox] envlis...
1
2016-07-08T16:17:28Z
38,319,437
<p>I figured this out. looks like I need to specify python2.7 instead of py27 for windows </p> <pre><code>[tox] envlist=python2.7 </code></pre> <p>This correctly detects the location of python irrespective of C or D drive.</p>
0
2016-07-12T03:12:14Z
[ "python", "python-2.7", "tox" ]
List of all element names in HTML document — beautifulsoup
38,271,393
<p>I want to get a list containing <strong>all different tag names</strong> of a HTML document (a list of string of tag names without repetition). I tried putting empty entry with <code>soup.findall()</code>, but this gave me the entire document instead.</p> <p>Is there a way of doing it?</p>
2
2016-07-08T16:21:22Z
38,272,067
<p>Using <code>soup.findall()</code> you get a list of every single element you can iterate over. Therefore you can do the following:</p> <pre><code>from bs4 import BeautifulSoup html_doc = """ &lt;html&gt;&lt;head&gt;&lt;title&gt;The Dormouse's story&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;p class="title"&gt;&lt...
5
2016-07-08T17:04:33Z
[ "python", "web-scraping", "beautifulsoup" ]
Python Exception Handling with in a loop
38,271,394
<p>An exception occurs when my program can't find the element its looking for, I want to log the event within the CSV, Display a message the error occurred and continue. I have successfully logged the event in the CSV and display the message, Then my program jumps out of the loop and stops. How can I instruct python to...
1
2016-07-08T16:21:31Z
38,271,447
<p>Just put the <code>try/except</code> block inside the loop. And there is no need in that <code>pass</code> statement in the end of the <code>except</code> part. </p> <pre><code>with open('list4.csv','wb') as f: writer = csv.writer(f) for s in sites: try: adrs = "http://turnpikeshoes.com/...
4
2016-07-08T16:24:54Z
[ "python", "csv", "error-handling", "exception-handling" ]
Is there a way to modify datetime objects through the Django ORM Query?
38,271,457
<p>We've a Django, Postgresql database that contains objects with: </p> <pre><code>object_date = models.DateTimeField() </code></pre> <p>as a field.</p> <p>We need to count the objects by hour per day, so we need to remove some of the extra time data, for example: minutes, seconds and microseconds.</p> <p>We can re...
2
2016-07-08T16:25:47Z
38,272,656
<pre><code>count = len(MyModel.objects.filter(object_date__range=(beginning_of_hour, end_of_hour))) </code></pre> <p>or </p> <pre><code>count = MyModel.objects.filter(object_date__range=(beginning_of_hour, end_of_hour)).count() </code></pre> <p>Assuming I understand what you're asking for, this returns the number of...
2
2016-07-08T17:47:23Z
[ "python", "django", "python-3.x", "django-models", "django-queryset" ]
Is there a way to modify datetime objects through the Django ORM Query?
38,271,457
<p>We've a Django, Postgresql database that contains objects with: </p> <pre><code>object_date = models.DateTimeField() </code></pre> <p>as a field.</p> <p>We need to count the objects by hour per day, so we need to remove some of the extra time data, for example: minutes, seconds and microseconds.</p> <p>We can re...
2
2016-07-08T16:25:47Z
38,273,423
<p>If you simply want to obtain the dates without the time data, you can use <code>extra</code> to declare calculated fields:</p> <pre><code>query = MyModel.objects .extra(select={ 'object_date_group': 'CAST(object_date AS DATE)', 'object_hour_group': 'EXTRACT(HOUR FROM object_date)' }) .va...
1
2016-07-08T18:41:13Z
[ "python", "django", "python-3.x", "django-models", "django-queryset" ]
how to split text into individual list items
38,271,467
<p>I have a couple sentences of text in the format below:</p> <pre class="lang-none prettyprint-override"><code>Title: Presenting in a new Forum, Jun-01-2016 # Sentence 1 Source: xyz Website # Sentence 2 Type: Special Presentations # Sentence 3 From: 14/May/2016 ...
0
2016-07-08T16:26:15Z
38,271,510
<p>If that is from a text file than you can just call .readlines() which returns an array of the lines. If it is a string then split on '\n'.</p>
0
2016-07-08T16:28:18Z
[ "python" ]
how to split text into individual list items
38,271,467
<p>I have a couple sentences of text in the format below:</p> <pre class="lang-none prettyprint-override"><code>Title: Presenting in a new Forum, Jun-01-2016 # Sentence 1 Source: xyz Website # Sentence 2 Type: Special Presentations # Sentence 3 From: 14/May/2016 ...
0
2016-07-08T16:26:15Z
38,271,543
<p>Assuming the first word of each sentence ends with ':' and the first line of the paragraph doesn't end in ':', the following code should work:</p> <pre><code>string = """\ Title: Presenting in a new Forum, Jun-01-2016 Source: xyz Website Type: Special Presentations ...
0
2016-07-08T16:30:03Z
[ "python" ]
how to split text into individual list items
38,271,467
<p>I have a couple sentences of text in the format below:</p> <pre class="lang-none prettyprint-override"><code>Title: Presenting in a new Forum, Jun-01-2016 # Sentence 1 Source: xyz Website # Sentence 2 Type: Special Presentations # Sentence 3 From: 14/May/2016 ...
0
2016-07-08T16:26:15Z
38,271,693
<p>If you are always going to have title, source, type and from (which are 1 line each) and then a paragraph of arbitrary number of lines:</p> <pre><code>splitted_file = string.splitlines() title = splitted_file[1] source = splitted_file[2] type = splitted_file[3] _from = splitted_file[4] # can't use 'from' as a var...
2
2016-07-08T16:40:00Z
[ "python" ]
how to split text into individual list items
38,271,467
<p>I have a couple sentences of text in the format below:</p> <pre class="lang-none prettyprint-override"><code>Title: Presenting in a new Forum, Jun-01-2016 # Sentence 1 Source: xyz Website # Sentence 2 Type: Special Presentations # Sentence 3 From: 14/May/2016 ...
0
2016-07-08T16:26:15Z
38,271,760
<p>If that's a string you'll want to use:</p> <pre><code>el2.splitlines() </code></pre> <p>Which will split the string on each new line, and if you need the linebreaks (\n) added to the string you can use:</p> <pre><code>el2.splitlines(5) </code></pre> <p>If el2 is a file you'll want to do it this way:</p> <pre><c...
0
2016-07-08T16:44:13Z
[ "python" ]
When should we call multiprocessing.Pool.join?
38,271,547
<p>I am using 'multiprocess.Pool.imap_unordered' as following </p> <pre><code>from multiprocessing import Pool pool = Pool() for mapped_result in pool.imap_unordered(mapping_func, args_iter): do some additional processing on mapped_result </code></pre> <p>Do I need to call <code>pool.close</code> or <code>pool.j...
1
2016-07-08T16:30:13Z
38,271,957
<p>No, you don't, but it's probably a good idea if you aren't going to use the pool anymore.</p> <p>Reasons for calling <code>pool.close</code> or <code>pool.join</code> are well said by Tim Peters in <a href="http://stackoverflow.com/questions/20387510/proper-way-to-use-multiprocessor-pool-in-a-nested-loop">this SO p...
1
2016-07-08T16:55:53Z
[ "python", "python-multiprocessing" ]
Gather unique values from 2 lists
38,271,565
<p>I currently have 2 "set" lists, both contain mostly the same values i.e:</p> <pre><code>a = [1,2,3,4,5,6] b = [1,2,3,4,5,6,7,8] </code></pre> <p>What I'm trying to do is compare the two and only return 7 &amp; 8 into another list however I'm having no luck, I've tried a few methods I've found on here such as:</p...
0
2016-07-08T16:31:39Z
38,271,584
<p>You can use sets:</p> <pre><code>set(b) - set(a) Out[65]: {7, 8} </code></pre> <p>Or more explicitly:</p> <pre><code>set(b).difference(a) Out[67]: {7, 8} </code></pre> <p>For symmetric difference, you can use <code>^</code>. It will return elements that are in a or b, but not in both. Assume <code>a</code> has a...
2
2016-07-08T16:33:23Z
[ "python", "python-2.7" ]
Gather unique values from 2 lists
38,271,565
<p>I currently have 2 "set" lists, both contain mostly the same values i.e:</p> <pre><code>a = [1,2,3,4,5,6] b = [1,2,3,4,5,6,7,8] </code></pre> <p>What I'm trying to do is compare the two and only return 7 &amp; 8 into another list however I'm having no luck, I've tried a few methods I've found on here such as:</p...
0
2016-07-08T16:31:39Z
38,271,690
<pre><code>list(set(a)-set(b))+list(set(b)-set(a)) </code></pre>
-1
2016-07-08T16:39:43Z
[ "python", "python-2.7" ]
Gather unique values from 2 lists
38,271,565
<p>I currently have 2 "set" lists, both contain mostly the same values i.e:</p> <pre><code>a = [1,2,3,4,5,6] b = [1,2,3,4,5,6,7,8] </code></pre> <p>What I'm trying to do is compare the two and only return 7 &amp; 8 into another list however I'm having no luck, I've tried a few methods I've found on here such as:</p...
0
2016-07-08T16:31:39Z
38,272,153
<p>Another approach is using a <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a> to count the number of occurrences of each element from both lists:</p> <pre><code>from collections import defaultdict from itertools import chain a = [1,2,3...
0
2016-07-08T17:11:52Z
[ "python", "python-2.7" ]
Multiple operations on Dataframe
38,271,612
<p>I am trying to group by one/two columns, Sum the value of forth column and find mean in fifth column. Every operation to be written in separate output. Feels a bit tricky to make even a start. </p> <p>Input: No header, has more than 100k rows </p> <pre><code>StartTime, EndTime,Day,SumCount,UniqueCount 00:00:00,01:...
1
2016-07-08T16:35:11Z
38,271,729
<p>Try:</p> <pre><code>df.groupby(['StartTime', 'EndTime']).agg({'SumCount': ['sum'], 'UniqueCount': {'median': lambda x: np.median(x).round(0)}}) </code></pre> <p><a href="http://i.stack.imgur.com/uSk9a.png" rel="nofollow"><img src="http://i.stack.imgur.com/uSk9a.png" alt="enter image de...
1
2016-07-08T16:41:58Z
[ "python", "pandas", "dataframe", "aggregate", "median" ]
Count occurence of key per column in many columns in csv
38,271,647
<p>Have a csv like this</p> <pre><code>col1,col2,col3 t,t,t f,f,f t,f,t </code></pre> <p>The the file is quite big (50 Mb) with many columns</p> <p>Need to count the amount of t per column</p> <p>Tried this:</p> <pre><code>import csv import collections col1 = collections.Counter() with open('file.csv') as input_f...
-2
2016-07-08T16:37:32Z
38,271,856
<p>This will count the number of Ts in the first column. I make the assumption that they will all be lowercase, but if this is not true you can easily make that change.</p> <pre><code>t_count = [] with open('file.csv') as f: for line in f: for col_num, col in enumerate(line.rstrip().split(',')): ...
0
2016-07-08T16:49:07Z
[ "python", "csv" ]
Count occurence of key per column in many columns in csv
38,271,647
<p>Have a csv like this</p> <pre><code>col1,col2,col3 t,t,t f,f,f t,f,t </code></pre> <p>The the file is quite big (50 Mb) with many columns</p> <p>Need to count the amount of t per column</p> <p>Tried this:</p> <pre><code>import csv import collections col1 = collections.Counter() with open('file.csv') as input_f...
-2
2016-07-08T16:37:32Z
38,271,924
<pre><code>import csv totals = {} with open('file.csv') as input_file: for row in csv.reader(input_file, delimiter=','): for column, cell in enumerate(row): if column not in totals: totals[column] = 0 if cell == 't': totals[column] += 1 for column in...
1
2016-07-08T16:53:10Z
[ "python", "csv" ]
Numpy Linespace Not Working
38,271,711
<p>So I interpolated from data files and got a function. Later, I used linspace to create x values which I would then plug in to the function. However, when I did so, the x-range expanded to 100. I don't understand why it is doing this. How should I fix this?<a href="http://i.stack.imgur.com/41kzK.png" rel="nofollow"><...
0
2016-07-08T16:41:14Z
38,271,752
<p>It's not the <code>linspace</code> that's the problem, but your <code>plot</code> function that is. If you use<br> <code>plt.plot(xnew, f(xnew))</code> you will get the graph you want.</p>
6
2016-07-08T16:43:39Z
[ "python", "numpy", "matplotlib", "plot" ]
replace values in a float with a string- python
38,271,750
<p>I wanted to replace dot in a float with a string</p> <p>for example if I have a float 15.444 I need print it something like below 15 eggs 444 chicken</p> <p>If take I take a real example,here is the code</p> <pre><code>enter code here name = "chris" height_cm = 175 height = (height_cm * 1/2.54) * 1/12 weight = ...
-6
2016-07-08T16:43:28Z
38,271,910
<p>I don't code python but you may want to do something along the line of this(java):</p> <pre><code>float input = 15.444f; int[] split = (input+"").split("."); System.out.println(split[0]+" eggs and "+split[1]+" chickens"); </code></pre> <p>But why would you ever need to do something like this. A float is a horrible...
-2
2016-07-08T16:52:04Z
[ "python" ]
Print a dictionary by rows
38,271,768
<p>I have a dictionary in this format:</p> <pre><code>d = {'type 1':[1,2,3],'type 2':['a','b','c']} </code></pre> <p>It's a symmetric dictionary, in the sense that for each key I'll always have the same number of elements.</p> <p>There is a way to loop as if it were rows:</p> <pre><code>for row in d.rows(): pri...
1
2016-07-08T16:44:36Z
38,271,810
<p>You can <code>zip</code> the <code>.values()</code>, but the order is not guaranteed unless you are using a <code>collections.OrderedDict</code> (or a <a href="https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html" rel="nofollow">fairly recent version of PyPy</a>):</p> <pre><code>for row ...
3
2016-07-08T16:46:37Z
[ "python", "dictionary" ]
Print a dictionary by rows
38,271,768
<p>I have a dictionary in this format:</p> <pre><code>d = {'type 1':[1,2,3],'type 2':['a','b','c']} </code></pre> <p>It's a symmetric dictionary, in the sense that for each key I'll always have the same number of elements.</p> <p>There is a way to loop as if it were rows:</p> <pre><code>for row in d.rows(): pri...
1
2016-07-08T16:44:36Z
38,272,141
<p>If you want your rows ordered alphabetically by key you might consider:</p> <pre><code>zip(*(v for k, v in sorted(d.iteritems()))) # [(1, 'a', 'd', 4), (2, 'b', 'e', 5), (3, 'c', 'f', 6)] </code></pre> <p>If your dataset is huge then consider itertools.izip or pandas.</p> <pre><code>import pandas as pd df = pd.Da...
1
2016-07-08T17:10:36Z
[ "python", "dictionary" ]
Print a dictionary by rows
38,271,768
<p>I have a dictionary in this format:</p> <pre><code>d = {'type 1':[1,2,3],'type 2':['a','b','c']} </code></pre> <p>It's a symmetric dictionary, in the sense that for each key I'll always have the same number of elements.</p> <p>There is a way to loop as if it were rows:</p> <pre><code>for row in d.rows(): pri...
1
2016-07-08T16:44:36Z
38,272,331
<p>Even you pass the dictionary to <strong>OrderedDict</strong> you will not get ordered result as dictionary entry. So here tuples of tuple can be a good option. </p> <p>See the code and output below:</p> <p><strong>Code (Python 3):</strong></p> <pre><code>import collections t = (('type 1',[1,2,3]), ('type 2',...
1
2016-07-08T17:25:02Z
[ "python", "dictionary" ]
sympy lambdify: how to make more functions (NCDF, NPDF, etc) available
38,271,772
<p>How do I make sympy’s <a href="http://docs.sympy.org/dev/modules/utilities/lambdify.html" rel="nofollow"><code>lambdify</code></a> accept more function names, like a Normal function, for example? To make something like this work:</p> <pre><code>lambdify(('x',), 'NPDF(x, 0, 1)') </code></pre> <p>I don’t mind us...
2
2016-07-08T16:44:56Z
38,314,758
<p>If you have a numerical implementation of the function you want to use, pass it in the second argument, like</p> <pre><code>lambdify(x, NPDF(x, 0, 1), modules=['numpy', {'NPDF': NPDF_implementation}]) </code></pre>
1
2016-07-11T19:31:28Z
[ "python", "sympy", "lambdify" ]
Unmerged Cell For Loop skipping cells
38,271,775
<p>I am using openpyxl and found some code through goolging about unmerging cells in an xlsx workbook. </p> <p>I got the code to work, but found that it was not removing all the merged cells in a single pass through. I set it up to run using a while loop and solved the issue, but was wondering what I am doing wrong to...
2
2016-07-08T16:45:01Z
38,272,755
<p><code>ws.merged_cell_ranges</code> is mutable so you need to be careful that it is not directly used in any for-loop, because the implicit counter won't take into account that the property has been recalculated. This is a common gotcha in Python illustrated by:</p> <pre><code>l = list(range(10)) for i in l: pri...
2
2016-07-08T17:53:07Z
[ "python", "excel", "openpyxl" ]
How do I run a Python script from Java without hardcoded file path?
38,271,838
<p>Right now I have the absolute file path hardcoded into my Java program so that the Python script can be ran. However, when my program is deployed onto the company's platform, this file path will no longer be correct. The script is located in the same directory of the class which calls it, and this directory structur...
2
2016-07-08T16:48:09Z
38,271,936
<p>You can use this to return the file path that the Java class was executed from:</p> <pre><code>final File path = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); </code></pre> <p>You can then use this <code>path</code> object to load up the current directory and run yo...
2
2016-07-08T16:54:25Z
[ "java", "python", "filepath", "runtime.exec" ]
How do I run a Python script from Java without hardcoded file path?
38,271,838
<p>Right now I have the absolute file path hardcoded into my Java program so that the Python script can be ran. However, when my program is deployed onto the company's platform, this file path will no longer be correct. The script is located in the same directory of the class which calls it, and this directory structur...
2
2016-07-08T16:48:09Z
38,273,275
<p>After trying what @Confiqure suggested, I found that the path was going one step too far into the directory structure of my program. Instead I tried:</p> <pre><code>String path = new File("").getAbsolutePath + "/my/path/to/script"; </code></pre> <p>The <code>new File("").getAbsolutePath</code> returned the path to...
0
2016-07-08T18:31:15Z
[ "java", "python", "filepath", "runtime.exec" ]
cannot load image in flask on ubuntu
38,271,940
<p>I'm just new to Flask and I'm trying to do a project to learn it.I am trying to load a background image for my page and I've tried many ways.But it just gets 404 error . This is my signup.py file:</p> <pre><code>from flask import Flask , render_template from database_home import Profile from flask import Blueprint...
0
2016-07-08T16:54:33Z
38,272,329
<p>Here is a fix to your issue:</p> <p>1 - In <code>Blueprint</code> definition, make <code>static</code> pointing to the <code>static</code> folder instead to <code>css</code>:</p> <pre><code>sign_up = Blueprint('sign_up' , __name__, template_folder="/home/ali/Desktop/flasklearn/ccs/templates", static_folder="/home/...
0
2016-07-08T17:24:50Z
[ "python", "flask" ]
How to check if two nodes are connected with recursive function
38,271,944
<p>In an interview I have recently been asked a similar question as the below: I had to build a recursive function that shows whether two Nodes are connected. how can I make the below code work? Is there a way to pass a,b,c 'by reference' so when they become instantiated this is effective when I call check_connection. ...
1
2016-07-08T16:54:46Z
38,272,033
<p>The issue is that None is not a mutable object. Rather than setting a,b,c to None, you should have set them to Nodes with no neighbors. That way they would be changed by the declarations that followed. As you currently have it neighbors of a is not c but rather None, because c was just a variable pointing to None at...
1
2016-07-08T17:01:53Z
[ "python", "recursion", "pass-by-reference" ]
How to check if two nodes are connected with recursive function
38,271,944
<p>In an interview I have recently been asked a similar question as the below: I had to build a recursive function that shows whether two Nodes are connected. how can I make the below code work? Is there a way to pass a,b,c 'by reference' so when they become instantiated this is effective when I call check_connection. ...
1
2016-07-08T16:54:46Z
38,277,056
<p>This seems to work:</p> <pre><code>class Node(): def __init__(self): self.neighbours=None def check_connection(first, second): if second in first.neighbours: print ("Connection found") exit() else: for conection in first.neighbours: check_connection(conection...
0
2016-07-09T00:19:17Z
[ "python", "recursion", "pass-by-reference" ]
Applications of '~' (tilde) operator in Python
38,271,945
<p>I just discovered the <a href="https://en.wikipedia.org/wiki/Bitwise_operation#NOT">bitwise complement unary operation</a> in Python via <a href="https://stackoverflow.com/questions/8305199/the-tilde-operator-in-python">this question</a> and have been trying to come up with an actual application for it, and if not, ...
13
2016-07-08T16:54:50Z
38,272,035
<blockquote> <p>Are there any examples of valid use-cases for this operator that I should be aware of? And even if there are, is it generally acceptable to override this operator for types other than int?</p> </blockquote> <p>Typically, you would not want to overload the <code>~</code> operator just because it is fu...
6
2016-07-08T17:01:58Z
[ "python", "python-3.x", "operator-overloading", "bit-manipulation", "tilde" ]
Applications of '~' (tilde) operator in Python
38,271,945
<p>I just discovered the <a href="https://en.wikipedia.org/wiki/Bitwise_operation#NOT">bitwise complement unary operation</a> in Python via <a href="https://stackoverflow.com/questions/8305199/the-tilde-operator-in-python">this question</a> and have been trying to come up with an actual application for it, and if not, ...
13
2016-07-08T16:54:50Z
38,272,045
<p>The standard use cases for the bitwise NOT operator are bitwise operations, just like the bitwise AND <code>&amp;</code>, the bitwise OR <code>|</code>, the bitwise XOR <code>^</code>, and bitwise shifting <code>&lt;&lt;</code> and <code>&gt;&gt;</code>. Although they are rarely used in higher level applications, th...
11
2016-07-08T17:02:41Z
[ "python", "python-3.x", "operator-overloading", "bit-manipulation", "tilde" ]
Applications of '~' (tilde) operator in Python
38,271,945
<p>I just discovered the <a href="https://en.wikipedia.org/wiki/Bitwise_operation#NOT">bitwise complement unary operation</a> in Python via <a href="https://stackoverflow.com/questions/8305199/the-tilde-operator-in-python">this question</a> and have been trying to come up with an actual application for it, and if not, ...
13
2016-07-08T16:54:50Z
38,272,296
<p>You can use that operator in conjunction with the negation operator (<code>-</code>) to increment a number by 1. For example:</p> <pre><code>x = 5 assert -~x == 6 </code></pre> <p>This is the only practical way I've ever used the <code>~</code> operator. Any other way it is used for anything apart from numbers, is...
2
2016-07-08T17:23:03Z
[ "python", "python-3.x", "operator-overloading", "bit-manipulation", "tilde" ]
Applications of '~' (tilde) operator in Python
38,271,945
<p>I just discovered the <a href="https://en.wikipedia.org/wiki/Bitwise_operation#NOT">bitwise complement unary operation</a> in Python via <a href="https://stackoverflow.com/questions/8305199/the-tilde-operator-in-python">this question</a> and have been trying to come up with an actual application for it, and if not, ...
13
2016-07-08T16:54:50Z
38,274,268
<p>It's commonly used in <a href="http://codegolf.stackexchange.com/">code golf</a> as a shortcut for a few things, such as using <code>~x</code> rather than <code>-x-1</code> or <code>~my_bool</code> rather than <code>not my_bool</code>.</p>
1
2016-07-08T19:41:22Z
[ "python", "python-3.x", "operator-overloading", "bit-manipulation", "tilde" ]
Tkinter: <<ListboxSelect>> event thrown before 'active' item is updated?
38,272,044
<p>So I just came across this issue, and it's been driving me crazy for a couple hours now... I have a <code>Listbox</code> with several items on it. I bind the <code>&lt;&lt;ListboxSelect&gt;&gt;</code> event binded to a function called <code>onSelected</code>.</p> <p>This function should print the item that got sele...
0
2016-07-08T17:02:33Z
38,272,470
<p>The "active" element is not the same as the selection, and it is updated on button release. You are correct that the active element may lag behind the current selection. The selected items are updated on button press. Actually, the updating of the active element on a button click isn't documented, so it may be platf...
0
2016-07-08T17:34:53Z
[ "python", "tkinter", "listbox" ]
metrics.f1_score - length of unsized object
38,272,133
<p>Newbie to Python and sklearn here. I'm getting a "type error" on the following code that I don't understand. Can anyone help?</p> <pre><code>vectorizer = CountVectorizer() X = vectorizer.fit_transform(train_data) Y = vectorizer.transform(dev_data) print Y.shape print dev_labels.shape parameters = {'n_neighbors':[...
1
2016-07-08T17:09:48Z
38,274,240
<p>You should simply change <code>scoring</code> parameter to <code>scoring='f1'</code>. This will do the job for you. </p> <p>Also you are using the <code>f1_score</code> method incorrectly. Your first parameter to it is the training data. Instead you are passing it the transformed feature vector which is not correct...
0
2016-07-08T19:39:50Z
[ "python", "scikit-learn" ]
Python SQLite3 Insert
38,272,168
<p>I'm getting an error when I insert values. My db has 3 columns. One autoincrement integer initialized here:</p> <pre><code>connection.execute("CREATE TABLE IF NOT EXISTS {tn} ({nf1} {ft1} PRIMARY KEY AUTOINCREMENT)"\ .format(tn = tableName, nf1 = "IDPK", ft1 = "INTEGER")) </code></pre> <p>and two text fields i...
1
2016-07-08T17:13:07Z
38,272,310
<p>There should be quotes arround <code>{col1}</code> and <code>{col2}</code> since they are being inserted as text values. For example, it currently is being evaluated like:</p> <pre><code>"INSERT INTO table_name VALUES (NULL, my text 1, my text 2)" </code></pre>
1
2016-07-08T17:23:40Z
[ "python", "sqlite3" ]
Python SQLite3 Insert
38,272,168
<p>I'm getting an error when I insert values. My db has 3 columns. One autoincrement integer initialized here:</p> <pre><code>connection.execute("CREATE TABLE IF NOT EXISTS {tn} ({nf1} {ft1} PRIMARY KEY AUTOINCREMENT)"\ .format(tn = tableName, nf1 = "IDPK", ft1 = "INTEGER")) </code></pre> <p>and two text fields i...
1
2016-07-08T17:13:07Z
38,272,587
<p><em>Don't use string formatting to insert variables into the query.</em> It is dangerous (you are vulnerable to <a href="https://en.wikipedia.org/wiki/SQL_injection" rel="nofollow">SQL injection attacks</a>) and error-prompt (as you can already see).</p> <p>Instead, <em>parameterize</em> your query:</p> <pre><code...
2
2016-07-08T17:43:25Z
[ "python", "sqlite3" ]
Curve fit with a piecewise function?
38,272,191
<p>As the title suggests, I am trying to do a curve fit with a piecewise function. Here is an example:</p> <pre><code>import numpy as np import scipy.optimize as sio x = np.array([0, 1, 2, 3, 4, 5]) y = np.array([2, 3, 4, 11, 18, 27]) def f(x, a): if x &lt;= 2: return x + a elif x &gt;= 3: re...
3
2016-07-08T17:14:46Z
38,272,370
<p>The overall problem is that you've written <code>f</code> as for scalars, but <code>x</code> and <code>a</code> are numpy arrays. This is the case both for your <code>if</code> line, and also the <code>return</code>s within the <code>if</code> statements.</p> <p>A solution most similar to your code would be to do:...
1
2016-07-08T17:27:09Z
[ "python", "numpy", "scipy", "ipython" ]
Curve fit with a piecewise function?
38,272,191
<p>As the title suggests, I am trying to do a curve fit with a piecewise function. Here is an example:</p> <pre><code>import numpy as np import scipy.optimize as sio x = np.array([0, 1, 2, 3, 4, 5]) y = np.array([2, 3, 4, 11, 18, 27]) def f(x, a): if x &lt;= 2: return x + a elif x &gt;= 3: re...
3
2016-07-08T17:14:46Z
38,273,734
<p>this is the kind of problem where you can use np.boolean arrays to your advantage. If you have a large array of data, it is much more efficient than looping over the array, and allows you to use arbitrary expressions as your if/else conditions.</p> <pre><code>import numpy as np import scipy.optimize as sio x = np...
1
2016-07-08T19:03:58Z
[ "python", "numpy", "scipy", "ipython" ]
Beautiful Soup Parsing Error
38,272,216
<p>I am trying to use beautifulsoup to first remove the <code>&lt;a&gt;</code> tags in the html string, but keep it's content. After that I would like to remove all tags and replace them with new lines.</p> <p>The strip_tags function is from <a href="http://stackoverflow.com/questions/1765848/remove-a-tag-using-beauti...
-1
2016-07-08T17:17:08Z
38,272,567
<blockquote> <p>The strip_tags function is from <a href="http://stackoverflow.com/questions/1765848/remove-a-tag-using-beautifulsoup-but-keep-its-contents">This post</a>.</p> </blockquote> <p>That function replaces tags with text they contain, recursively.</p> <p>Thus, your <code>'&lt;a&gt;test&lt;/a&gt;'</code> is...
-1
2016-07-08T17:42:07Z
[ "python", "beautifulsoup" ]
Beautiful Soup Parsing Error
38,272,216
<p>I am trying to use beautifulsoup to first remove the <code>&lt;a&gt;</code> tags in the html string, but keep it's content. After that I would like to remove all tags and replace them with new lines.</p> <p>The strip_tags function is from <a href="http://stackoverflow.com/questions/1765848/remove-a-tag-using-beauti...
-1
2016-07-08T17:17:08Z
38,272,945
<p>It behaves that way because the strip_tags function is manipulating NavigableStrings. (which is why you see all the unicode casts in strip_tags)</p> <p>When you run the soup.get_text("\n") it is seeing all elements of the NavigableString and adding the "\n" at the splits, even though there is no <code>&lt;a&gt;</co...
-1
2016-07-08T18:08:02Z
[ "python", "beautifulsoup" ]
How do I pass variable changes to a thread during execution in Python?
38,272,254
<p>I have created an app that controls LED lighting. I wanted to have support for color changing patterns. In order for other parts of the program to work, this section of code is being executed in a separate thread. Unfortunately, I cannot make changes to the color-cycling pattern through my web-based interface (fl...
1
2016-07-08T17:20:11Z
38,273,559
<blockquote> <p>Is there a way for me to pass the variable data to the thread (color1, color2, and speed)?</p> </blockquote> <p>Sure, take a look at the <a href="https://docs.python.org/2/library/queue.html" rel="nofollow">Queues</a>.</p> <p>What you need to do is let your producer push data such as color, speed ...
0
2016-07-08T18:52:47Z
[ "python", "multithreading", "flask" ]
Python Program Doesn't Execute Any Functions
38,272,316
<p>I'm currently learning python for fun. I'm used to coding in C++ and so far it's fairly easy to pickup. I wrote my first program on my own, but for some reason, it doesn't do anything and the functions I wrote won't execute. If I write print statements outside the functions, the statements execute, but it never goes...
0
2016-07-08T17:23:56Z
38,272,359
<p><code>StackAdder</code> is a function; it is neither <code>True</code> nor <code>False</code>, so <code>ConsecutivePrime</code> <em>is</em> called, it just doesn't do anything.</p>
4
2016-07-08T17:26:26Z
[ "python", "function", "primes" ]
Python Program Doesn't Execute Any Functions
38,272,316
<p>I'm currently learning python for fun. I'm used to coding in C++ and so far it's fairly easy to pickup. I wrote my first program on my own, but for some reason, it doesn't do anything and the functions I wrote won't execute. If I write print statements outside the functions, the statements execute, but it never goes...
0
2016-07-08T17:23:56Z
38,272,673
<p>Add these lines at the beginning of your <code>ConsecutivePrime()</code> function, and observe the output:</p> <pre><code>print(StackAdder == True) print(StackAdder == False) </code></pre> <p>You can see <code>False</code> printed twice, right? Surprised? Read the comments on the answer by Scott Hunter. May be tha...
0
2016-07-08T17:48:18Z
[ "python", "function", "primes" ]
Python Program Doesn't Execute Any Functions
38,272,316
<p>I'm currently learning python for fun. I'm used to coding in C++ and so far it's fairly easy to pickup. I wrote my first program on my own, but for some reason, it doesn't do anything and the functions I wrote won't execute. If I write print statements outside the functions, the statements execute, but it never goes...
0
2016-07-08T17:23:56Z
38,272,895
<p>There are major problems in the way you structured your code, and I will try to point out the most obvious mistakes in your functions:</p> <p>1) Regarding the function <code>isPrime(primeNum)</code>, this is the correct way of writing it:</p> <pre><code>def isPrime(primeNum): isPrime = False while not isPr...
0
2016-07-08T18:04:05Z
[ "python", "function", "primes" ]
Vectorizing image thresholding with Python/NumPy
38,272,339
<p>I've been trying to find a more efficient way to iterate through an image and split their properties on a threshold. In searching online and discussing with some programming friends they introduced me to the concept of vectorizing (particularly using numpy) a function. After much searching and trial and error, I can...
2
2016-07-08T17:25:14Z
38,272,475
<p>NumPy supports and encourages vectorization through its <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html#numpy.ndarray" rel="nofollow"><code>arrays</code></a> and <a href="http://docs.scipy.org/doc/numpy/reference/ufuncs.html" rel="nofollow"><code>ufuncs</code></a>. In your case, you h...
6
2016-07-08T17:35:44Z
[ "python", "arrays", "numpy", "image-processing", "vectorization" ]
How to sort bars in a Pandas Histogram
38,272,398
<p>I have a problem with the following code.</p> <pre class="lang-python prettyprint-override"><code>databisclose.loc[:,"Close Month Only"]=databisclose.loc[:,"Close Month"].dt.month serie = databisclose.loc[:,"Close Month Only"].value_counts() serie.plot(kind='bar') </code></pre> <p>Databisclose is a dataframe. The ...
-1
2016-07-08T17:29:24Z
38,272,476
<p>Just update this line by adding a parameter to avoid sorting (By default its true) - </p> <pre><code>serie = databisclose.loc[:,"Close Month Only"].value_counts(sort = False) </code></pre> <p>More about this function in the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.h...
1
2016-07-08T17:35:53Z
[ "python", "sorting", "pandas", "histogram" ]
Regular expression to extract IPV6 address alone
38,272,436
<p>I am trying to extract an IPV6 address from the below line. I am getting the below output.. I just want till the IPV6 address,not beyond that.That is i don't want to see Scope:Link</p> <p>Code:</p> <pre><code>out ='ifconfig eth6.36\r\neth6.36 Link encap:Ethernet HWaddr A0:36:9F:5F:24:EE \r\n inet addr...
1
2016-07-08T17:33:00Z
38,272,920
<p>You can move the parentheses according to your need. Like </p> <pre><code>pattern = '(eth6\.36\s+Link encap:Ethernet\s*HWaddr\s*\w\w:\w\w:.+\s*inet addr:36.36.36.10\s*Bcast:36.36.36.255\s*Mask:255.255.255.0\s*\inet6 addr:\s*\w\w\w\w:.+) Scope:Link' </code></pre> <p>will get</p> <pre><code>In [9]: match.groups()[...
1
2016-07-08T18:05:53Z
[ "python" ]
Regular expression to extract IPV6 address alone
38,272,436
<p>I am trying to extract an IPV6 address from the below line. I am getting the below output.. I just want till the IPV6 address,not beyond that.That is i don't want to see Scope:Link</p> <p>Code:</p> <pre><code>out ='ifconfig eth6.36\r\neth6.36 Link encap:Ethernet HWaddr A0:36:9F:5F:24:EE \r\n inet addr...
1
2016-07-08T17:33:00Z
38,281,218
<p>Since you're dealing with the (standardised) output of <code>ifconfig</code>, why not dispell with <em>regex</em>s entirely, and just manipulate the string? </p> <pre><code>$ cat /tmp/tmp.py #!/usr/bin/env python3 out ='ifconfig eth6.36\r\neth6.36 Link encap:Ethernet HWaddr A0:36:9F:5F:24:EE \r\n inet...
0
2016-07-09T11:14:16Z
[ "python" ]
Pandas: if-else not working on a column
38,272,493
<p>I want to define a column in which I want to put 1 or 0 if the date contained in another column is equal to a certain data.</p> <pre><code>DF[['column_i']]= 0 if DF[['column_j']] == '1983-11-08' else 1 </code></pre> <p>It seems that the operation is not defined univocally because it returns an error:</p> <blockqu...
0
2016-07-08T17:37:06Z
38,272,717
<p>You can do something like this using a <code>numpy.where</code> statement:</p> <pre><code>df['column_i'] = np.where(df['column_j'] == '1983-11-08', 0, 1) </code></pre>
2
2016-07-08T17:50:48Z
[ "python", "pandas", "dataframe" ]
Pandas: if-else not working on a column
38,272,493
<p>I want to define a column in which I want to put 1 or 0 if the date contained in another column is equal to a certain data.</p> <pre><code>DF[['column_i']]= 0 if DF[['column_j']] == '1983-11-08' else 1 </code></pre> <p>It seems that the operation is not defined univocally because it returns an error:</p> <blockqu...
0
2016-07-08T17:37:06Z
38,274,393
<p>in this particular case (when you need zero or one) you can do it this way:</p> <pre><code>DF[['column_i']] = (DF[['column_j']] != '1983-11-08').astype(np.int8) </code></pre> <p>using the fact that <code>True</code> and <code>False</code> values are represented as <code>1</code> and <code>0</code> internally in Py...
1
2016-07-08T19:51:00Z
[ "python", "pandas", "dataframe" ]
Why isn't a celery backend pointing to an ip that's not local host not working?
38,272,592
<pre><code>from celery import Celery app = Celery('tasks', backend='amqp://guest@192.168.99.100', broker='amqp://guest@192.168.99.100//') @app.task() def add(x, y): return x + y </code></pre> <p>I am successfully able to send celery tasks but when I try to get the results of the task it doesn't send them back. ...
0
2016-07-08T17:43:38Z
38,314,824
<p>I don't know exactly why this worked but it did</p> <p>Run the command with the --pool=threads/solo switch</p> <p>Celery -A proj.tasks worker -l info --pool=threads -n w1</p>
0
2016-07-11T19:36:12Z
[ "python", "rabbitmq", "task", "celery", "amqp" ]
Pickle in Python, incorrect received data
38,272,642
<p>I am creating simple server client architecture using pickle. When I receive data and print it, first number disaapear, why? how can I avoid this? for example: ({2,2,4}, {3,4}) - > ({2,4}, {3,4})</p> <p>server code: import pickle import socket</p> <pre><code>TCP_IP = '127.0.0.1' TCP_PORT = 5005 BUFFER_SIZE...
0
2016-07-08T17:46:30Z
38,273,083
<p>"{}" means you are using a set. In a set every item exists only once. Instead you can use a list with these -> "[]" or a tupel -> "()" So</p> <pre><code>wyslij_dane(({2,2,4}, {3,4})) </code></pre> <p>becomes</p> <pre><code>wyslij_dane(([2,2,4], [3,4])) </code></pre> <p>and so on.</p>
1
2016-07-08T18:18:22Z
[ "python", "server", "client", "pickle" ]
Find the right path with os.chdir() in digital ocean
38,272,645
<p>I tried several ways but never succeeded. I need to change the directory in digital ocean (<code>/home/vagrant</code>). I have files saved in the same folder as where the file.py file is. file.py and other files that file.py aims to execute are all in <code>/folder/PH/Programs</code>. When I ran <code>$python file.p...
0
2016-07-08T17:46:46Z
38,272,854
<p>Either you provide the full path to file, or do not put a slash at the beginning. That means the root directory. </p> <p>go with:</p> <pre><code>os.chdir('~/folder/PH/Programs') </code></pre> <p>If it is in your home directory, or otherwise specify the full path to file.</p> <p>(In fact, the path you say in your...
1
2016-07-08T18:00:33Z
[ "python", "terminal", "chdir" ]
Python : How to limit number of integers printed in a line?
38,272,662
<p>how would I be able to print say only 10 numbers per line when doing :</p> <pre><code>for a in range(100 , 201): print(a , end=" ") </code></pre> <p>Doing this would give </p> <pre><code>100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130...
-3
2016-07-08T17:47:42Z
38,272,742
<p>You can print out slices.</p> <pre><code>from itertools import takewhile, count, islice def slice_iterable(iterable, chunk): _it = iter(iterable) return takewhile(bool, (tuple(islice(_it, chunk)) for _ in count(0))) for chunk in slice_iterable(range(100, 201), 10): print(*chunk) </code></pre> <p>Ou...
6
2016-07-08T17:52:28Z
[ "python", "python-3.x" ]
How to upload file to server with django?
38,272,671
<p>I've found <a href="https://github.com/axelpale/minimal-django-file-upload-example/tree/master/src/for_django_1-9/myproject/myproject/myapp" rel="nofollow">this very simple code</a> for my problem but I've tried to repeat it in my project and there was no result. I think I do everything correctly but result is bad.<...
1
2016-07-08T17:48:16Z
38,272,789
<p>Replace</p> <pre><code>my_file = self.request.FILES['file'] </code></pre> <p>with</p> <pre><code>my_file = self.request.FILES['docfile'] </code></pre> <p>in your views.py</p>
1
2016-07-08T17:55:55Z
[ "python", "django", "file-upload" ]
Importing images in tensorflow
38,272,699
<p>I'm trying to import images and convert them to tensors. All the other solutions recommend making a <code>filename_queue</code> and using <code>tf.reader()</code>, but I can't get that to work... hence, I'm just going with the basics.</p> <p>I have a file called <code>test.jp</code>g in my desktop directory, and I'...
1
2016-07-08T17:49:52Z
38,272,906
<p>The function <code>tf.image.decode_jpeg</code> just constructs a graph node and adds it to an execution graph. You have to actually <em>evaluate</em> the node to <em>run</em> it and get its value as a <code>numpy</code> array. Try the following :</p> <pre><code>import tensorflow as tf image = tf.image.decode_jpeg(...
1
2016-07-08T18:04:53Z
[ "python", "image", "filesystems", "tensorflow" ]
How do I transpose a pandas dataframe while preserving the index and rename keys
38,272,708
<p>This is what I have:</p> <pre><code>df: A B C D 0 foo 1 3 5 7 1 moo 2 4 6 8 2 poo 3 5 7 9 </code></pre> <p>What I want:</p> <pre><code>df_Transposed: foo moo poo 0 A 1 2 3 1 B 3 4 5 2 C 5 6 7 3 D ...
0
2016-07-08T17:50:26Z
38,272,886
<h3>One liner (and gross)</h3> <pre><code>df.reset_index(0, drop=True).T.set_index([range(len(df.columns))], append=True).swaplevel(0, 1) </code></pre> <h3>Less gross</h3> <pre><code>df1 = df.reset_index(0, drop=True).T idx = pd.MultiIndex.from_tuples( zip(range(len(df1)), df1.index.tolist()) ) df1 = df1.set_ind...
2
2016-07-08T18:03:21Z
[ "python", "numpy", "pandas", "dataframe" ]
How do I transpose a pandas dataframe while preserving the index and rename keys
38,272,708
<p>This is what I have:</p> <pre><code>df: A B C D 0 foo 1 3 5 7 1 moo 2 4 6 8 2 poo 3 5 7 9 </code></pre> <p>What I want:</p> <pre><code>df_Transposed: foo moo poo 0 A 1 2 3 1 B 3 4 5 2 C 5 6 7 3 D ...
0
2016-07-08T17:50:26Z
38,272,924
<p>You could transpose, and then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.droplevel.html" rel="nofollow"><code>droplevel</code></a> to remove the extra column level</p> <pre><code>result.columns = result.columns.droplevel(0) </code></pre> <p>and use <a href="http://pandas.p...
2
2016-07-08T18:06:11Z
[ "python", "numpy", "pandas", "dataframe" ]
How do I transpose a pandas dataframe while preserving the index and rename keys
38,272,708
<p>This is what I have:</p> <pre><code>df: A B C D 0 foo 1 3 5 7 1 moo 2 4 6 8 2 poo 3 5 7 9 </code></pre> <p>What I want:</p> <pre><code>df_Transposed: foo moo poo 0 A 1 2 3 1 B 3 4 5 2 C 5 6 7 3 D ...
0
2016-07-08T17:50:26Z
38,273,266
<p>You could do something similar to piRSquared's answer, but with a different way of changing the index.</p> <pre><code>df1 = df.reset_index.(0, drop=True).T df1.index = pd.MultiIndex.from_tuples([(i,x) for i,x in enumerate(df1.index)]) </code></pre> <p>This will work for dataframes that aren't square as well as tho...
2
2016-07-08T18:30:26Z
[ "python", "numpy", "pandas", "dataframe" ]
How do I transpose a pandas dataframe while preserving the index and rename keys
38,272,708
<p>This is what I have:</p> <pre><code>df: A B C D 0 foo 1 3 5 7 1 moo 2 4 6 8 2 poo 3 5 7 9 </code></pre> <p>What I want:</p> <pre><code>df_Transposed: foo moo poo 0 A 1 2 3 1 B 3 4 5 2 C 5 6 7 3 D ...
0
2016-07-08T17:50:26Z
38,274,329
<p>This somewhat works, I couldnt find a way to drop labels(['level_0', 'index']) from multiIndex. </p> <pre><code> df3 = df.reset_index(0, drop=True).T.reset_index().reset_index() df3 = df3.set_index(['level_0', 'index']) df3 foo moo poo level_0 index 0 ...
1
2016-07-08T19:45:49Z
[ "python", "numpy", "pandas", "dataframe" ]
How do I transpose a pandas dataframe while preserving the index and rename keys
38,272,708
<p>This is what I have:</p> <pre><code>df: A B C D 0 foo 1 3 5 7 1 moo 2 4 6 8 2 poo 3 5 7 9 </code></pre> <p>What I want:</p> <pre><code>df_Transposed: foo moo poo 0 A 1 2 3 1 B 3 4 5 2 C 5 6 7 3 D ...
0
2016-07-08T17:50:26Z
38,274,763
<p>I was able to do it another way. Here's my code. After transposing:</p> <pre><code>df.columns = df.iloc[0] df = df.reset_index() df = df.drop(df.index[0]) df = df.reset_index() df =df.drop(["level_0","index"],axis = 1) </code></pre>
1
2016-07-08T20:17:29Z
[ "python", "numpy", "pandas", "dataframe" ]
most efficient way to read data from stdin in python
38,272,893
<p>I know the most efficient way to read data from file in chunks. But I want to read data from stdin and I want the fastest way to read data because time is a constraint in the execution of the code. I want to do this in python 2.7.</p> <p>Edit: Judging the best method to read data from stdin will depend on a lot of ...
-1
2016-07-08T18:03:41Z
38,272,913
<p>You can use the <code>fileinput</code> module. A good way to read from <code>STDIN</code> using this is as such</p> <pre><code>import fileinput as fi for line in fi.input(): // DO SOMETHING </code></pre>
1
2016-07-08T18:05:18Z
[ "python", "stdin" ]
opening a file without an extension python
38,272,946
<p>I would like to open a file called "summary" and read information out of it to write into an output file, however I cannot open "summary"</p> <p>I have tried to verify that the path exists - which works:</p> <pre><code>import os.path print os.path.exists('/Users/alli/Documents/Summer2016/sfit4_trial/summary') </co...
0
2016-07-08T18:08:05Z
38,273,010
<p>Have you tried?</p> <pre><code>... path = '/Users/alli/Documents/Summer2016/sfit4_trial' for infile in glob.glob(os.path.join(path, 'summary*')): ... </code></pre>
1
2016-07-08T18:12:36Z
[ "python" ]
Remove vba modules using python?
38,272,965
<p>It seems win32api should be able to do this given the answer <a href="http://VBComponents.Remove" rel="nofollow">here</a> and [.</p> <p>I would like to remove all modules from an excel workbook (.xls) using python</p>
0
2016-07-08T18:09:37Z
38,273,465
<p>Actually simply reading in the file with <a href="https://pypi.python.org/pypi/xlrd" rel="nofollow"><code>xlrd</code></a>, copying with <a href="https://pypi.python.org/pypi/xlutils" rel="nofollow"><code>xlutils</code></a>, and spitting it out with <a href="https://pypi.python.org/pypi/xlwt" rel="nofollow"><code>xlw...
0
2016-07-08T18:44:23Z
[ "python", "excel", "winapi" ]
Remove vba modules using python?
38,272,965
<p>It seems win32api should be able to do this given the answer <a href="http://VBComponents.Remove" rel="nofollow">here</a> and [.</p> <p>I would like to remove all modules from an excel workbook (.xls) using python</p>
0
2016-07-08T18:09:37Z
38,287,230
<p>Consider using the <a href="https://msdn.microsoft.com/en-us/library/aa443983(v=vs.60).aspx" rel="nofollow">VBComponents collection</a> available in the COM interface accessible with Python's <code>win23com.client</code> module. However, inside the particular workbook you need to first grant <a href="http://stackove...
0
2016-07-09T23:36:06Z
[ "python", "excel", "winapi" ]
Return cv::Mat with Swig and use in Python
38,273,006
<p>I am returning a cv::Mat in a C++ implementation. It is wrapped with Swig and I read the return value in Python.</p> <p>In Python, the type is shown as . Note, I am returning a cv::Mat, but it shows as type cv::Mat* in Python. So I can't use it as a normal opencv Image object in Python. What can I do to fix this? <...
0
2016-07-08T18:12:16Z
38,962,926
<p>All unspecified types are handled as pointers by SWIG. To receive a cv::Mat as a proper Python class you must provide at least that class declaration to SWIG. I have done some code with that and some others functionalities, look at <a href="https://github.com/renatoGarcia/opencv-swig" rel="nofollow">https://github.c...
1
2016-08-15T20:56:17Z
[ "python", "opencv", "swig" ]
Finding all occurances of a substring then deleting a few previous characters up to a previous space in python for all occurances
38,273,075
<p>I am having trouble finding out how to do this:</p> <p><code>string = "A'' E'R4 B CR2 G''R8"</code></p> <p>What I want to do is locate all R characters in string, then remove previous characters up to previous space so it looks like this:</p> <p><code>"A'' R4 B R2 R8"</code></p> <p>If anyone can help in what dir...
-1
2016-07-08T18:17:50Z
38,273,134
<p>You can use <em>regular expressions</em> to solve this problem.</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; &gt;&gt;&gt; s = "A'' E'R4 B CR2 G''R8" &gt;&gt;&gt; re.sub(r"(?&lt;=\s)\S+(?=R)", "", s) "A'' R4 B R2 R8" </code></pre> <p>where:</p> <ul> <li><code>(?&lt;=\s)</code> is a <em>positive lookbehind</...
0
2016-07-08T18:21:14Z
[ "python", "regex", "string" ]
python replace placeholder values in a string
38,273,213
<p>I have below requirement in python,where I need to pass date and id at run time.</p> <pre><code>query_str="select * from test_table where data_date = '${data_date}' and id = ${id}" Where data_date is string column and id is big int column. </code></pre> <p>If i'm passing data_date as 2015-01-01 and id as 1, it ...
-6
2016-07-08T18:26:29Z
38,273,328
<p>What you are actually asking about is called <a href="http://stackoverflow.com/questions/1633332/how-to-put-parameterized-sql-query-into-variable-and-then-execute-in-python"><em>query parameterization</em></a> and it has to be done right relying on what your database driver provides. This way you let your driver han...
3
2016-07-08T18:34:40Z
[ "python" ]
How to repeat individual characters in strings in Python
38,273,353
<p>I know that </p> <pre><code>"123abc" * 2 </code></pre> <p>evaluates as <code>"123abc123abc"</code>, but is there an easy way to repeat individual letters N times, e.g. convert <code>"123abc"</code> to <code>"112233aabbcc"</code> or <code>"111222333aaabbbccc"</code>?</p>
4
2016-07-08T18:36:47Z
38,273,369
<p>What about:</p> <pre><code>&gt;&gt;&gt; s = '123abc' &gt;&gt;&gt; n = 3 &gt;&gt;&gt; ''.join(char*n for char in s) '111222333aaabbbccc' &gt;&gt;&gt; </code></pre>
15
2016-07-08T18:37:59Z
[ "python", "string" ]
How to repeat individual characters in strings in Python
38,273,353
<p>I know that </p> <pre><code>"123abc" * 2 </code></pre> <p>evaluates as <code>"123abc123abc"</code>, but is there an easy way to repeat individual letters N times, e.g. convert <code>"123abc"</code> to <code>"112233aabbcc"</code> or <code>"111222333aaabbbccc"</code>?</p>
4
2016-07-08T18:36:47Z
38,273,442
<p>An alternative <a href="https://docs.python.org/3/library/itertools.html" rel="nofollow"><code>itertools</code></a>-problem-overcomplicating-style option with <code>repeat()</code>, <code>izip()</code> and <code>chain()</code>:</p> <pre><code>&gt;&gt;&gt; from itertools import repeat, izip, chain &gt;&gt;&gt; "".jo...
4
2016-07-08T18:42:56Z
[ "python", "string" ]
How to repeat individual characters in strings in Python
38,273,353
<p>I know that </p> <pre><code>"123abc" * 2 </code></pre> <p>evaluates as <code>"123abc123abc"</code>, but is there an easy way to repeat individual letters N times, e.g. convert <code>"123abc"</code> to <code>"112233aabbcc"</code> or <code>"111222333aaabbbccc"</code>?</p>
4
2016-07-08T18:36:47Z
38,273,445
<p>If you want to repeat <em>individual</em> letters you can just replace the letter with n letters e.g.</p> <pre><code>&gt;&gt;&gt; s = 'abcde' &gt;&gt;&gt; s.replace('b', 'b'*5, 1) 'abbbbbcde' </code></pre>
1
2016-07-08T18:43:08Z
[ "python", "string" ]
How to repeat individual characters in strings in Python
38,273,353
<p>I know that </p> <pre><code>"123abc" * 2 </code></pre> <p>evaluates as <code>"123abc123abc"</code>, but is there an easy way to repeat individual letters N times, e.g. convert <code>"123abc"</code> to <code>"112233aabbcc"</code> or <code>"111222333aaabbbccc"</code>?</p>
4
2016-07-08T18:36:47Z
38,273,449
<p>@Bahrom's answer is probably clearer than mine, but just to say that there are many solutions to this problem:</p> <pre><code>&gt;&gt;&gt; s = '123abc' &gt;&gt;&gt; n = 3 &gt;&gt;&gt; reduce(lambda s0, c: s0 + c*n, s, "") '111222333aaabbbccc' </code></pre> <p>Note that <code>reduce</code> is not a built-in in pyth...
1
2016-07-08T18:43:33Z
[ "python", "string" ]
How to repeat individual characters in strings in Python
38,273,353
<p>I know that </p> <pre><code>"123abc" * 2 </code></pre> <p>evaluates as <code>"123abc123abc"</code>, but is there an easy way to repeat individual letters N times, e.g. convert <code>"123abc"</code> to <code>"112233aabbcc"</code> or <code>"111222333aaabbbccc"</code>?</p>
4
2016-07-08T18:36:47Z
38,273,538
<p>Or using regular expressions:</p> <p></p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = '123abc' &gt;&gt;&gt; n = 3 &gt;&gt;&gt; re.sub('(.)', r'\1' * n, s) '111222333aaabbbccc' </code></pre>
1
2016-07-08T18:51:08Z
[ "python", "string" ]
How to repeat individual characters in strings in Python
38,273,353
<p>I know that </p> <pre><code>"123abc" * 2 </code></pre> <p>evaluates as <code>"123abc123abc"</code>, but is there an easy way to repeat individual letters N times, e.g. convert <code>"123abc"</code> to <code>"112233aabbcc"</code> or <code>"111222333aaabbbccc"</code>?</p>
4
2016-07-08T18:36:47Z
38,273,552
<p>Another way:</p> <pre><code>def letter_repeater(n, string): word = '' for char in list(string): word += char * n print word letter_repeater(4, 'monkeys') mmmmoooonnnnkkkkeeeeyyyyssss </code></pre>
1
2016-07-08T18:52:12Z
[ "python", "string" ]