Unnamed: 0 int64 0 1.91M | id int64 337 73.8M | title stringlengths 10 150 | question stringlengths 21 64.2k | answer stringlengths 19 59.4k | tags stringlengths 5 112 | score int64 -10 17.3k |
|---|---|---|---|---|---|---|
2,800 | 72,678,949 | Finding out if values in dataframe increases in tens place | <p>I'm trying to figure out if the value in my dataframe is increasing in the tens/hundreds place. For example I created a dataframe with a few values, I duplicate the values and shifted them and now i'm able to compare them. But how do i code and find out if the tens place is increasing or if it just increasing by a l... | <p>IIUC, divide by 10, get the <code>floor</code>, then compare the successive values (<code>diff(1)</code>) to see if the difference is exactly 1:</p>
<pre><code>np.floor(df['value'].astype(float).div(10)).diff(1).eq(1).astype(int)
</code></pre>
<p>If you want a jump to at least the next tens (or more) use <code>ge</c... | python|pandas|dataframe | 2 |
2,801 | 16,060,625 | Python: access structure field through its name in a string | <p>In Scapy, I want to compare a number of header fields between any two packets <code>a</code> and <code>b</code>. This list of fields is predefined, say:</p>
<pre><code>fieldsToCompare = ['tos', 'id', 'len', 'proto'] #IP header
</code></pre>
<p>Normally I would do it individually:</p>
<pre><code>if a[IP].tos == b[... | <p>You can use <a href="http://docs.python.org/2/library/functions.html#getattr"><code>getattr()</code></a>. These lines are equivalent:</p>
<pre><code>getattr(x, 'foobar')
x.foobar
</code></pre>
<p><a href="http://docs.python.org/2/library/functions.html#setattr"><code>setattr()</code></a> is its counterpart.</p> | python|ip|structure|field|scapy | 29 |
2,802 | 31,965,625 | GAE launcher Python installation can't import module six | <p>I just recently launched my local Google App Engine sandbox Python application after not touching it in a while. It seems the following import is giving me problems, but this didn't happen before.</p>
<pre><code>from googleapiclient.discovery import build
</code></pre>
<p>This results in the import error:</p>
<pr... | <p>The problem was introduced by some updated libraries included with Google App Engine launcher. To avoid the import error, you'll need to include module six into you project. It can be found <a href="https://pypi.python.org/pypi/six" rel="nofollow">here</a></p> | python|google-app-engine|google-cloud-endpoints | 1 |
2,803 | 51,961,033 | How to deal with MinMaxScaler when there is only a single input? | <p>I was working with <code>MinMaxScaler</code>. So the following input:</p>
<pre><code>data = [[-1, 2], [-0.5, 6], [0, 10], [1, 18]]
</code></pre>
<p>would be transformed in the range(0,1) as follows:</p>
<pre><code>[[ 0. 0. ]
[ 0.25 0.25]
[ 0.5 0.5 ]
[ 1. 1. ]]
</code></pre>
<p>Now how to transform ... | <p>There are a few plausible interpretations of what you're asking.</p>
<ul>
<li>If you're interested in using a single variable for your <strong>training set</strong>, scaling everything to 0 is a reasonable interpretation. Without some sort of domain knowledge or other sources of information, the best guess you have... | python|pandas|scikit-learn | 2 |
2,804 | 10,015,590 | index python dictionary by value | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/2568673/inverse-dictionary-lookup-python">Inverse dictionary lookup - Python</a> </p>
</blockquote>
<p>Is there a built in way to index a dictionary by value in Python.</p>
<p>e.g. something like:</p>
<pre><c... | <p>You could use a <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>:</p>
<pre><code>my_dict = {'fruit':'apple','colour':'blue','meat':'beef'}
print [key for key, value in my_dict.items() if value == 'apple']
</code></pre>
<p>The code above is doin... | python|dictionary | 5 |
2,805 | 68,029,851 | How do I slice a line from a text file in python? | <p>Currently I am working on a python password manager. Its not too complex, just a simple commandline interface. I have made one file in which the passwords and usernames are stored in the following format:</p>
<pre><code>servicenameusername-usernameinput
servicenamepassword-generatedpassword
</code></pre>
<p>for eg:<... | <p>Some <code>string.split()</code> magic will resolve this. I added some logic to be able to deal with usernames or passwords containing the <code>-</code> character</p>
<p><strong>password.py</strong></p>
<pre class="lang-py prettyprint-override"><code>from pprint import pprint
def process_two_lines(line1: str, lin... | python|string|text-files|slice | 1 |
2,806 | 26,320,840 | Create scatterplot in pandas using row as index and row as data | <p>First off, let me say that I just began using the pandas module a few days ago, so apologies if there is a simple solution to this that I was unaware of. I am trying to make a scatterplot in pandas using a specific row as the index (for the x-axis) and a specific row for the data to be plotted. I want this to be exe... | <pre><code>In [3]: df.T.plot(kind='scatter', x=4, y=1)
</code></pre>
<p>The <code>.T</code> transposes the matrix, so <code>4</code> is now the column you use as the <code>x</code> axis.</p> | python|pandas|scatter-plot | 1 |
2,807 | 26,180,946 | What are the differences with the code below? | <p>I'm writing a few pieces of code and I've got some questions</p>
<pre><code>def fanction(tata):
for i in range(0,4):
tata +i
print tata
tata = 0
fanction(tata)
</code></pre>
<p>The results are </p>
<pre><code>0
0
0
0
</code></pre>
<p>Second piece of code :</p>
<pre><code>def fbnction(tbtb):... | <p><code>tata + i</code> does not change <code>tata</code>. It just returns added value.</p>
<p>If you want <code>tata</code> to be changed, you need to assign back the added result.</p>
<pre><code>tata = tata + i
</code></pre>
<p>or</p>
<pre><code>tata += i
</code></pre>
<hr>
<pre><code>>>> tata = 5
>... | python|python-2.7 | 4 |
2,808 | 2,155,509 | Basics of string based protocol security | <p>I wasn't sure how to phrase this question, so apologies in advance if it's a duplicate of something else.</p>
<p>I wanted to sanity check how I've secured my twisted based application and think I've done a good job at it, but it's been over a decade since I've written anything that uses raw or managed sockets.</p>
... | <p>The protocol you described addresses one attack, that is the a replay attack. However, you are very vulnerable to MITM attacks. The TCP connection won't drop when the attacker moves in on the protocol. Further more anything transferred over this system can be sniffed. If you are on the wireless at a cafe everyo... | python|networking|encryption|cryptography|twisted | 6 |
2,809 | 2,114,510 | Preserving argument default values while method chaining | <p>If I have to wrap an existing method, let us say wrapee() from a new method, say wrapper(), and the wrapee() provides default values for some arguments, how do I preserve its semantics without introducing unnecessary dependencies and maintenance? Let us say, the goal is to be able to use wrapper() in place of wrapee... | <p>Check out <a href="http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists" rel="nofollow noreferrer">argument lists</a> in the Python docs.</p>
<pre><code>>>> def wrapper(param1, *stuff, **kargs):
... print(param1)
... print(stuff)
... print(args)
...
>>> wrapper(3, 4, 5, foo... | python | 3 |
2,810 | 32,194,539 | python selenium send css with !important | <p>I would like to change the css of the element as follows. It works fine when:</p>
<pre><code>browser.execute_script(
"arguments[0].style.display = 'block';",
browser.find_element_by_xpath("//div[@role='main']/div/div/div["+str(d)+"]/div["+str(r)+"]/div/div[2]")
)
</code></pre>
<p>but when I try to add the ... | <p>The statement element.style.display = 'block' will only work for setting the value of <em>valid</em> property values. Since 'block !important' is not recognized, it will not be added. !important itself is a declaration.</p>
<p>You can use .setProperty() instead, which will let you add more than the value. Use 'impo... | javascript|python|css|selenium | 1 |
2,811 | 32,241,085 | Extrapolating data from a curve using Python | <p>I am trying to extrapolate future data points from a data set that contains one continuous value per day for almost 600 days. I am currently fitting a 1st order function to the data using <code>numpy.polyfit</code> and <code>numpy.poly1d</code>. In the graph below you can see the curve (blue) and the 1st order funct... | <p>The very general rule of thumb is that if your fitting function is not fitting well enough to your actual data then either:</p>
<ul>
<li>You are using the function wrong, e.g. You are using 1st order polynomials - So if you are convinced that it is a polynomial then try higher order polynomials.</li>
<li><p>You are... | python|numpy|statistics|regression|polynomial-math | 1 |
2,812 | 44,149,394 | Select a random row from the table using Python | <p>Below is the my table.I use MySQL for the database queries. </p>
<p><strong>Structure of the table</strong></p>
<p><a href="https://i.stack.imgur.com/lu8Kr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lu8Kr.png" alt="enter image description here"></a></p>
<p>I want to print questions randoml... | <pre><code>from random import randint
num = randint(1,5)
</code></pre>
<p>Then db query:</p>
<pre><code>SELECT question FROM your_table WHERE ques_id = num;
</code></pre>
<p>Alternatively:</p>
<pre><code>SELECT question FROM your_table LIMIT num-1, 1;
</code></pre>
<p>num would be a random number between 1 and 5, ... | python|database|random | 1 |
2,813 | 33,058,003 | django: set model fields as choices in models.py | <p>Is it possible to set the choices of a field from another table?
for example</p>
<pre><code>class Initial_Exam(models.Model):
Question_category = models.CharField(max_length=20, choices = Job.Job_Position)
class Job(models.Model):
Job_Position = models.CharField(max_length=30, null=True)
</code></pre>
<p>... | <p>To close this:
As commented above, instead of twisting my implementation, setting the foreign key for <code>Initial_Exam</code> and using <code>__unicode__</code> on <code>Job</code> did the job</p>
<p>should look like this:</p>
<p><code>class Job(models.Model):
Job_Position = models.CharField(max_length=30, n... | python|django|python-2.7|django-models | 0 |
2,814 | 14,143,611 | Splitter window display issue | <p>I am writing a program which has a TreeCtrl on the left and a RichTextCtrl on the right.
Following is the code of the splitter, panel and other elements. </p>
<p>The problem is that in windows, the bottom of the treectrl and textctrl is hidden. The statusbar covers the bottom of the splitter. But even after removin... | <p>I think the issue here may be that you've explicitly told the SplitterWindow to take up the entire display size. Try omitting the size argument to the constructor, or adjust it down some, to see if that has any effect.</p>
<p>If omitting the size parameter does not help, I'd suggest creating Panels with Sizers tha... | python|wxpython | 0 |
2,815 | 54,498,368 | What is a NameError and how can I fix it? | <p>I have defined a function to return the indices of certain occurrences in a list. However, when I try to run my doctests, it returns a NameError, but exits with 'exit code 0' meaning there's no problems with it. </p>
<pre><code>def build_placements(shoes):
"""Return a dictionary where each key is a company, and... | <p>Your error is here:</p>
<pre><code>for value in item:
value += 1
</code></pre>
<p><code>item</code> is an element of the <code>shoes</code> list, all elements of <code>shoes</code> are strings. You cannot add an integer to a string. So <code>value += 1</code> raises an error, and because of this the whole func... | python | 1 |
2,816 | 34,736,343 | Django: Object is not iterable when trying to instantiate an object | <p>I am getting 'Players' object is not iterable when I am trying to save some form data, and I don't understand why.</p>
<p>Here is my RequestedPartners model:</p>
<pre><code>class RequestedPartners(models.Model):
first_nm = models.CharField('Requested Partner First Name', max_length=100)
last_nm = models.Ch... | <p><code>RequestedPartners.player</code> is a ManyToManyField. As per the <a href="https://docs.djangoproject.com/es/1.9/topics/db/examples/many_to_many/" rel="nofollow">documentation</a> they have a special api when you need to assign values to them.</p>
<p>First, you need to save the <code>RequestedPartners</code> o... | python|django | 1 |
2,817 | 27,035,511 | Skype4Py MessageStatus not firing consistently | <p>I'm trying to make a basic Skype bot using <code>Skype4Py</code> and have encountered a rather serious error. I am working on a 64 bit windows 7 with the 32bit Python 2.7.8. installed, along with the latest version of Skype4Py.</p>
<p>My main demand is that the bot has an overview of <code>5</code> different Skype ... | <p>Unfortunately, this is probably a bug in the Skype API.
This <a href="http://blogs.skype.com/2013/11/06/feature-evolution-and-support-for-the-skype-desktop-api/" rel="nofollow">help post</a> indicates that support for the API is being revoked, saying:</p>
<blockquote>
<p>Important: As communicated in this blog po... | python|skype4py | 1 |
2,818 | 23,326,247 | AttributeError: type object X has no attribute Y | <p>So I'm a Django noob although I'm quite familiar with the Python syntax. I keep getting this error:</p>
<pre><code>AttributeError at /dashboard/home/
type object 'Member' has no attribute 'dept1'
</code></pre>
<p>every time I try to go to my dashboard/home/ url.</p>
<p>I have created a Custom User Model as given ... | <p>You're trying to access the <code>dept1</code> attribute of the Member <em>class</em>, but you ought to be getting the attribute from an <em>instance</em> of the Member class.</p>
<p>So, your view function should look more like this:</p>
<pre><code>current_member = Member.objects.get(user = request.user)
post_list... | python|django | 3 |
2,819 | 23,201,647 | organizing numbers in numpy | <p>I have some numbers in list which i want to organize with numpy.Heres my code</p>
<pre><code>lst=['99.56','99.76','99.84','100.00','100.00','100.00','100.00','100.00','100.00','99.80','99.43']
lst2=[]
for i in np.arange(95.0,100.0,0.1):
x=0
for j in lst:
if float(i)+0.1>= float(... | <p>The <code>ndarray</code> generated by <code>numpy.arange</code> does generally <em>not</em> include the end value:</p>
<pre><code>In [15]: np.arange(99.0, 100., 0.1)
Out[15]: array([ 99. , 99.1, 99.2, 99.3, 99.4, 99.5, 99.6, 99.7, 99.8, 99.9])
</code></pre>
<p>Note that there is a built-in method <code>nu... | python|numpy | 2 |
2,820 | 1,071,793 | how to convert a python dict object to a java equivalent object? | <p>I need to convert a python code into an equivalent java code. Python makes life very easy for the developers by providing lots of shortcut functionalities. But now I need to migrate the same to Java. I was wondering what will the equivalent of dict objects in java? I have tried using HashMap but life is hell. For st... | <p>It's probably easiest to just create a class for the (Name, Strength) tuple:</p>
<pre><code>class NameStrength {
public String name;
public String strength;
}
</code></pre>
<p>Add getters, setters and a constructor if appropriate.</p>
<p>Then you can use the new class in your map:</p>
<pre><code>Map<I... | java|python|hashmap|dictionary | 4 |
2,821 | 58,240,937 | Writing a function that calculates the average value of 5 parameters from user input | <p>I need to build a code that will give the average sum of 5 user input parameters. I have to add all 5 parameters, and then divide the addition by 5. I also have to make sure the function uses the return command to return the average as the value for the function. Since I am a beginner I can't use advanced code. Been... | <h2>A pythonic implementation</h2>
<ul>
<li>Create <code>input</code> directly into a list and repeat with <code>range</code>
<ul>
<li>There's no need to create a separate object for each input</li>
<li>There's no need to then load those 5 objects into another object</li>
</ul></li>
<li>Convert <code>input</code> to ... | python-3.x|string|integer|average | 1 |
2,822 | 58,392,838 | How to get Information about sharpness of Image with Fourier Transformation? | <p>i am rookie with Matplotlib, Python, FFT.
My Task is to get information about sharpness of a Image with FFT, but how do i get this done? What i have done so far:</p>
<pre class="lang-py prettyprint-override"><code>#getImage:
imgArray2 = Camera.GetImage()
imgArray2 = cv2.flip(imgArray2, 0)
grayImage = Image.fromarr... | <p>As the comments pointed out, you are looking for high frequencies (frequencies away from the center of your 2D Fourier plot).
I'm giving a synthetic example. I added some noise to make it more similar to a real image.
In the 3rd line I'm showing a lowpass filter in the middle, multiply the FFT spectrum to the right... | python|numpy|matplotlib|fft | 1 |
2,823 | 33,948,081 | Automatically writing headers using csv python | <p>I'm trying to write a motif finding function which takes amino acid fasta as an input and outputs an motifs in the excel file.</p>
<p>My desired output looks like this..</p>
<pre><code>SeqName M1 Hits M2 Hits
Seq1 MN[A-Z] 3 V[A-Z]R[ML] 2
Seq2 MN[A-Z] 0 V[A-Z]R[ML] 5
S... | <p>It is simple. make header row,</p>
<pre><code>>>> headerrow = ['SeqName']
>>> for i in range(1,6):
... headerrow.append('M%d' % i)
... headerrow.append('Hits')
...
>>> headerrow
['SeqName', 'M1', 'Hits', 'M2', 'Hits', 'M3', 'Hits', 'M4', 'Hits', 'M5', 'Hits']
</code></pre>
<p>and wri... | python|csv | 1 |
2,824 | 33,636,973 | How to store HDF5 (HDF Store) in a Django model field | <p>I am currently working on a project where I generate pandas DataFrames as results of analysis. I am developing in Django and would like to use a "data" field in a "Results" model to store the pandas DataFrame.</p>
<p>It appears that HDF5(HDF Store) is the most efficient way to store my pandas DataFrames. However, I... | <p>You can create a <a href="https://docs.djangoproject.com/en/2.2/howto/custom-model-fields/" rel="nofollow noreferrer">custom Model field</a> that saves your data to a file in storage and saves the relative file path to the database.</p>
<p>Here is how you could subclass <code>models.CharField</code> in your app's <... | python|django|pandas|hdfstore|django-custom-field | 1 |
2,825 | 33,734,810 | Python Regex for extracting specific part from string | <p>I have the following string:</p>
<pre><code>SOURCEFILE: file_name.dc : 1 : log: the logging area
</code></pre>
<p>I am trying to store anything inbetween the third and the fourth colon in a variable and discard the rest.</p>
<p>I've tried to make a regular expression to grab this but so far i have this which... | <pre><code>>>> import re
>>> s = "SOURCEFILE: file_name.dc : 1 : log: the logging area"
>>> s1 = re.sub(r"[^\:]*\:[^\:]*\:[^\:]*\:([^\:]*)\:.*", r"\1", s)
>>> print s1
log
</code></pre> | python|regex | 1 |
2,826 | 37,857,531 | How to find particular column unique values count in python pandas? | <p>I have following dataframe.,</p>
<pre><code>company,sector,marks
a,b1,21
b,b2,27
c,b2,20
a,b3,70
</code></pre>
<p>I have to display no of company,sector and sum of marks
how do we take unique column value length in pandas </p> | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.nunique.html" rel="nofollow"><code>nunique</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sum.html" rel="nofollow"><code>sum</code></a>:</p>
<pre><code>print (pd.Series([df.c... | python|python-2.7|pandas|dataframe | 1 |
2,827 | 27,843,361 | Add or subtract to integer db field using sqlform in web2py | <p>I have set up the db table with the following fields:</p>
<pre><code>db.define_table('balance',
Field('income', 'integer'),
Field('income_description', "text"),
Field('expenses', 'integer'),
Field('expenses_discription', "text"),
Field... | <p>What you need to use is a <a href="http://www.web2py.com/books/default/chapter/29/06/the-database-abstraction-layer#Computed-fields" rel="nofollow">Computed Field</a>:</p>
<pre><code>>>> db.define_table('item',
Field('unit_price','double'),
Field('quantity','integer'),
Field('total_... | python|web2py | 0 |
2,828 | 65,877,958 | Perlin Noise - Python's Ursina Game Engine | <p>Is there a way to incorporate Perlin Noise into my Minecraft Clone? I have tried many different things that did not work.</p>
<p>Here is a snippet of my code:</p>
<pre><code>from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController
from ursina.shaders import camera_grayscale_shad... | <p>To generate terrain using perlin noise, you can create a <code>Terrain</code> entity with the heightmap with your perlin noise image :</p>
<pre class="lang-py prettyprint-override"><code>from ursina import *
app = Ursina()
noise = 'perlin_noise_file' # file
t = Terrain(noise) # noise must be a file
app.run()
</... | python|ursina | 0 |
2,829 | 72,182,886 | Save iteration in dataframe | <p>I have two dataframes:</p>
<pre><code>import numpy as np
import pandas as pd
from sklearn.metrics import r2_score
df = pd.DataFrame([{'A': -4, 'B': -3, 'C': -2, 'D': -1, 'E': 2, 'F': 4, 'G': 8, 'H': 6, 'I': -2}])
</code></pre>
<p>df2 looks like this (just a cutout; in total there are ~100 rows).</p>
<pre><code>... | <p>You can store the result in every loop</p>
<pre class="lang-py prettyprint-override"><code>for index, row in df2.iterrows():
reg = np.polyfit(df.values[0], row.values, 1)
predict = np.poly1d(reg) # Slope and intercept
trend = np.polyval(reg, df)
std = row.std() # Standard deviation
r2 = np.round(... | python|pandas|dataframe | 1 |
2,830 | 36,840,438 | Binding list to params in Pandas read_sql_query with other params | <p>I've been trying to test various methods for making my code to run. To begin with, I have this list:</p>
<p><code>member_list = [111,222,333,444,555,...]</code></p>
<p>I tried to pass it into this query:</p>
<pre class="lang-py prettyprint-override"><code>query = pd.read_sql_query(
"""
select member id
,yearm... | <p>Break this up into three parts to help isolate the problem and improve readability:</p>
<ol>
<li>Build the SQL string</li>
<li>Set parameter values</li>
<li>Execute <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql_query.html" rel="noreferrer">pandas.read_sql_query</a></li>
</ol>
<hr />
... | python|pandas|pyodbc | 23 |
2,831 | 48,574,075 | Python - multiplying dataframes of different size | <p>I have two dataframes:</p>
<p>df1 - is a pivot table that has totals for both columns and rows, both with default names "All"
df2 - a df I created manually by specifying values and using the same index and column names as are used in the pivot table above. This table does not have totals.</p>
<p>I need to multiply... | <p>IIUC, </p>
<p><strong>My Preferred Approach</strong><br>
you can use the <code>mul</code> method in order to pass the <code>fill_value</code> argument. In this case, you'll want a value of <code>1</code> (multiplicative identity) to preserve the value from the dataframe in which the value is not missing.</p>
<pre... | python|pandas|dataframe|pivot-table|multiplication | 2 |
2,832 | 48,885,681 | Get the list of RGB pixel values of each superpixel | <p>l have an RGB image of dimension (224,224,3). l applied superpixel segmentation on it using SLIC algorithm.</p>
<p>As follow : </p>
<pre><code>img= skimageIO.imread("first_image.jpeg")
print('img shape', img.shape) # (224,224,3)
segments_slic = slic(img, n_segments=1000, compactness=0.01, sigma=1) # Up to 1000 seg... | <p>Can be done using <code>np.where</code> and the resulting indices.</p>
<pre><code>def sp_idx(s, index = True):
u = np.unique(s)
return [np.where(s == i) for i in u]
superpixel_list = sp_idx(segments_slic)
superpixel = [img[idx] for idx in superpixel_list]
</code></pre> | python-3.x|numpy|opencv|scikit-image|superpixels | 1 |
2,833 | 48,494,951 | Convert a list of a list of strings with decimals into floats | <p>I have a list of a list that goes like this: </p>
<pre><code>Main_List: [ ['1.2','3.5'],[ ['5.8','8.3'] ]
</code></pre>
<p>I am trying to convert one of the sublists into floats, here is what i did:</p>
<pre><code>Main_List[1] = [float(i) for i in Main_List[1]]
</code></pre>
<p>but i keep getting an error "Valu... | <p>I was able to figure it out, what i had to do is create another list and set it equal to the first sublist then turn all its elements to floats.</p>
<p>for example</p>
<pre><code>Sublist_1 = []
Sublist_1 = MainList[0]
Sublist_1 = map(float, Sublist_1)
</code></pre> | string|python-2.7|csv|floating-point | 0 |
2,834 | 48,690,189 | Taking the average of a sliced list | <p>The problem I'm having is attempting to take the average of my list (derived from y, which is a list of sin values). However, when running the code, I get the error </p>
<p>TypeError: float() argument must be a string or a number, not 'list'</p>
<p>Any help you could offer would be greatly appreciated</p>
<pre><c... | <p>You have made <code>list_to_avg</code> a list that contains a list.</p>
<p>Use</p>
<pre><code>list_to_avg = y[r+k:len(y)-1-r+k]
</code></pre>
<p>instead.</p> | python|list|sum|moving-average | 0 |
2,835 | 69,343,883 | Datetime format of a Pandas dataframe column switching randomly | <p>I am using a dataframe which has a 'Date' column. I have used <code>pd.to_datetime()</code> to convert this column format to yyyy-mm-dd. However, this format is getting switched to some other format at intermittent dates in the dataframe (eg: yyyy-dd-mm).</p>
<pre><code>Date
2021-02-01 <----- this is 2nd Jan, 20... | <p>The problem comes from how pandas parses dates.
When receiving <code>2021-02-01</code> it does not know if it is Feb 1st or Jan 2nd, so it applies its default decision rules: when the date starts with the year, the next field is the month, so resulting in Feb 1st.
This is not the case when parsing <code>2021-01-21</... | python|pandas|dataframe|date|datetime | 0 |
2,836 | 48,352,058 | Why are the two tkinter entries using the same number? | <pre><code>import os
import tkinter
import tkinter.font as tkFont
from tkinter import *
coord1 = "0,0"
coord2 = "0,0"
EQ = "y = mx + b"
def tkinter_window():
global coord1Entry
global coord2Entry
global coord1
global coord
tk = Tk()
tk.title("Math Graph")
#create
font1 = tkFont.Fon... | <p>It is because you are using identical strings for the <code>textvariable</code> option when you need to be using two different instances of one of the <a href="http://effbot.org/tkinterbook/variable.htm" rel="nofollow noreferrer">special tkinter variables</a> (<code>StringVar</code>, etc)</p>
<p>By the way, you alm... | python|python-3.x|tkinter | 3 |
2,837 | 47,999,097 | Django REST Framework custom headers in request object | <p>I have a problem viewing incoming custom headers from requests when I'm creating a new API view via the <code>@api_view</code> decorator. </p>
<p>My custom API view looks like this:</p>
<pre><code> @api_view(['GET'])
def TestView(request):
print(request.META)
return Response({'message': 'test'})
</code></pr... | <p>Django prepends <code>HTTP_</code> to the custom headers. I <strong>think</strong> (not sure, though) that it might be related to some security issues described <a href="https://www.djangoproject.com/weblog/2015/jan/13/security/" rel="nofollow noreferrer">here</a>. It also capitalizes them, so your <code>custom</cod... | python|django|django-rest-framework | 4 |
2,838 | 51,286,846 | How to change the target directory for a screenshot using Selenium webdriver in Firefox or Chrome | <p>I want to make a screenshot of a webpage and save it in a <strong>custom location</strong> using <em>Selenium webdriver with Python</em>. I tried saving the screenshot to a custom location using both Firefox and Chrome but it always saves the screenshot in the project dir. Here is my Firefox version:</p>
<pre><code... | <p>You need to consider a couple of facts as follows:</p>
<h2>profile.set_preference('key', 'value')</h2>
<p><a href="https://seleniumhq.github.io/selenium/docs/api/py/webdriver_firefox/selenium.webdriver.firefox.firefox_profile.html#selenium.webdriver.firefox.firefox_profile.FirefoxProfile.set_preference" rel="nofol... | python|selenium|selenium-webdriver|webdriver|selenium-chromedriver | 5 |
2,839 | 51,332,225 | Correctly assigning a data structure in python | <p>I have the following class:</p>
<pre><code>class Node():
def __init__(self, symbol, rule, children):
self.symbol = symbol
self.rule = rule
self.children = children
def addChild(self,child):
self.children.append(child)
</code></pre>
<p>I use it to build parsing trees; now I'... | <p>In your <code>simplify()</code> function, the parameter <code>n</code> is a reference to some specific node, and you can change what node it refers to; but reassigning <code>n</code> doesn't change any of the other structure. As a specific example, this loop actually does nothing:</p>
<pre><code>for c in n.childre... | python | 2 |
2,840 | 51,141,097 | How can I run a python script without python.exe | <p>My goal is to have a python script that I can giving to someone to run on their windows machine that does not have python installed. I do want to package it up in an exe because I want the underlying code to be easily read.</p>
<p>I am updating an old VBscript and I want to mirror it. I am also using a few librarie... | <p>use pyinstaller to package it up to an exe. You can still maintain your source code. Packaging it up wont remove your source code.</p> | python|windows|scripting | 0 |
2,841 | 51,502,479 | How to make a function use a variable outside the function, but in a method of a class | <p>I am trying to make a function that will be able to access a variable from outside the function. However, this variable needs to be defined in a class. I'll define a simplified function of what I am trying to do in code for clarity.</p>
<pre><code>class Stuff():
def __init__(self):
print("Initialized... | <p>You can't. A <em>member</em> variable belongs to a specific instance of a class. You have to know the instance to do that, so you'd better pass <code>y</code> to your function as well. </p>
<p>You could do the opposite though. use <code>global</code> in the <code>forward</code> function to define a global <code>y</... | python|function|class|variables|global | 3 |
2,842 | 17,463,209 | How convert a String to a String with HTML entities? | <p>I am looking for a way, preferably in <code>python</code>, but <code>PHP</code> is also ok or even an online site, to convert a string like</p>
<pre><code>"Wählen"
</code></pre>
<p>into a string like</p>
<pre><code>"W&auml;hlen"
</code></pre>
<p>i.e. replacing each ISO 8859-1 character/symbol by its HTML ent... | <pre><code>echo htmlentities('Wählen', 0, 'utf-8');
</code></pre>
<p>^ PHP</p>
<p><strong>PS</strong>: <em>Learn the arguments based on where you need the encoded string to appear</em>:</p>
<pre><code>// does not encode quotes
echo htmlentities('"Wählen"', 0, 'utf-8');
// encodes quotes
echo htmlentities('"Wählen"',... | php|python|encoding|html-entities | 3 |
2,843 | 65,036,565 | How to create a list of elements where the start index is given in one list until I encounter a specific element in the larger list? | <p>I have 2 lists as follows:</p>
<pre><code>main_list={"A","B","End of Block", "C","D","E","F","End of Block",.....,"End of Block","Q", "R",...}
index_list = {1,4,9,10,...}
</code></pre>
<p>I need to create a ... | <p>It could also be done using list comprehension:</p>
<pre><code>main_list=["A","B","End of Block", "C","D","E","F","End of Block"]
index_list = [1,4]
output_list = [ "".join(main_list[i:main_list.index("End of Block",... | python|list | 1 |
2,844 | 64,669,149 | Pandas Groupby -- efficient selection/filtering of groups based on multiple conditions? | <p>I am trying to</p>
<ul>
<li>filter dataframe groups in Pandas, based on multiple (<code>any</code>) conditions.</li>
</ul>
<p>but I cannot seem to get to a fast Pandas 'native' one-liner.</p>
<p>Here I generate an example dataframe of <code>2*n*n</code> rows and 4 columns:</p>
<pre><code>import itertools
import rand... | <p>This is similar to your second approach, but chained together:</p>
<pre><code>mask = (df[['C','D']].gt(50) # in the case you have different thresholds for `C`, `D` [50, 60]
.all(axis=1) # check for both True on the rows
.groupby([df['A'],df['B']]) # normal groupby
.t... | pandas|group-by|data-science | 3 |
2,845 | 65,054,894 | Django serve file in memory instead of saving on disk | <p>I want to render plot (<code>matplotlib</code>) in one place of code and then in <code>ViewSet</code> serve to it user without saving on disk. I tried to use <code>io</code> library to keep file in memory, but it seems that always something is wrong.</p>
<p>My code where I save plot on disk:</p>
<pre><code>def some_... | <p>Make sure that you pass matplotlib a <a href="https://docs.python.org/3/library/io.html#io.BytesIO" rel="nofollow noreferrer"><code>BytesIO</code></a> object, and not a <code>StringIO</code>. Then get the bytes using <code>getvalue()</code>, and pass them to <code>HttpResponse</code>. If that's what you've already t... | python|django|matplotlib|django-rest-framework | 2 |
2,846 | 65,370,450 | calculate the content of a variable | <p>I'm learning python, and I have encountered a problem.</p>
<pre><code>for i in input:
operator = i.split()[0]
number1 = i.split()[1]
number2 = i.split()[2]
equation = (number1 + ' ' + operator + ' ' + number2)
</code></pre>
<p>This code is supposed to calculate a randomly generated input, for exampl... | <p>You don't need a loop:</p>
<pre><code>a = input()
operator = a.split()[0]
number1 = a.split()[1]
number2 = a.split()[2]
equation = (number1 + ' ' + operator + ' ' + number2)
print(equation)
</code></pre> | python|string|loops|variables|calculation | 0 |
2,847 | 61,649,442 | how to scrape all the pages on a real estate website using pyton? | <p>I need some assistance scraping multiple pages for a real estate website. I have written the code to scrape page 1 successfully and attempted to implement code to <strong>scrape</strong> all 25 pages of it but am now stuck. Any tips/help would be greatly appreciated.</p>
<pre><code>import requests
from bs4 import Be... | <p>You should increment the page number every time that it scrapes a page. Try this:</p>
<pre class="lang-py prettyprint-override"><code>import requests
from bs4 import BeautifulSoup
from csv import writer
base_url = 'https://www.rew.ca/properties/areas/kelowna-bc'
for i in range(1, 26):
url = '/page/' + str(i)
... | python | 0 |
2,848 | 60,364,871 | Django ckeditor upload image | <p>I'm trying to use ckeditor to upload an image. Looks like everything is set up by documentation, but still I'm getting an error while trying to upload an image. I think that there is a problem with static files. Looks like ckeditor doesn't know where to upload files, even though I've provided all needed parameters:<... | <p>Looks like there is a problem with 'static' folder location in my project. I've solved my problem adding </p>
<pre><code>CKEDITOR_STORAGE_BACKEND = 'django.core.files.storage.FileSystemStorage'
</code></pre>
<p>To my settings file. Not sure if it will work for you, but it definitely works for me since 'FileSystemS... | python|django|ckeditor|django-ckeditor | 1 |
2,849 | 71,411,855 | How to insert values form sqlite to excel without brackets and in specific column (Python)? | <p>I am new to Python. I want to know how to add values into an excel file. I did some research on google but I still can't find the way to make it.
This is what I have:</p>
<pre><code>wb = load_workbook('example.xlsx')
ws = wb.active
con = sqlite3.connect(database=r'database.db')
cur = con.cursor()
cur.execute("S... | <p><code>.fetchall</code> returns a list of tuples, and <code>str(row)</code> gives you the string representation of that list.</p>
<p>If you want each individual element of this list in its own cell you'll need to iterate over the list and modify the cell name in each iteration:</p>
<pre class="lang-py prettyprint-ove... | python|excel|sqlite | 1 |
2,850 | 63,355,488 | Python: Cannot put json format(dict) values into a list | <p>I tried to extract a set of date values from a json input. And when i finished the extraction of <code>F_Date</code> , it was correct.</p>
<pre><code>2020-05-20T00:00:00
2020-05-18T00:00:00
2020-05-15T00:00:00
2020-05-13T00:00:00
</code></pre>
<p>I set a list to contain the values, so I wanna use the index of list l... | <p>All you need to do is print F_Date instead of F_Date[0] which only prints the first Character as a String can be interpreted as a list of Characters and you are printing the index 0.</p>
<pre><code>print(F_Date)
</code></pre>
<p>If you are confused to what F_Date is, F_Date is your Date String as it is the value to ... | python|json|list|for-loop|if-statement | 0 |
2,851 | 63,706,286 | How do i add a cooldown or a ratelimit to this event? discord.py | <pre><code>@commands.Cog.listener()
async def on_message(self, message):
user_in = message.content.lower()
if "gn" in user_in.split(" ") or "good night" in user_in :
if message.author.bot: return
if not message.guild: return
await m... | <p><a href="https://stackoverflow.com/questions/62557843/discord-py-rewrite-how-to-get-cooldowns-working-with-on-message-event">Discord.py (Rewrite) How to get cooldowns working with on_message event?</a></p>
<p>I would recommend you to check out this post.</p> | python|discord|discord.py | 3 |
2,852 | 56,670,184 | Why does MATLAB produce an error when calling a python script with "from tensorflow import keras"? | <p>I have the following python script (test_from_import.py)</p>
<pre><code>from tensorflow import keras
#import tensorflow.keras
from tensorflow.keras import backend as K
</code></pre>
<p>that I call from MATLAB (R2018a) with the following code:</p>
<pre class="lang-matlab prettyprint-override"><code>testDir = '....... | <p>According to <a href="https://github.com/h5py/h5py/issues/1151" rel="nofollow noreferrer">this issue</a> in the <code>h5py</code> repository, the problem is some version incompatibility. The solution that worked for several people was downgrading to <code>h5py</code> v2.8.0.</p>
<p>Installing a specific version usi... | python|matlab|tensorflow|keras|tf.keras | 1 |
2,853 | 60,800,577 | How to fix a Traceback problem in Dataframe Python on Ubuntu | <p>I tried to use DataFrame in Python. Commands are:</p>
<pre><code>import pandas as pd
from numpy.random import uniform
df = pd.DataFrame(uniform(0,1,(3,4)),
index = 'A B C D'.split(),
columns='E F G H'.split())
</code></pre>
<p>But unfortunately I get the following error. Does an... | <p>You are creating an 3x4 matrix but providing 4 row indices. Provide only 3 rows to your <code>index</code>.</p>
<pre><code>import pandas as pd
from numpy.random import uniform
df = pd.DataFrame(uniform(0,1,(3,4)),
index = 'A B C'.split(),
columns='E F G H'.split())
</code></pre> | python|dataframe | 1 |
2,854 | 66,170,394 | beautifulsoup: Dropping text inside tags | <p>I am trying to extract strings from a html file using beautifulsoup. A query replies with label tags inside them, how can I get rid of those tags.</p>
<pre><code>from bs4 import BeautifulSoup
import requests
with open('/Desktop/filename.html') as html_file:
soup = BeautifulSoup(html_file, 'lxml')
string = soup... | <p>You can try with decompose, example, before the print use this:</p>
<pre><code>for label_element in string.find_all("label"):
label_element.decompose()
</code></pre> | python|html|beautifulsoup | 1 |
2,855 | 66,206,118 | TypeError: Expected tensorflow.python.framework.tensor_spec.TensorSpec, found numpy.ndarray | <p>I am getting the following error when i would like to migrate from TFF 0.12.0 to TFF 0.18.0,
Knowing that I have an image dataset, Here is my sample_batch</p>
<pre><code>images, labels = next(img_gen.flow_from_directory(path0,target_size=(224, 224), batch_size=2))
sample_batch = (images,labels)
...
def model_fn():
... | <p>In version <a href="https://github.com/tensorflow/federated/releases/tag/v0.13.0" rel="nofollow noreferrer"><code>0.13.0</code></a> the <code>sample_batch</code> parameter was deprecated. The <code>input_spec</code> parameter must be a <a href="https://www.tensorflow.org/federated/api_docs/python/tff/Type" rel="nofo... | tensorflow-federated | 1 |
2,856 | 69,244,072 | Jpype: ModuleNotFoundError when import classes in jar | <h2>Problem</h2>
<p>I got an <code>ModuleNotFoundError: No module named 'spoon'</code> when I set the <code>-Djava.class.path</code> as a directory <code>"jars/*"</code>.</p>
<p>Project structure</p>
<pre><code>utils
├── __init__.py
├── jars
│ └── spoon-core-9.2.0-beta-4.jar
└── parse_utils.py
</code></pre>... | <p>See <a href="https://github.com/jpype-project/jpype/issues/1002" rel="nofollow noreferrer">this link</a>:</p>
<blockquote>
<p>I would start with checking to see if the jar was picked up in the path.</p>
<pre><code>import jpype
jpype.startJVM(classpath="jars/*")
print(jpype.java.lang.System.getProperty(&quo... | python|jpype | 1 |
2,857 | 68,245,054 | how to use python to open a browser page and make it on top | <p>I need to use python to open a selenium browser page and make it shown as the top page. My command is:</p>
<p><code>driver.execute_script('''window.open("https://www.abcxyzle.com", "_blank");''')</code></p>
<p>The problem is the url portion of the command needs to be in a variable becuase my code... | <p><strong>try this :</strong></p>
<pre><code>testurl = "https://www.google.com"
driver.execute_script(f'''window.open("{testurl}", "_blank");''')
driver.switch_to.window(driver.window_handles[1])
</code></pre> | python|selenium | 1 |
2,858 | 59,380,566 | Adafruit MM8451 & Raspberry PI SPI Error 121 with Buster | <p>Working with a Raspberry PI and interfacing with an Adafruit MMA8451 Accelerometer board. I am trying a fresh installation of Buster after I had all this working on Stretch. I have installed all the latest libraries and done all the latest updates. I am able to have the MMA8451 show up using </p>
<pre><code>sudo i2... | <p>I think I found a fix. Unsure if this is caused by Buster or something else.</p>
<p>I went into /boot/config.txt and added in</p>
<pre><code>core_freq=500
core_freq_min=500
dtparm=i2c_arm=on,i2c_arm_baudrate=10000
</code></pre>
<p>That seems to get it working every time instead of having communication errors.</p... | python|raspberry-pi|raspberry-pi3|adafruit|debian-buster | 0 |
2,859 | 49,210,649 | Unable to use "Filter" in AWS Rest API request | <p>I am trying to use "Filter" in request parameters while sending REST API request to AWS. Surprisingly, below request parameter just works:</p>
<p>request_parameters = 'Action=DescribeAvailabilityZones&Version=2016-11-15'</p>
<p>However, as soon as I change it to:
request_parameters = 'Action=DescribeAvailabili... | <p>figured out the solution. The parameters list expects the filter to be passed in a key/value fashion. Below is the amendment which I found to be working:</p>
<p>request_parameters = 'Action=DescribeAvailabilityZones&<strong>Filter.1.Name=state</strong>&<strong>Filter.1.Value=available</strong>&Version=2... | python|rest|api|amazon-web-services | 1 |
2,860 | 70,753,233 | How to find shared values among pandas dataframe rows and number of occurrences | <p>i'm dealing with a pretty large db, in particular with these two columns:</p>
<p><a href="https://i.stack.imgur.com/HK6Z5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HK6Z5.png" alt="Db columns" /></a></p>
<p>First column features an id and second column values consists in lists of uids associa... | <p>True, <code>df.apply()</code> can become extremely slow when it comes to large datasets. There is a library called Bodo which uses high-performance computing under the hood to speed up Pandas code. It works very well with user-defined functions. Here is an example: <a href="https://medium.com/bodo-ai/making-pandas-... | python-3.x|pandas|dataframe | 1 |
2,861 | 60,288,212 | Python RegEx - Single vs multiple line test | <p>re.finditer() will pick the (.com) is the below text is in multiline string. The same function does not work if the text is in a single string (var ss). Can anyone please help me to understand?</p>
<pre><code>s = """ example (.com)
w3resource github (.com)
stackoverflow (.com) """
# ss = """ example (.co... | <p>The dot ( . ) will match any character except a newline, so in first case your greedy + stops when it finds the newline, on the later case, the greedy + works till the last parenthesis and hence perform only a single match.So it means your regex should be modified, try replacing it with below, so what I wrote it is ... | python|regex | 0 |
2,862 | 67,773,024 | Create and append single column of 1’s, 0’s, and -1’s in csv file based on assessment of several other pre-existing columns | <pre><code>signal_1 signal_2 signal_3 signal_4
0 0 0 0
1 1 0 -1
1 1 0 -1
1 0 -1 -1
0 0 -1 -1
</code></pre>
<p>I have the signal data above in a csv file that I can pull into numpy arrays repr... | <p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>numpy.select()</code></a> as follows:</p>
<pre><code>import numpy as np
df['result'] = np.select([(df['signal_1'] == 1) & (df['signal_2'] == 1), (df['signal_3'] == -1) & (df['signal_4'] ... | python|pandas|numpy|csv | 3 |
2,863 | 67,822,206 | how to access resource files after pip install in virtual env in python? | <p>Let says that I have this project structure:</p>
<pre><code>src
|my_package
__init__.py
|utils
__init__.py
util.py
|resources
__init__.py
my_resource.yml
</code></pre>
<p>In util.py, I have this code which need the resource file to work:</p>
<pre><code>import yaml
import import... | <p>your <code>data_files</code> is both mis-specified and not the setting you want (it's intended for non-package data). the keys in <code>data_files</code> are placed from the root of the prefix (so say you install your package into <code>./venv</code> instead of your data ending at <code>./venv/lib/python#.#/site-pa... | python|resources|virtualenv|python-wheel | 2 |
2,864 | 65,518,434 | Why are models having there parent class names in admin Django | <p>I have created models like this</p>
<pre><code>class User(AbstractUser):
login_count = models.PositiveIntegerField(default=0)
class Supplier(User):
company_name= models.CharField(max_length=30)
company_domain=models.CharField(max_length=30)
class Worker(User):
ACCOUNT_TYPE = (
('1', 'A... | <p>Because <code>AbstractUser</code> is an abstract model it's <code>Meta</code> class is inherited by all subclasses, <a href="https://docs.djangoproject.com/en/3.1/topics/db/models/#meta-inheritance" rel="nofollow noreferrer">docs</a>.</p>
<p>You need to provide your own <code>Meta</code> class for each model and pas... | python|django|django-admin|django-users|django-admin-actions | 3 |
2,865 | 50,800,749 | .datalog format using Z3 | <p>I'm trying to use the Z3 extension: muZ with fixed-point constraints following this tutorial: <a href="https://rise4fun.com/Z3/tutorial/fixedpoints" rel="nofollow noreferrer">https://rise4fun.com/Z3/tutorial/fixedpoints</a>.</p>
<p><strong>As marked in this tutorial, three different text-based input formats are acc... | <p>If you put that program text in a file (say <code>a.datalog</code>), you can directly call z3 on it. (Note that the extension has to be <code>datalog</code>).</p>
<p>When I do that, I get:</p>
<pre><code>$ z3 a.datalog
Tuples in Gt:
(x=a(0),y=b(1))
(x=b(1),y=c(2))
(x=c(2),y=d(3))
(x... | python|z3|z3py|datalog | 1 |
2,866 | 44,964,370 | How to aggregate some data in pandas DataFrame | <p>I have dataframe like this: </p>
<pre><code>df = pd.DataFrame({'id': [115,120,200], 'category': ['a','a', 'b'], 'clust': [1, 2, 3]})
</code></pre>
<p>I want to aggregate and count the amount of id of every category, which is in particular clust. For instance, result can also data frame where index row is clust and... | <p>IIUC, let's use <code>groupby</code> and <code>unstack</code>:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'id': [115,120,200], 'category': ['a', 'a', 'b'], 'clust': [1, 2, 3]})
df
</code></pre>
<p>Input Dataframe:</p>
<pre><code> category clust id
0 a 1 115
1 a 2 120
2 ... | python|pandas|dataframe | 0 |
2,867 | 45,066,228 | Open Tkniter Toplevel only if it doesn't already exist | <p>I am trying to create a python app with a Tkinter UI and am currently having the following issue. I am trying to set up the UI such that a log is being kept in the background, and when the user presses a button a <code>Toplevel</code> window appears. The window displays the log, and appends updates to it in real t... | <p>You just need to initialize <code>self.textWindow</code> in addition to checking whether it exists:</p>
<pre><code>class guiapp(tk.Frame):
...
self.textWindow = None
...
def TextWindow(self):
if self.textWindow is None or not self.textWindow.winfo_exists():
self.textWindow = tk.... | python|user-interface|tkinter | 3 |
2,868 | 56,328,238 | Python Dictionary to CSV Issue | <p>I put together a python script to clean CSV files. The reformatting works, but the data rows the writer writes to the new CSV file are wrong. I am constructing a dictionary of all rows of data before writing using writer.writerows(). When I check the dictionary using print statements, the correct data is appendin... | <p>It looks like you are appending the same dictionary to the list over and over.</p>
<p>In general, when appending a nuber of separate dictionaries to a list, I would use <code>mylist.append(mydict.copy())</code>, otherwise later on when you assign new values within a dictionary of the same name you are really just u... | python|json|csv|dictionary | 1 |
2,869 | 44,433,591 | This is the error that I am getting while executing from sklearn import preprocessing, cross_validation, svm | <pre><code>Traceback (most recent call last):
File "C:/Python27/12.py", line 4, in <module>
from sklearn import preprocessing, cross_validation, svm
File "C:\Python27\lib\site-packages\sklearn\__init__.py", line 57, in <module>
from .base import clone
File "C:\Python27\lib\site-packages\sklear... | <p>Install this package using:</p>
<pre><code>easy_install scipy
</code></pre>
<p>or</p>
<pre><code>sudo apt-get install python-scipy
</code></pre>
<p>or</p>
<pre><code>pip install scipy
</code></pre>
<p>or</p>
<pre><code>conda install scikit-learn
</code></pre>
<p>if you are using windows refer: </p>
<p><a hr... | python | 0 |
2,870 | 35,855,355 | run python in terminal using sublime | <p>I use Linux Mint 17.3 and recently installed Sublime Text 3 <em>(unregistered version)</em>. In order to run python scripts in terminal <em>(the external terminal of the OS, not the internal one of the IDE)</em> I fount somewhere this:</p>
<p>Tools -> Build system -> New build system</p>
<p>type this:</p>
<pre><c... | <p>could you go to Tools -> Build System -> new build system </p>
<p>paste the following in the window that open </p>
<pre><code>{
"path": "/usr/local/bin",
"cmd": ["python3", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python"
}
</code></pre>
<p>then save i... | python|linux|terminal|sublimetext3 | 2 |
2,871 | 36,164,653 | In Pandas, how to send the output from groupby transform to the original dataframe? | <p>Consider the following example</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
... | <p>if expressed in two lines, the logic becomes cleaner to write & read</p>
<pre><code>df['d_pos_sum'] = df.groupby(['A', 'B']).transform(lambda x: x[x>0].sum())
df['d_neg_sum'] = df.groupby(['A', 'B']).transform(lambda x: x[x<0].sum())
</code></pre> | python|pandas | 1 |
2,872 | 53,711,920 | How to draw samples from two variables from population | <p>I have dataset that female students have than male. I need analyze which gender perform better in their test. Because their number not equal, I need to draw sample which equal.</p>
<pre><code>female=df.sample (df.query ("gender=='female'")=200)
male=df.sample (df.query ("gender=='male'")=200)
</code></pre>
<p>Is t... | <p>Not quite. Among other things, you have a syntax error. Assuming you want 200 samples from each population, try this:</p>
<pre><code>female = df[df['gender']=='female'].sample(200)
male = df[df['gender']== 'male'].sample(200)
</code></pre> | python|dataframe | 0 |
2,873 | 40,248,939 | Pandas DataFrame index - month and day only | <p>I'd like to have a <code>DataFrame</code> with a <code>DatetimeIndex</code>, but I only want the months and days; not years. I'd like it to look like the following:</p>
<pre><code>(index) (values)
01-01 56.2
01-02 59.6
...
01-31 62.3
02-01 61.6
...
12-31 44.0
</code></pre>
<p>I've tried creating a... | <p>you can do it this way:</p>
<pre><code>In [78]: df = pd.DataFrame({'val':np.random.rand(10)}, index=pd.date_range('2000-01-01', freq='10D', periods=10))
In [79]: df
Out[79]:
val
2000-01-01 0.422023
2000-01-11 0.215800
2000-01-21 0.186017
2000-01-31 0.804285
2000-02-10 0.014004
2000-02-20 0.2... | python|pandas | 4 |
2,874 | 39,902,629 | Right way to set variables at python class | <p>Which is the right way to work with variables inside a class?</p>
<p>1- setting them as class attributes where we get them and access them from class itself:</p>
<pre><code>class NeuralNetwork(object):
def __init__(self, topology):
self.topology = topology
self.buildLayers()
def buildLayers(self):
... | <p>In general the first way is the "really object oriented" way, and much preferred over the second and the third.</p>
<p>If you want your buildLayers function to be able to change the topology occasionally, give it a param. topology with default value = None.</p>
<p>As long as you don't pass that param. at calling b... | python|class|variables|standards | 2 |
2,875 | 52,532,420 | How to create table in hbase using pyspark? | <p>I wants to create new hbase table if not exist in namespace/hbase from pyspark code for storing data, can someone help me do this task?</p> | <p>I think the easiest way is that using happybase. You can find document here
<a href="https://happybase.readthedocs.io/en/latest/index.html" rel="nofollow noreferrer">happybase</a>. It is an example below</p>
<pre><code>hbase(main):001:0> list
TABLE ... | python-2.7|pyspark|hbase | 0 |
2,876 | 52,580,023 | How to get the best estimator & parameters out from pipelined gridsearch and cross_val_score? | <p>I'd like to find the best parameters from SVC, using nested CV approach:</p>
<pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
X, y = load_breast_cancer(return_X_y=True)
from sklearn.mo... | <p>Well, you don't have to use <code>cross_val_score</code>, you can get all information and meta results during the cross-validation and after finding best estimator.</p>
<p>Please consider this example:</p>
<pre><code>from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.model_selection... | python|machine-learning|scikit-learn | 5 |
2,877 | 38,807,895 | Seaborn multiple barplots | <p>I have a pandas dataframe that looks like this:</p>
<pre><code> class men woman children
0 first 0.91468 0.667971 0.660562
1 second 0.30012 0.329380 0.882608
2 third 0.11899 0.189747 0.121259
</code></pre>
<p>How would I create a plot using seaborn that looks like this? D... | <p>Yes you need to reshape the DataFrame:</p>
<pre><code>df = pd.melt(df, id_vars="class", var_name="sex", value_name="survival rate")
df
Out:
class sex survival rate
0 first men 0.914680
1 second men 0.300120
2 third men 0.118990
3 first woman 0.667971
... | python|pandas|matplotlib|seaborn | 76 |
2,878 | 27,999,249 | How to sort list of tuples by several keys | <p>I am doing an exercise on Python and lists with one problem:
I have a list of tuples sorted by second key:</p>
<pre><code>[('f', 3), ('a', 3), ('d', 3), ('b', 2), ('c', 2)]
</code></pre>
<p>And I need sort it: Second value by number and first value by alphabetical order. And it must look like:</p>
<pre><code>[('a... | <p>The <code>sort()</code> method is stable. Call it twice, first for the secondary key (alphabetically), then for the primary key (the number):</p>
<pre><code>>>> lst = [('f', 3), ('a', 3), ('d', 3), ('b', 2), ('c', 2)]
>>> lst.sort()
>>> lst.sort(key=lambda kv: kv[1], reverse=True)
>>... | python|list|sorting | 0 |
2,879 | 46,648,387 | Converting JSONL file to CSV - "JSONDecodeError: Extra data" | <p>I am using tweepy's <code>Streamlistener</code> to collect Twitter Data and the code I am using generates a JSONL file with a bunch of meta data.
Now I would like to convert the file into a CSV for which I found a code for just that. Unfortunately I have run into the Error reading: </p>
<pre><code>raise JSONDecode... | <p>If the data file consists of multiple lines, each of which is a single json object, you can use a generator to decode the lines one at a time.</p>
<pre><code>def extract_json(fileobj):
# Using "with" ensures that fileobj is closed when we finish reading it.
with fileobj:
for line in fileobj:
... | python|json|csv|tweepy | 1 |
2,880 | 64,453,617 | Pandas- masking rows/columns between two dataframes where indexes are not shared | <p><strong>The Problem</strong></p>
<p>I have two datasets that describe, let's say, the temperature at certain depths and at certain latitudes for a sea. The datasets are from two different models and therefore have differing resolution, with model 1 have a higher resolution for latitude and both models having differe... | <p><code>depthxsect</code> returns an <code>np.array</code> of the indices that you need. So, you can skip creating the boolean array <code>depthmask</code> and just pass the np.array to your datframe using <code>.loc</code>. You should use <code>.mask</code> if you are trying to <em>keep</em> all of the rows but just ... | python|pandas|dataframe|indexing|data-masking | 1 |
2,881 | 64,407,618 | Correct use of multiple windows for MVC pattern with Tkinter | <p>I'm trying to make a Python program with a GUI in which various animations will be displayed on a canvas. I decided to use a MVC pattern and Tkinter. When launching my program, a window should pop and you have to choose the dimensions of the canvas before displaying the GUI.</p>
<p><a href="https://i.stack.imgur.com... | <p>The way I found to solve this problem was to create a window <code>Tk()</code> and just unpacking and packing the different frames. I guess it is not the best way to do it but it worked !</p> | python|user-interface|tkinter|canvas|model-view-controller | 0 |
2,882 | 70,555,866 | Flask is not found despite it should have been installed | <p>I am a beginner in Flask and I'm trying to code a web email application with flask and python. But right after trying to import Flask with the command <code>from flask import flask</code> it gives me the following Error:</p>
<pre><code>> *Traceback (most recent call last): File "C:\Users\fabia\OneDrive\Des... | <p><code>pip install flask</code> command in <code>cmd</code> install flask in global environment.</p>
<p>But <code>Pycharm</code> has a virtual environment, so you need to install <code>flask</code> in virutal environment of <code>Pycharm</code>.</p>
<p>Open <code>Pycharm</code> and in it's <code>terminal</code> type ... | python|pip | 1 |
2,883 | 73,065,332 | python function parameter control | <pre><code>def getBooks(self,name):
query = "SELECT * FROM books"
self.cursor.execute(query)
books = self.cursor.fetchall()
return books
</code></pre>
<p>I have a function called "getBooks", and this function is actually a combination of 2 functions. one function must... | <p>You can specify a default parameter of name to be None, and then treat the variable according to its type:</p>
<pre><code>def getBooks(self,name=None):
if name is None:
...
else:
...
</code></pre> | python|sql|sqlite | 2 |
2,884 | 49,975,192 | Look for string in a range of lines and pick all the string after a particular and append it another file | <p>I have <code>file 1</code> contents as </p>
<pre><code>wire x;
wire y;
input a;
input b;
input c;
reg m;
reg n;
</code></pre>
<p>I have to put signals <code>a</code>, <code>b</code>, <code>c</code> only in another file <code>file 2</code> in the following manner</p>
<pre><code>assign inst.a=;
assign inst.b=;
assi... | <p>This one-line Perl program</p>
<pre><code>perl -lne 'print "assign inst.$1=;" if /^input\h+(\w+);/' 'file 1'
</code></pre> | python|perl | 1 |
2,885 | 64,675,440 | How to use variable as value in xsl:apply-templates? | <p>I'm trying to extract some data from xml file and pass it to many html files based on specific nodes.
My <code>source.xml</code>:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
<products>
<product>
<id>1</id>
<feature>Product descrip... | <p>Your attempt:</p>
<pre><code><xsl:template match="/products">
<xsl:apply-templates select="product[id=$item_num]" />
</xsl:template>
<xsl:template match="id" >
<p><xsl:value-of select="."/></p>
<xsl:value-of select=&quo... | python|xml|xslt | 0 |
2,886 | 64,945,532 | PANDAS reading dataframe from file properly | <p>my file(text file) looks like:</p>
<pre><code> -1 1 2.99988E-02-4.93580E-17 4.28928E-17-2.01725E-16 4.57184E-18 1.54030E-16
-1 2 2.99988E-02-4.93581E-17-3.85396E-17-2.02655E-16-4.41397E-17-2.23963E-16
-1 3 2.99988E-02 2.47173E-17 4.28930E-17 1.60350E-16 5.28503E-17 1.53007E-16
...
</code><... | <p>This is not a delimited file, but a fixed widths one. It used to be a common format in the 80' when we used the Fortran IV language...</p>
<p>But it is still supported by pandas with the <code>read_fwf</code> function:</p>
<pre><code>df = pd.read_fwf(file_dir, header=None, widths=(3,10) + 6 * (12,))
</code></pre>
<p... | python|pandas | 0 |
2,887 | 65,074,479 | Converting all text files with multiple encodings in a directory into a utf-8 encoded text files | <p>I am new starter in Python and, in general, in coding. So any help is greatly appreciated.</p>
<p>I have more than 3000 text files in a single directory with multiple encodings. And I need to convert them into a single encoding (e.g. utf8) for further NLP work. When I checked the type of these files using shell, I i... | <p>I met the same problem like you.
I used two steps to solve this problem.</p>
<p>code is below:</p>
<pre><code>import os, sys, codecs
import chardet
</code></pre>
<p>First, using chardet package to identify the coding of text.</p>
<pre><code>for text in os.listdir(path):
txtPATH = os.path.join(path, text)
txt... | python|encoding|utf-8 | 3 |
2,888 | 65,322,797 | Chromedriver test work locally and on CI CD env python | <p>What I have: CURRENT_BROWSER=chrome in Win Environments</p>
<pre><code>def before_scenario(context, scenario):
use_fixture(browser, context)
def after_scenario(context, scenario):
context.cache.clear()
context.driver.quit()
@fixture
def browser(context):
browser_type = os.getenv('CURRENT_BROWSER'... | <p>If you are using a <a href="https://docs.microsoft.com/en-us/azure/devops/pipelines/agents/hosted?view=azure-devops&tabs=yaml#use-a-microsoft-hosted-agent" rel="nofollow noreferrer">Microsoft-hosted agent</a>: <code>windows-latest</code>, <code>windows-2019</code> or <code>vs2017-win2016</code>, the Chrome Drive... | python|azure-devops | 0 |
2,889 | 65,369,649 | Group by and Aggregate with nested Field | <p>I want to group by with nested serializer field and compute some aggregate function on other fields.</p>
<p>My Models Classes:</p>
<pre><code>class Country(models.Model):
code = models.CharField(max_length=5, unique=True)
name = models.CharField(max_length=50)
class Trade(models.Model):
country = models... | <p>I have found the solution. Actually to_representation in serializer class got only the id of country not its object so i override to_representation as:</p>
<pre><code>class TradeAggregateSerializers(serializers.ModelSerializer):
...
...
def to_representation(self, instance):
#instance['country'] = some i... | python|django|django-rest-framework | 0 |
2,890 | 5,561,111 | Including many-to-many from another model in field in django admin interface | <p>Greetings,
I'm sure there is a simple solution to what I'm trying to do but unfortunately I wasn't able to find it in the documentation.</p>
<p>I have the following model (simplified version shown):</p>
<p>models.py:</p>
<pre><code>class Student(models.Model):
student_id = models.IntegerField(primary_key=True, ... | <p>You can use the <a href="http://docs.djangoproject.com/en/1.3/ref/contrib/admin/#inlinemodeladmin-objects" rel="nofollow"><strong><code>inlines</code></strong></a> in your related model, or <a href="http://www.eivanov.com/2009/01/manytomany-relations-in-django.html" rel="nofollow"><strong><code>this</code></strong><... | python|django|foreign-keys|many-to-many | 1 |
2,891 | 61,813,589 | Python script to copy file and directory from one remote server to another remote server | <p>I am running a python script - ssh.py on my local machine to transfer file and directory from one remote server (ip = 35.189.168.20) to another remote server (ip = 10.243.96.94)</p>
<p>This is how my code looks: </p>
<pre><code>HOST = "35.189.168.207"
USER = "sovith"
PASS = "xxx"
destHost = "10.243.96.94"
destUser... | <p>That's not possible. Not the way you do it. The fact that you open a connection to one remote server, does not make the following code magically work, as if it was executed on that server. It still runs on the <em>local machine</em>. So the code is trying to upload <em>local files</em> (which do not exist).</p>
<hr... | python|ssh|sftp|paramiko|pysftp | 0 |
2,892 | 67,547,109 | Django(djongo) can't connect to MondoDB Atlas after Heroku deployment | <p>I managed to get it working locally (different cluster, separate settings.py), but not after when deployed to Heroku.</p>
<p><strong>Heroku</strong> - automatically adds DATABASE_URL config var with a postgresql, and I cannot remove/edit it.</p>
<p><strong>MongoDB Atlas</strong> - I've set the MongoDB Atlas cluster ... | <p>I've been having the same issue. Everything works fine locally. The problem is when deploying on Heroku. I have added <code>'authMechanism': 'SCRAM-SHA-1'</code> and I have also configured MongoDB as my database by adding a <code>MONGODB_URI config var</code>. Heroku still autoconfigures <code>DATABASE_URL config va... | python|django|mongodb|heroku|djongo | 0 |
2,893 | 71,148,569 | Remove a row based on two empty columns in python pandas | <p>I want to be able to remove rows that are empty in column NymexPlus and NymexMinus
right now the code I have is</p>
<pre><code>df.dropna(subset=['NymexPlus'], inplace=True)
</code></pre>
<p>The thing about this code is that it will also delete rows in the column NymexMinus which I don't want to happen.
Is there an I... | <p>Use a list as <code>subset</code> parameter and <code>how='all'</code>:</p>
<pre><code>df.dropna(subset=['NymexPlus', 'NymexMinus'], how='all', inplace=True)
</code></pre> | python|pandas | 2 |
2,894 | 71,209,111 | Why is it a TypeError to use an arithmetic expression in %-style print formatting? | <p>I tried to input a float number and output a simple result using two methods:</p>
<pre><code>t = float(input())
print('{:.2f}'.format(1.0 - 0.95 ** t))
print('%.2f' % 1.0 - 0.95 ** t)
</code></pre>
<p>The first method worked but a TypeError occurred in the second one:</p>
<blockquote>
<p>unsupported operand type(s) ... | <p>On this line: <code>print('%.2f' % 1.0 - 0.95 ** t)</code></p>
<p>Python is trying to do <code>'%.2f' % 1.0</code> first, then subtracting <code>0.95 ** t</code> from the result. That's a problem because the first term is a string and the second one is a float.</p>
<p>Use parentheses to control the order of operatio... | python|python-3.x|string-formatting | 6 |
2,895 | 64,559,186 | How can I save the random output to use it in another function in python | <p>I am new to python3 I am trying very hard to add the output of the function, is there any way that I can save an output of an random integer
so that i can altogether add it please help me.</p>
<pre><code>def dice():
import random
rollball = int(random.uniform(1, 6))
return (rollball)
def dice2():
im... | <p>Use a variable or set a global variable for it</p>
<pre><code>import random
def dice():
rollball = int(random.uniform(1, 6))
return (rollball)
def dice2():
rollball = int(random.uniform(1, 6))
return (rollball)
roll1 = dice()
print(roll1)
input("you have 10 chances left")
roll2 = dice2()
... | python|python-3.x|random | 0 |
2,896 | 63,332,048 | trying to import png images to torchvision | <p>I am attempting to import images for use with torch and torchvision. But I am receiving this error:</p>
<pre><code>TypeError: Caught TypeError in DataLoader worker process 0.
Original Traceback (most recent call last):
File "c:\python38\lib\site-packages\torch\utils\data\_utils\worker.py", line 178, in _... | <p>Your <code>transform</code> variable is unused, it should be passed to the Dataset constructor:</p>
<pre><code>`dataset = torchvision.datasets.ImageFolder('datasets', transform=transform)`
</code></pre>
<p>Because of that, the <code>ToTensor</code> is never applied to your data, and thus they remain PIL images, not ... | python|pytorch | 1 |
2,897 | 63,707,292 | Selecting distinct random items from a list | <p>I am trying to make a rummy program in python 3.8, And a have a set list of all the possible cards, how do I pick 13 random <strong>distinct</strong> cards such that once those cards are chosen by the player, the other player cannot receive them?</p>
<p>For example</p>
<pre><code>card =['Ah','Ad','Ac','As','2h','2d'... | <p>Use the <a href="https://docs.python.org/3/library/random.html#random.sample" rel="nofollow noreferrer"><code>random.sample</code></a> which selects unique values:</p>
<pre><code>from random import sample
card = ['Ah','Ad','Ac','As','2h','2d','2c','2s','3h','3d','3c','3s','4h','4d','4c','4s','5h','5d','5c','5s','6h... | python | 3 |
2,898 | 56,580,115 | Retrieve data from django-rest to show in a form | <p>I have two classes linked with a ForeignKey. My first class is "Categories", with "ID" and "Name" properties. The second class is "Documents", with "ID", "Title" and "User" properties, the last one is linked with a category defined in the first class.</p>
<p>I'm developing the front-end based on Vue, so I want to k... | <p>You could make a separated request to get all the category before you create the form.</p>
<p>To do this, you need to create a CategorySerializer and a ListCategoryProvider</p>
<pre class="lang-py prettyprint-override"><code>class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Ca... | python|django|vuejs2|django-rest-framework | 0 |
2,899 | 18,150,786 | BeautifulSoup fails to parse long view state | <p>I try to use BeautifulSoup4 to parse the html retrieved from <a href="http://exporter.nih.gov/ExPORTER_Catalog.aspx?index=0" rel="nofollow">http://exporter.nih.gov/ExPORTER_Catalog.aspx?index=0</a> If I print out the resulting soup, it ends like this:</p>
<pre><code>kZXI9IjAi"/></form></body></htm... | <p>BeautifulSoup uses a <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser" rel="nofollow">pluggable HTML parser</a> to build the 'soup'; you need to try out different parsers, as each will treat a broken page differently.</p>
<p>I had no problems parsing that page with any of the parse... | python|html-parsing|beautifulsoup | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.