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 |
|---|---|---|---|---|---|---|
6,500 | 34,729,119 | Post string as FORMDATA in python | <p>I'm trying to replicate this cURL onliner:</p>
<pre><code>curl -i -XPOST 'http://httpbin.org/post?db=data' --data-binary 'files,host=server10,folder=max value=0.64 1434055562121200000'
</code></pre>
<p>to python with the help of python-requests.</p>
<p>I've tried:</p>
<pre><code>import requests
payload = {'files... | <p>Answering my self.</p>
<pre><code>import requests
url = 'http://10.10.10.10:8086/write?db=data'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
payload = "cpu,host=server01,region=us-west value=0.64 1434055562000000000\n"
r = requests.post(url, data=payload, headers=headers)
</code></pre>
<p>With t... | python|python-requests | 1 |
6,501 | 27,045,613 | Whoosh - Slop Operator Behaviour | <pre><code># Text: income tax expense resulting from the utilization of net operating loss carry forwards
</code></pre>
<p>Query Formats tried:</p>
<pre><code>q = QueryParser(u"content", ix.schema).parse(u"income utilization~3")
q = QueryParser(u"content", ix.schema).parse(u"'income utilization'~3")
</code></pre>
<p... | <p>You are confusing fuzzy operator with the slop operator:</p>
<ol>
<li><strong>Fuzzy Operator/edit distance</strong>: <code>word~</code> and <code>word~n</code> , those are for fuzzy terms means searching <code>word</code> with edit distance equal to <code>n</code>.</li>
<li><strong>Slop Operator</strong>: <code>"wo... | python|python-2.7|full-text-search|whoosh | 0 |
6,502 | 27,343,968 | Don’t understand lazy regex | <p>Say we have a string <code>1abcd1efg1hjk1lmn1</code> and want to find stuff between <code>1</code>-s. What we do is</p>
<pre><code>re.findall('1.*?1','1abcd1efg1hjk1lmn1')
</code></pre>
<p>and get two results</p>
<pre><code>['1abcd1', '1hjk1']
</code></pre>
<p>ok I get that. But if we do</p>
<pre><code>re.finda... | <p>Regex always tries to match the input string from left to right. Consider your <code>'1.*?1hj'</code> regex. <code>1</code> in your regex matches the first one and the following <code>.*?</code> matches all the characters upto the <code>1hj</code> sub-string non-greedily. So that you got <code>['1abcd1efg1hj']</co... | python|regex|lazy-evaluation | 5 |
6,503 | 12,190,238 | How to get the qualified name of the currently executing function? | <p>Python 3.3 introduced the <code>__qualname__</code> attribute for function objects and class objects.</p>
<p>It's easy to get the (unqualified) name and a code object for the currently executing function.</p>
<p>But how to get the qualified name for the currently executing function?</p> | <p>You can use <a href="https://github.com/alexmojaki/executing#getting-the-__qualname__-of-the-current-function" rel="nofollow noreferrer"><code>executing</code></a>:</p>
<pre><code>executing.Source.for_frame(frame).code_qualname(frame.f_code)
</code></pre> | python-3.x | 2 |
6,504 | 7,716,970 | Python API for C++ | <p>I have a code on C++, that creates file and writes data to it. Is it possible to use Python's functions to use Python's functionality in my C++ code? For example, I'd like to do this:</p>
<pre><code># Content of function.py
from PIL import Image
imgObject = Image.open('myfile.jpg') # Create Image object
pixArray = ... | <p>You may have a look to boost::python library which is really great for interfacing python and C++.</p> | c++|python|cpython|python-imaging-library | 1 |
6,505 | 7,973,823 | How do you shift all pages of a PDF document right by one inch? | <p>I want to shift all the pages of an existing pdf document right one inch so they can be three hole punched without hitting the content. The pdf documents will be already generated so changing the way they are generated is not possible. </p>
<p>It appears iText can do this from a <a href="https://stackoverflow.com... | <p>You can try pyPdf:</p>
<p><a href="http://pybrary.net/pyPdf/" rel="nofollow">http://pybrary.net/pyPdf/</a></p> | c++|python|linux|pdf|pypdf | 4 |
6,506 | 70,868,202 | Python: Add 1 every month in dataframe for all columns | <p>I have a dataframe:</p>
<pre><code> A B C
date
2021-01-01 1 nan 1
2021-01-23 nan 1 1
2021-02-03 1 nan 1
</code></pre>
<p>How can I add "1" to all columns at the beginning of each month? (Note I also want to do this quarterly as well) The dataframe should end up looking like this... | <p>IIUC the logic, you could do:</p>
<pre><code># ensure datetime
df.index = pd.to_datetime(df.index)
# fill missing starts of month
idx = pd.date_range(df.index.min(), df.index.max(), freq='MS')
df = df.reindex(df.index.union(idx))
# update starts of month
prev = df.shift(1).loc[idx] # get last data of previous mont... | python|pandas|dataframe|indexing | 2 |
6,507 | 33,564,939 | Recursive traversal of a dictionary in python (graph traversal) | <p>I have a dictionary with the following structure:</p>
<pre><code> KEY VALUES
v1 = {v2, v3}
v2 = {v1}
v3 = {v1, v5}
v4 = {v10}
v5 = {v3, v6}
</code></pre>
<p>The values of a key are actually links to other keys. By using the values I want to reach the other keys till the end. Some keys are not linked as you... | <p>A simple solution is to keep a "visited" set of already known nodes:</p>
<pre><code>def reach(travel_dict, x, visited=None):
if visited is None:
visited = set() # see note
visited.add(x)
for y in travel_dict.get(x, []):
if y not in visited:
yield y
for z in reach(... | python|dictionary|recursion|graph|multimap | 5 |
6,508 | 33,533,748 | Python - Getting calling module's path via traceback, problems? | <p>In python, I often find myself loading package resources through calls such as the following:</p>
<pre><code>import os
fp = open(os.path.join(os.path.dirname(os.path.realpath(__file__)),
"resource.json"), "r")
</code></pre>
<p>I've been considering using a library function such as the follow... | <p>To find the location of a module, function, or class, use the <code>inspect</code> module:</p>
<pre><code>import inspect
print(inspect.getsourcefile(some_module))
</code></pre>
<p>You can use this to find the location of the code units you are interested in. If you put this in a library, just wrap it in a function... | python|module|path|traceback | 0 |
6,509 | 46,807,010 | What are doc2vec training iterations? | <p>I am new to doc2vec. I was initially trying to understand doc2vec and mentioned below is my code that uses Gensim. As I want I get a trained model and document vectors for the two documents.</p>
<p>However, I would like to know the benefits of retraining the model in several epoches and how to do it in Gensim? Can ... | <p><code>Word2Vec</code> and related algorithms (like 'Paragraph Vectors' aka <code>Doc2Vec</code>) usually make multiple training passes over the text corpus. </p>
<p>Gensim's <code>Word2Vec</code>/<code>Doc2Vec</code> allows the number of passes to be specified by the <code>iter</code> parameter, if you're also supp... | python|deep-learning|word2vec|gensim|doc2vec | 7 |
6,510 | 46,644,140 | extract value from xml using python bs4 and lxml | <p>How am i able to extract the number of listeners <strong><code><listeners>10</listeners></code></strong> from the xml file below, my code is not working.</p>
<pre><code>import bs4
import urllib2
import lxml
bs4.BeautifulSoup(urllib2.urlopen('http://admin:mashytamam@192.168.0.31:8382/admin/').read(), 'l... | <p>try this:</p>
<pre><code>soup = BeautifulSoup(output.read(), 'xml')
for value in soup.find_all('listeners'):
print(value.get_text())
</code></pre> | python|beautifulsoup|lxml | 1 |
6,511 | 46,841,659 | Getting list of dates (excluding weekends) | <p>I am using python v3.6. I would like to get a list of dates that exclude weekends. </p>
<p>Here is what I have on hand;</p>
<pre><code>import pandas as pd
datelist = pd.bdate_range(pd.datetime.today(), periods=10).tolist()
</code></pre>
<p>What the above code does is to return a list of dates starting from today ... | <p>You could do</p>
<pre><code>pd.bdate_range('21/12/2017', periods=10).tolist()
</code></pre>
<p>Or, be more specific with <code>pd.to_datetime(.., format=)</code></p>
<pre><code>pd.bdate_range(pd.to_datetime('21/12/2017', format='%d/%m/%Y'), periods=10).tolist()
</code></pre> | python|python-3.x|pandas|date | 2 |
6,512 | 46,987,013 | tuples with unicode fix | <p>I have some tuples from an sql query that are a list of album names. However, they output in unicode giving it u' before each name, which I would like to remove. It prints out like this: </p>
<pre><code>((u'test',), (u'album test',), (u'test!',), (u'',), (u'album1',), (u'album2',), (u'album3',), (u'testalbum',))
</... | <p>Looks like you are calling <code>encode()</code> on the tuple. You really should be calling <code>encode()</code> on the (Unicode) string, which is the first element of the tuple.</p>
<hr>
<p>For example,</p>
<pre><code>>>> t = (u'hello', u'world')
>>> t.encode()
Traceback (most recent call last... | python|sql|unicode|tuples|ascii | 1 |
6,513 | 56,879,416 | Trying to import all columns from a csv with an object data type with pandas | <p>I'm trying to read a csv into a new dataframe with <code>pandas</code>. A number of the columns may only contain numeric values, but I still want to have them imported in as strings/objects, rather than having columns of float type.</p>
<p>I'm trying to write some python scripts for data conversion/migration. I'm n... | <p>It should stop converting data. </p>
<pre><code>pd.read_csv(..., dtype=str)
</code></pre>
<p>Doc: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer">read_csv</a> </p>
<pre><code>dtype: ... Use str or object together with suitable na_values settings... | python|pandas|csv|dataframe | 2 |
6,514 | 65,740,400 | Why am I getting an error while using MiniConda in VS Code? | <p>So, recently I started to learn Python for Data Sc. and installed miniconda. I planned to use VS Code for practice. I added python.exe path to VS Code. But when I started executing python programs in my default Git Bash terminal from VSCode, it gave the following error:</p>
<pre><code>$ conda activate base
CommandN... | <p>I activated the conda environment in the bash terminal with the following command:</p>
<ol>
<li>Use the command "<code>source deactivate</code>",</li>
<li>Then use the command "<code>conda deactivate</code>",</li>
<li>Now we can use the command "<code>conda activate base</code>" to acti... | python|visual-studio-code|anaconda|data-science|git-bash | 1 |
6,515 | 72,381,715 | Need help implementing a custom loss function in lightGBM (Zero-inflated Log Normal Loss) | <p>Im trying to implement this zero-inflated log normal loss function based on this paper in lightGBM (<a href="https://arxiv.org/pdf/1912.07753.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1912.07753.pdf</a>) (page 5). But, admittedly, I just don’t know how. I don’t understand how to get the gradient and hessi... | <p>This is the "translation", as you defined it, of the tensorflow implementation. Most of the work is just defining the functions yourself (i.e. softplus, crossentropy, etc.)</p>
<p>The mean absolute percentage error is used in the linked paper, not sure if that is the eval metric you want to use.</p>
<pre><... | python|machine-learning|loss-function|lightgbm|boosting | 1 |
6,516 | 72,437,785 | Dask to_csv generates inaccessible file | <p>I'm new to Dask. My motivation was to read large CSV files faster by parallelizing the process. After reading a file, I use <code>compute()</code> in order to merge the parts into a single pandas df. Then, when using pandas <code>to_csv</code>, the output CSV file isn't readable:</p>
<pre><code>$ file -I *.csv
my_bi... | <p>The original motivation is to read the data into memory faster. Using <code>dask</code> is a plausible solution, but if the intention is to bring the data into memory, then there are other alternatives available also. For example, <code>modin</code> follows <code>pandas</code> API and could deliver reduction proport... | python|pandas|csv|terminal|dask | 0 |
6,517 | 43,149,207 | Tensorflow variables' name changed after function calling | <p>I am trying to write my own batch normalization codes. Therefore, I test the codes below. In order to track the online average mean and variance, I pass them as parameters into the getsta() function. However, I find that the names of "avg_mean" and "avg_variance" changed. Although I could manually force change their... | <p>Here are the problems in your code that needs to be fixed:</p>
<p>1- At the following line you are replacing <code>avg_variance1</code> with an <code>operation</code> returned by <code>getsta</code>. You must not do that. When you have created the variable <code>avg_variance1</code> and pass it to <code>getsta</cod... | tensorflow|static-variables|variable-names | 0 |
6,518 | 37,124,586 | Iterating through a site's pages with python and Beautiful Soup | <p>Is there a way to iterate through a page's archives where the format is </p>
<p>'<a href="http://base_url/page=#" rel="nofollow">http://base_url/page=#</a>' - where # is 2-nth page number?</p>
<p>Ideally I'd like to deploy my scraper on every successive page after 'base_url'</p>
<p>is the a function or for loop ... | <p>You can just request each page like so:</p>
<pre><code># python 2
from urllib2 import urlopen
# python 3
from urllib.request import urlopen
base_url = "http://example.com/"
# request page 1 through 10
n = 10
for i in range(1, n+1):
if (i == 1):
# handle first page
response = urlopen(base_url)
... | python|loops|web-scraping|iteration | 2 |
6,519 | 48,787,398 | python: pass a double-single quote string to sql query | <p>I am working with a python application that uses textual SQL for postgresql queries.
I would like to use strings similar to this ''mykey,myval''` for my sql query. The code is wrapped into a function which should append the string to an hstore. Here is the code:</p>
<pre><code> def _myfunc_for_hstore(connection, in... | <p>Actually I removed entirely the</p>
<pre><code>value = "''{},{}''".format(key,val) # build the string to insert
</code></pre>
<p>and used directly key and value. This work fine:</p>
<pre><code>def _myfunc_for_hstore(connection, inst, key, val):
connection.execute('''SELECT master_modify_multiple_shards
... | python|postgresql | 0 |
6,520 | 48,666,832 | matplotlib figure parameters don't appears | <p>Here is my issue: I have an embedded matplotlib figure in a Qt5 application. When I press the button "edit axis, curve and image parameter", I select my concerned subplot, but only the tab "axis" options appears. it is missing tabs for "curve" and "image". </p>
<p>actual picture</p>
<p><img src="https://i.stack.im... | <p>class View2D(MapView):</p>
<pre><code>def show(self, som, what='codebook', which_dim='all', cmap=None,
col_sz=None, desnormalize=False):
(self.width, self.height, indtoshow, no_row_in_plot, no_col_in_plot,
axis_num) = self._calculate_figure_params(som, which_dim, col_sz)
self.prepare()
if... | python|matplotlib|pyqt5 | 0 |
6,521 | 20,199,936 | What is a way of accessing arbitrary groups in hdf5 file using pytables? | <p>Want to access/create an arbitrary group in an HDF5 db file using pytables.
The file has the following structure:</p>
<pre><code>db
|_ user_00 # Group
|_ subjectTable # TableObject
|_ subject_00 # GroupObject
</code></pre>
<p>Registring a new subject means adding a row t... | <pre><code>row_str = 'h5f.root.{}'.format(user)
where = eval(row_str)
subjectGroup = h5f.createGroup(where, subjectName)
</code></pre> | python|database|hdf5|pytables | 3 |
6,522 | 67,183,616 | How I can get HTML tags where located some text | <p>I have some text, like <code>message</code></p>
<p>I have a method who search this last message:</p>
<pre><code>def get_message_text(self):
return self.get_elements(f"//*[@data-qa='Paragraph-message-text']")[-1].text
</code></pre>
<p>this text in HTML looks like this:</p>
<pre><code><h1><stron... | <p>Once you have the web element all that you need to get it's tag name(s) is<br />
<code>String tag = element.getTagName();</code><br />
In case the element has several tags you will have to split tag names from the <code>tag</code> string.<br />
My code syntax is in <code>Java</code> however it's quite similar to <co... | python|selenium | 0 |
6,523 | 4,483,888 | What are the benefits of pip and virtualenv? | <p>So everyone is telling me to use pip and virtualenv but no-one is able to
explain me how it is better than my current approach. The main reason
for people to use pip and virtualenv seems to be that everyone else is using it...</p>
<p>I'm sure there are very good reasons to use PIP and virtualenv but I haven't
been ... | <p>virtualenv really shines when you have a number of projects, and don't want them to all share the same Python installation. For example, you could have two project with conflicting requirements.</p> | python|django|pip | 19 |
6,524 | 48,344,081 | PAGMO/PYGMO: Anyone understand the options for Corana’s Simulated Annealing? | <p>I'm using the PYGMO package to solve some nasty non-linear minimization problems, and am very interested in using their simulated_annealing algorithm, however it has a lot of hyper-parameters for which I don't really have any good intuition. These include:</p>
<p><code>Ts (float) – starting temperature
Tf (float) ... | <p>Gonna answer my own question here. I climbed into the actual .cpp code and found the answers.</p>
<p>In Corana's method, you select how many total iterations <code>N</code> of annealing you want. Then the minimization is a nested series of loops where you vary the step sizes, number of step-size adjustments, and te... | python|minimization|simulated-annealing | 0 |
6,525 | 51,267,502 | Parsing XML Soap Response With Python using Element Tree | <p>I have a XML Soap Response in this format , Which Has following info Username: Fulname: State: State Duration:</p>
<pre><code><return>
<columns>
<values>
<data>Username</data>
<data>Full Name</data>
<dat... | <pre><code>input_data = """<return>
<columns>
<values>
<data>Username</data>
<data>Full Name</data>
<data>State</data>
<data>State Duration</data>
</values... | python|xml|soap|elementtree | 0 |
6,526 | 51,481,371 | Allocate only one gpu to Keras (TF backend) script | <p>I have a machine with 2 GPUs.</p>
<p>Quite often, one is used in production (i.e doing predictions with the already trained model), while the other is used for training and experimenting new models.</p>
<p>While I was using theano, I had no problem running my scripts on only one GPU by specifying a flag as follow<... | <p>You can easily choose one gpu. Just fill 0 or 1 on <code>CUDA_VISIBLE_DEVICES</code></p>
<pre><code>import os
os.environ["CUDA_VISIBLE_DEVICES"]="1"
</code></pre>
<p>Furthermore if you want to spesify a portion of gpu for the selected gpu above, add:</p>
<pre><code>from keras import backend as K
import tensorflow... | python-3.x|tensorflow|machine-learning|keras|gpu | 7 |
6,527 | 51,140,011 | pandas:drop multiple columns which name in a list and assigned to a new dataframe | <p>I have a dataframe with several columns:</p>
<pre><code>df
pymnt_plan ... settlement_term days
</code></pre>
<p>Now I know which columns I Want to delete/drop, based on the following list:</p>
<pre><code> mylist = ['pymnt_plan',
'recoveries',
'collection_recovery_fee',
'policy_code',
'num_... | <p>You can do</p>
<pre><code>new_df = df[list]
df = df.drop(columns=list)
</code></pre> | python|pandas | 2 |
6,528 | 51,136,890 | Choose Items from a List in multithreaded python | <p>I am a beginner in python and cant figure out how to do this:
I am running a python script that puts a new value every 5-10 seconds into a list. I want to choose these elements from the list in another multithreaded python script however per thread one value, so one value shouldnt be reused, if theres no next value,... | <p>If I understood correctly, you want to use one thread (a producer) to fill a list with values, and then a few different threads (consumers) to remove from that same list. Thus resulting with a series of consumers which have mutually exclusive subsets of the values added by the producer. </p>
<p>A possible outcome m... | python|multithreading | 2 |
6,529 | 17,193,152 | Parsing html in Beautiful soup | <p>I try to parse the fragments of html like this: </p>
<pre><code><div><span>adrress</span>text of address</div>
</code></pre>
<p>How can I take fragment 'text of address' programatically without span tag in Beatiful soup?</p>
<p>Now I take whole content of div and remove span, but I think t... | <pre><code>>>> fragment = '<div><span>adrress</span>text of address</div>'
>>> soup = BeautifulSoup(fragment)
>>> soup.div.span.nextSibling
u'text of address'
</code></pre> | python|beautifulsoup | 1 |
6,530 | 17,139,627 | how to count words upto a limit in python? | <p>I am writing a code, to count the frequency of word occurrences in a document containing about 20,000 files,i am able to get the overall frequency of a word in the document and
my code so far is:</p>
<pre><code>import os
import re
import sys
sys.stdout=open('f2.txt','w')
from collections import Counter
from glob im... | <p>How about somethiing like this?</p>
<pre><code>from glob import glob # (instead of iglob)
...
filepaths = glob(os.path.join(folderpath,'*.txt'))
num_files = len(filepaths)
# Add all words to counter
for filepath in filepaths):
with open(filepath,'r') as filehandle:
lines = filehandle.read()
... | python|python-3.x | 2 |
6,531 | 69,955,310 | How to send email notification using Cloud Pubsub | <p>How to send email notification from Pub sub using python script when files are uploaded in google cloud compute engine.</p> | <h2>The following examples illustrate the creation of notification channels with Python</h2>
<pre><code>
def restore(project_name, backup_filename):
print(
"Loading alert policies and notification channels from {}.".format(
backup_filename
)
)
record = json.load(open(ba... | python|google-cloud-platform|google-compute-engine|google-cloud-pubsub|email-notifications | 1 |
6,532 | 73,064,527 | How to separate many dataframes from one excel Sheet Pandas | <p>I'm using an excel sheet with many different dataframes on it. I'd like to import those dataframes but separately. For now When i import the excel_file with pandas, it creates one single dataframe full of blanks where the dataframe are delimited. How can I create a different dataframe for each on of them?</p>
<p>Tha... | <p>If you're using the <code>pandas.read_excel()</code> function, you can simply use the <code>usecols</code> parameter to specify which columns you want to include in each dataframe. Only downside would be you'd need to do a <code>read_excel</code> call for each of the dataframes you want to read in.</p> | python|excel|pandas | 0 |
6,533 | 55,865,724 | Creating Pairs for Training a Siamese Network for Speaker Verification Text Dependent | <p>I want to build a siamese network for speaker verification using <code>python</code>. This network consists of 2 identical Convolutional Neural Network (CNN) to learn a similarity function which can distinguish whether 2 input voice belong to the same person or not. <br><br></p>
<h3>Data</h3>
<p>I have 10 person r... | <p>You should check out the end-to-end speaker verification systems, which are essentially siamese networks for speaker verification.</p>
<p><a href="https://arxiv.org/abs/1710.10467" rel="nofollow noreferrer">L. Wan, et al., "Generalized end-to-end loss for speaker verification," in Proc. ICASSP, 2018.</a></p>
<p>I ... | python|deep-learning|conv-neural-network | 0 |
6,534 | 50,205,577 | open multiple excel files with tkfiledialog | <p>I have some excel files and I want to open them at the same time and print their content. How can I do that with using tkFileDialog ?</p> | <p>Example of how to open many (text) files and print them: </p>
<pre><code>from tkinter import *
from tkinter import filedialog
root = Tk()
root.geometry('300x150')
root.title('Filemenu test')
file_list = filedialog.askopenfilenames()
for file in file_list:
with open(file) as input_file:
text = input_f... | python|tkinter | 0 |
6,535 | 66,579,313 | How to plot a dot plot type scatterplot in matplotlib or seaborn? | <p>Let's say I have a df like this:</p>
<pre><code>df = pd.DataFrame({'col1': list('aabbb'), 'col2': [1, 3, 1, 5, 3]})
col1 col2
0 a 1
1 a 3
2 b 1
3 b 5
4 b 3
</code></pre>
<p>I would like to see a plot, where on the x axis, I have the col1 names ONCE, and on the y axis, the col2 ... | <p>Beeswarm, strip, and scatter plots are all options, depending on your data and preferred aesthetic.</p>
<hr />
<h3><a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.scatter.html" rel="nofollow noreferrer"><code>plt.scatter</code></a> or <a href="https://pandas.pydata.org/pandas-docs/dev/reference/... | python|matplotlib|seaborn|scatter|dot-plot | 2 |
6,536 | 62,473,310 | Large data sets with array in Python | <p>Currently I have large data sets ( 2 columns which are X and Y and more than 2000 arrows) in excel and csv. files which I want to import and use in Python as array list of values in X and Y. I can't seem to import this X and Y columns with around 2000 values into the code in order to work with them and test my code ... | <p>To read your csv and excel file you can use Pandas. It will give you a DataFrame which you can easily turn it into a list with some operations.</p>
<pre><code>import pandas as pd
# To make operations for excel files also import
from pandas import ExcelWriter
from pandas import ExcelFile
#Reading csv
xFile = pd.re... | python|arrays|excel|numpy|large-data | 2 |
6,537 | 56,456,656 | How do i merge (i.e 'concat') 100+ .csv files using the pandas module? | <p>I'm a newbie to data science with python. So, I wanted to play around with the following data "<a href="https://www.ssa.gov/OACT/babynames/limits.html" rel="nofollow noreferrer">https://www.ssa.gov/OACT/babynames/limits.html</a>." The main problem here is that instead of giving me one file containing the data for al... | <p>Try something like this:</p>
<pre><code>import pandas as pd
import glob
path = r'../' # use your path
all_files = glob.glob(path + "/*.txt")
list = []
for filename in all_files:
df = pd.read_csv(filename)
list.append(df)
final_df = pd.concat(list, axis=0, ignore_index=True)
</code></pre> | python|pandas|csv|concat | 0 |
6,538 | 61,132,755 | sentence that appear the most using tfidf in my dataframe with python | <p>I want to look for the sentence that appear the most using tfidf in my dataframe, I did some preprocessing as tokenize and stopword, and now I have 2 columns (text & Stopword)</p>
<pre><code>text Stopword
bts jimin declared himself the worst play... | <p>So it looks like there's a lot of equations to <a href="https://en.wikipedia.org/wiki/Tf%E2%80%93idf" rel="nofollow noreferrer">tf-idf</a>. I'm unsure which one to use, but once you decide I would do something like:</p>
<pre class="lang-py prettyprint-override"><code>def tf_idf(word):
# do stuff
return stuff
o... | python|csv|dataframe|tokenize|tf-idf | 0 |
6,539 | 66,282,221 | Remove all zero rows and columns from symmetric numpy matrix | <p>I have this symmetric matrix:</p>
<pre class="lang-py prettyprint-override"><code>>>> X = np.array([[2,0,1,0],[0,0,0,0],[1,0,1,0], [0,0,0,0]])
array([[2, 0, 1, 0],
[0, 0, 0, 0],
[1, 0, 1, 0],
[0, 0, 0, 0]])
</code></pre>
<p>What's the most concise way to remove rows and columns that a... | <pre><code>rows = np.argwhere(np.sum(X, axis=0) == 0).flatten()
cols = np.argwhere(np.sum(X, axis=1) == 0).flatten()
np.delete(np.delete(X, rows, axis=0), cols, axis=1)
</code></pre> | python|numpy | 1 |
6,540 | 62,381,380 | Deep Learning: when learning rate is too high | <p>I observed something really odd in my code when I vary the learning rate of SGD in Keras:</p>
<pre class="lang-py prettyprint-override"><code>def build_mlp():
model = Sequential()
model.add(Conv2D(24, nb_row=3, nb_col=3, border_mode='same', activation='relu', input_shape=(28, 28, 1)))
model.add(BatchNor... | <p>What happens is that your high learning rate has driven the layer's weights out of bounds. That in turn causes the softmax function to output values that are either exactly 0 and 1 or very close to those numbers. The network becomes "too confident."</p>
<p>So regardless of input, your network will output 10-dimensi... | python|tensorflow|keras|deep-learning | 1 |
6,541 | 35,679,622 | (Python--numpy) how to resize and slice an numpy array with out a loop? | <p>So say I have this 2d numpy array:</p>
<pre><code>(
[
[1,2,3,4],
[5,6,7,8],
[9,8,7,6],
[5,4,3,2]
]
);
</code></pre>
<p>I'd like to sub-sample this and get 2 by 2 like this (indexing every other row and every other column):</p>
<pre><code>(
[
[1,3],
[9,7]... | <p>Yes you can use indexing with steps (in your example step would be 2):</p>
<pre><code>import numpy as np
a = np.array([[1,2,3,4], [5,6,7,8], [9,8,7,6], [5,4,3,2]])
a[::2, ::2]
</code></pre>
<p>returns</p>
<pre><code>array([[1, 3],
[9, 7]])
</code></pre>
<p>The syntax here is <code>[dim1_start:dim1_stop:d... | python|arrays|numpy | 2 |
6,542 | 58,750,432 | Sort date in string format in a pandas dataframe? | <p>I have a dataframe like this, how to sort this.</p>
<pre><code> df = pd.DataFrame({'Date':['Oct20','Nov19','Jan19','Sep20','Dec20']})
Date
0 Oct20
1 Nov19
2 Jan19
3 Sep20
4 Dec20
</code></pre>
<p>I familiar in sorting list of dates(string)</p>
<pre><code> a.sort(key=lambda... | <p>First convert column to datetimes and get positions of sorted values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.argsort.html" rel="noreferrer"><code>Series.argsort</code></a> what is used for change ordering with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/... | python|pandas|dataframe | 5 |
6,543 | 59,596,423 | Is it possible to rename "_id" to something else while aggregating in mongodb? | <p>I have the following query</p>
<pre class="lang-py prettyprint-override"><code>collection.aggregate([
{"$match": {"timestamp": {"$gte": lastDateInUnix}} },
{ "$group": {
"_id": {
"$dateToString": {
"format": "%d-%m-%Y",
... | <p>You use a <code>$project</code> to do that, <code>_id</code> is a required field for documents existing in DB, but you transform the document or result the way you like using <code>.aggregate()</code> or <code>.find()</code> which are two ways you retrieve data from DB :</p>
<pre><code>collection.aggregate([
{ ... | python|mongodb|pymongo | 1 |
6,544 | 60,197,498 | Getting the phase of a complex number | <p>I am using the following code - but not getting the phase back in the original
form (3.366):</p>
<pre><code>import math
import numpy as np
import cmath
Magn = 0.786236
Phase = 3.366
cohs = Magn * math.cos(Phase) + 1j*Magn*math.sin(Phase)
Magn_value = np.absolute(cohs)
Phase_value = np.angle(cohs)
print(alpha... | <p>Look at the documentation for the <code>angle</code> method: you get the phase expressed in a given range, -π to +π. If you want it in the more positive range 0 to 2π, simply add 2π to any negative value.</p> | python|complex-numbers | 3 |
6,545 | 35,047,991 | SQLAlchemy Error in elements.py - ColumnClause nor Comparator has 'description' | <p>The full error is:</p>
<pre><code>AttributeError: Neither 'ColumnClause' object nor 'Comparator' object
has an attribute 'description'
</code></pre>
<p>Occuring at line 544 in sqlalchemy\sql\elements.py in __ repr __</p>
<p>at line 735 in sqlalchemy\sql\elements.py in __ getattr__</p>
<p>I initially discovered ... | <p><code>Column</code> should be capitalized, as in: </p>
<p><code>streetnum = db.Column(db.String(100))</code></p>
<p>:) </p> | python|sqlalchemy|flask-sqlalchemy | 5 |
6,546 | 61,496,841 | How to remove rows with certain values | <p>I want to remove the rows that contain "New York" in city column. I have written the following:</p>
<pre><code> mydata=mydata[(mydata['city'] != ' New York')
</code></pre>
<p>When I query like below, I do not get any rows back (I checked for different white space variations too)</p>
<pre><code> mydata[(my... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.strip.html" rel="nofollow noreferrer"><code>Series.str.strip</code></a> and change tested value with no trailing space:</p>
<pre><code>mydata=mydata[(mydata['city'].str.strip() != 'New York') ]
</code></pre> | pandas|categorical-data | 0 |
6,547 | 57,340,634 | Fill dictonary values as the sum of values from a pandas dataframe | <p>I have a dictionary that contains the names of various players with all values set to <code>None</code> like so...</p>
<pre class="lang-py prettyprint-override"><code>players = {'A': None,
'B': None,
'C': None,
'D': None,
'E': None}
</code></pre>
<p>A pandas data frame (... | <p>Ummm <code>pandas</code> <code>stack</code> , usually we can <code>groupby</code> after flatten the df</p>
<pre><code>s=df2.stack().groupby(df1.stack().values).sum()
s
A 16
B 11
C 10
D 7
E 15
dtype: int64
s.to_dict()
{'A': 16, 'B': 11, 'C': 10, 'D': 7, 'E': 15}
</code></pre> | python|pandas | 4 |
6,548 | 54,178,646 | Python gTTS, is there a way to change the speed of the speech | <p>It seems that on gTTS there is no option for changing the speech of the text-to-speech apart from the slow argument. </p>
<p>I would like to speed up the sound by 5%. Any suggestion on how I can do it? </p>
<p>Best.</p>
<pre><code>tts_de = gTTS("Hallo, guten tag.", lang = 'de')
tts_de.save("s.mp3")
</code></pre> | <p>This isn't actually possible. According to the <a href="https://buildmedia.readthedocs.org/media/pdf/gtts/latest/gtts.pdf" rel="nofollow noreferrer">offical gTTS docs</a>, the only arguments relating to speed gTTS accepts is <code>slow</code>, a boolean specifying whether or not to slow down the playback.</p>
<p>If... | python|gtts | 3 |
6,549 | 58,279,628 | What is the difference between tf.keras and tf.python.keras? | <p>I've ran into serious incompatibility problems for the same code ran with one vs. the other; e.g.:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/58261348/valueerror-tried-to-convert-y-to-a-tensor-and-failed-error-none-values-not">Getting value of tensor</a></li>
<li><a href="https://stackoverflow.com/qu... | <p>From an official <a href="https://github.com/tensorflow/tensorflow/issues/33075#issuecomment-539070546" rel="noreferrer">TensorFlow dev</a>, shortened (emphasis mine):</p>
<blockquote>
<p>The API import is in the root of the package. Any other import is just Python allowing you to access privates with no consider... | python|tensorflow|keras|tensorflow2.0 | 14 |
6,550 | 28,452,307 | using subprocess pipe and stderr for one command | <p>Basically, I am trying to run the command (in linux)</p>
<pre><code>chrome http://www.google.com | cleanup.py
</code></pre>
<p>and trying to log stderr to a file.</p>
<pre><code>with open("/tmp/chrome-logs.txt", 'a') as tempf:
run_pipe = subprocess.Popen( ["-c", "cleanup.py"] , stdin=subprocess.PIPE, std... | <p>Try</p>
<pre><code>stderr=open(<file name>', 'w')
</code></pre>
<p>And then you do not need <em>communicate</em>, you may also just use <em>call</em> instead of <em>Popen</em></p> | python | 0 |
6,551 | 56,873,648 | How to do change color of the word for live template in pycharm? | <p>for example, I created such a live template.</p>
<pre><code>{% for %}
{% endfor %}
</code></pre>
<p>I want to change the color of the word "for".
how can I do it? please help me</p> | <p><strong>Edit:</strong> This setting seems to be available for Professional version of PyCharm.</p>
<p>Go to <code>Settings > Editor > Color Scheme > Django/Jinja2 Template > Tag Name</code></p>
<p><a href="https://i.stack.imgur.com/JAUpk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.co... | python-3.x|pycharm | 0 |
6,552 | 46,343,194 | How can I give the number two decimal in my template? | <p>I use the total_prices in my template</p>
<pre><code>{{ data.total_prices }} # there shows 300
</code></pre>
<p>But how can I give it both float number?</p>
<p>I means it looks like <code>300.00</code> in template.</p>
<p>How to do with that?</p> | <p>Use the <a href="https://docs.djangoproject.com/en/dev/ref/templates/builtins/#floatformat" rel="nofollow noreferrer">floatformat</a> template filter,</p>
<pre><code>{{ data.total_prices|floatformat:-2 }} # now it shows 300.00
</code></pre> | python|django|django-templates | 4 |
6,553 | 53,410,160 | Dynamic value change in for loop in django | <p>Hi how to pass dynamic value in for loop. in <code>value={{ product.size.0.size }}</code>
instead of 0 i want to pass index value</p>
<pre><code>{% for no_of in product.size %}
{{ forloop.counter }}
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label... | <p>No you don't. You're already iterating through the actual list, not the numbers.</p>
<pre><code>{% for size_item in product.size %}
...
value="{{ size_item.size }}"
...
{% endfor %}
</code></pre> | python|django|python-3.x|django-templates | 0 |
6,554 | 53,457,228 | cmd window and shutdown not running | <p>hello all I am python programmer
I made a program with spyder IDE with python 3.7.0
when I ran this program the program didn't execute the desired action
that is they don't shutdown this pc or lock it and doesn't open cmd
can you show me the mistake and if possible correct the code by typing below</p>
<pre><code>im... | <p><a href="https://docs.python.org/3/library/functions.html#input" rel="nofollow noreferrer">[Python 3]: <strong>input</strong>(<em>[prompt]</em>)</a> returns a <strong>string</strong>. When comparing a string with an integer (e.g. <code>"1" == 1</code>), <strong>the result will always be <em>False</em></strong>.</p>
... | python-3.x|operating-system|ctypes | 0 |
6,555 | 53,497,678 | How to read a Google Contacts csv file? | <p>I exported my Google Contacts into a CSV file and I am trying to parse it with <code>csv</code>:</p>
<pre><code>import csv
contacts = csv.DictReader(open('google.csv', 'rb'))
for c in contacts:
print(c)
</code></pre>
<p>This crashes with <code>csv.Error: iterator should return strings, not bytes (did you open ... | <p>You can try it using Pandas library that is the way that I used to read csv files.</p>
<pre><code>import pandas as pd
contacts = pd.read_csv('google.csv', na_values=['NA'])
</code></pre>
<p>Also I have found this <a href="https://realpython.com/python-csv/" rel="nofollow noreferrer">link</a> that maybe can help y... | python|python-3.x|csv|google-contacts-api | 0 |
6,556 | 21,910,829 | How can I get one column of a Numpy array? | <p>I am triyng to get the 3 columns of a NumPy (RGB) array:</p>
<pre><code>print px
[[[ 0 0 0]
[255 255 255]
[255 0 0]
[ 0 255 0]
[ 0 0 255]]]
print px[:,0]
print px[:,1]
print px[:,2]
[[0 0 0]]
[[255 255 255]]
[[255 0 0]]
</code></pre>
<p>but I would like to get the R, G and B like</p>
... | <p>Your array <code>px</code> is three-dimensional: the first dimension has just a single element: the complete arrays containing rows and colums. The second dimension is rows, the third is colums. Therefore, to select a column, and have it embedded in the outermost dimension like you have, use the following:</p>
<pre... | python|arrays|numpy | 3 |
6,557 | 24,665,992 | Applying two equations to one array | <p>I'm new to Python and Numpy, and I've spent a lot of time (days) searching for answers to my question, but I'm getting stumped. I have an array of magnitudes for earthquakes, and I need to convert them to a different form of magnitude (Mb to Mo). For magnitudes less than 4.3, I need to apply one conversion, and for ... | <pre><code>mw = numpy.where(mag < 4.3, 1.03 + 0.67 * mag, 0.1 + 0.88 * mag)
</code></pre>
<p>See docs on <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>. The first parameter will transform <code>data</code> into a boolean list, the second tw... | python|arrays|numpy | 3 |
6,558 | 51,621,611 | Django : view calls an other template (Pagination ) | <p>I have this view:</p>
<pre><code>class DamageListCriteria(TemplateView):
template_name = "damage/damagelist_criteria.html"
def get(self, request):
form = DamageListCriteriaForm()
general = General.objects.get(pk=1)
args = {
'form': form,
'general': general
}
return render(reques... | <p>The easiest thing to do would be not use Django itself but use Django REST framework and reuse its serializer classes along with APIView (or one of its subclasses). Are you in a position to use it or are you constrained?</p> | python|django | -1 |
6,559 | 54,651,114 | Dropping duplicate values in a column | <p>i have a frame like;</p>
<pre><code>df = pd.DataFrame({'America':["24,23,24,24","10","AA,AA, XY"]})
</code></pre>
<p>tried to convert it to a list, set etc.. but coudnt handle </p>
<p>how can i drop the duplicates </p> | <p>Use custom function with <code>split</code> and <code>set</code>:</p>
<pre><code>df['America'] = df['America'].apply(lambda x: set(x.split(',')))
</code></pre>
<p>Another solution is use list comprehension:</p>
<pre><code>df['America'] = [set(x.split(',')) for x in df['America']]
</code></pre>
<hr>
<pre><code>p... | python|pandas | 1 |
6,560 | 27,003,492 | celeryd with RabbitMQ hangs on "mingle: searching for neighbors", but plain celery works | <p>I'm banging my head to the wall with celeryd and RabbitMQ. </p>
<p>This example from tutorial is working just fine:</p>
<pre><code>from celery import Celery
app = Celery('tasks', backend='amqp', broker='amqp://')
@app.task
def add(x, y):
return x + y
</code></pre>
<p>I run:</p>
<pre><code>celery -A tasks worke... | <p>If you use the Database backend, adding the following options to celery should solve the problem:</p>
<pre><code> --without-mingle
</code></pre> | python|rabbitmq|celery|celeryd | 2 |
6,561 | 37,901,750 | How to back reference an object within a mocked method | <p><strong>Method:</strong></p>
<pre><code>def analyse_sentence(self, sentence, channel):
found_top_news = 'top news' in sentence or 'trending news' in sentence
if found_top_news:
categories = []
found_categories = SharedNewsUtils.extract_categories(sentence, categories)
... | <p>If <code>extract_categories</code> is mutating <code>categories</code> then you should be able to use <code>side_effect</code> in your test to mutate <code>categories</code>:</p>
<pre><code>def mutate_categories(sentence, categories):
categories.append('some_item')
mck.side_effect = mutate_categories
</code></p... | python|unit-testing|mocking | 0 |
6,562 | 51,169,517 | Advanced MultiIndex sorting and indexing | <p>I have a data with >100k rows and I need to efficiently regroup it from the left DataFrame to the multiindexed right one which indices are sorted by the sum of values in the 3rd column and inside each index 2nd column values are sorted by values in the 3rd column. All sortings are descending.</p>
<p>I have no idea ... | <p>I believe need:</p>
<pre><code>#aggregate sum by a, b columns
df = df.groupby(['a','b'], as_index=False)['c'].sum()
print (df)
a b c
0 bar one 1
1 baz one 1
2 baz two 3
3 foo one 3
4 foo two 2
#create new column by position with transform sum per a column
df.insert(1, 'sum', df.groupby('a')... | python|pandas|sorting|indexing | 0 |
6,563 | 64,478,759 | How to read object type of list into pandas dataframe? | <p>type(output)</p>
<blockquote>
<p>list</p>
</blockquote>
<p>print(output)</p>
<blockquote>
<p>Profile(username='0000_', name='ha', profile_photo='/pic/profile_images%2F712711040.jpg', tweets_count=159, following_count=89, followers_count=34, likes_count=118, is_verified=False, banner_photo='/pic/profile_banners%2F258... | <p>Try this:</p>
<pre><code>import pandas as pd
df = pd.DataFrame([profile.__dict__])
</code></pre>
<p>with profile is your instance of class Profile</p> | pandas|list | 0 |
6,564 | 73,305,967 | How to return data in specific format from Python Flask API? | <p>I am writing a get API using python flask.
This API is for a FAQ webpage in which there are multiple question and answers which are divided section wise.</p>
<h2>Webpage Example: How Webpage section looks for FAQ</h2>
<pre><code>**Section 1**
Question : Question 1 for section1?
Answer : Answer 1 for section ... | <p>my friend. I have some tips for you.
First of all, you should not use a database connection like this.
This way, you can not easily use it in other parts of your program.
Second, It's usually better to use an ORM like Sqlalchemy integrated with Flask. It will help you satisfy also the first problem.</p>
<p>And for y... | python|python-3.x|flask|flask-restful | 0 |
6,565 | 73,437,705 | AssertionError encrypt in django | <p>so i want to encrypt text to audio mp3. but when i run the code, there's error message Exception Type: AssertionError. and it's say there's error at</p>
<blockquote>
<p>assert len(key) == key_bytes</p>
</blockquote>
<p>can someone please check what's error with the function? i want encrypt using AES 128 and 256, pl... | <p>You have defined the value of <code>key_bytes</code> as <code>16</code> but in your <code>encrypt</code> function you are using <code>assert</code> to check whether the length of <code>key</code> which is 7 when you are calling the function(length of word "testing"), either you change the value of <code>ke... | python|django|encryption|key|aes | 0 |
6,566 | 73,478,066 | Efficiently merge all the polygons in a list in python | <p>I have a list of shapely polygons present in a list (around 12k). Many of the polygons in this list overlap with each other. The task I need to perform is to create a dictionary with the indexes of polygon which satisfy a certain overlapping threshold.
For e.g. if polygon1 overlaps with polygon5 and polygon6 and pol... | <p>I have got a similar problem. Find duplicate geometries and mark them out, solved by geopandas accessor <a href="https://my-data-toolkit.readthedocs.io/en/latest/reference/api/dtoolkit.geoaccessor.geoseries.duplicated_geometry_groups.html" rel="nofollow noreferrer">duplicated_geometry_groups</a>.</p>
<pre class="lan... | python|geometry|geopandas|shapely | 0 |
6,567 | 49,936,714 | Create first-class object all of it's instance attributes are readonly like slice? | <p>My question is how to create a class like <code>slice</code>?</p>
<p><code>slice</code> (built-in type) doesn't have a <code>__dict__</code> attribute
even that the <code>metaclass</code> of this <code>slice</code> is <code>type</code>.</p>
<p>And it is not using <code>__slots__</code>, and <strong>all it's attrib... | <p>The thing is that Python's built-in <code>slice</code> class is programmed in C. And when you code using the C-Python API you can code the equivalent of attributes accessible with the <code>__slots__</code> without using any mechanisms visible from the Python side. (You can even have 'real' private attributes, which... | python|python-2.7|metaclass|readonly-attribute | 3 |
6,568 | 64,054,012 | Looping through an array of API values for API GET request in Python | <p>I have an array of ice cream flavors I want to iterate over for an API GET request. How do I loop through an array such as [vanilla, chocolate, strawberry] using the standard API request below?</p>
<pre><code>import requests
url = "https://fakeurl.com/values/icecreamflavor/chocolate?"
payload = {}
heade... | <p>You could probably try string formatting on your url. You could loop through your array of ice-cream flavors, change the url in each loop and perform API GET request on the changed url.</p>
<pre><code>import requests
iceCreamFlavors = ["vanilla", "chocolate", "strawberry"]
url = "... | python|api|loops|get|python-requests | 0 |
6,569 | 65,158,714 | Allowing users to own their product in DJango | <p>i want to allow users to view only their own product. But i keep getting this error ""Cannot query "musty474": Must be "Merchant" instance"".</p>
<p>thanks beforehand.</p>
<p>models.py</p>
<pre><code>class Merchant(models.Model):
"""that means each product h... | <p>It doesn't look like owner is a member of Product. I think you need something like</p>
<pre><code>products=Product.objects.filter(merchant__owner=request.user)
</code></pre>
<p>This looks at the <code>owner</code> field off of the <code>merchant</code> field of Product.</p> | python|python-3.x|django|django-models|django-views | 0 |
6,570 | 65,422,451 | Python imaplib library mail.fetch, why do we hardcode response[0][1]? | <p>I am using the below code to read an unread email.</p>
<p>In <code>mail.fetch</code> method, getting typ,data as a returned parameters and we are accessing the raw email with <code>raw_email = data[0][1]</code>. Could anyone explain why we are hardcoding the index as <code>[0][1]</code> for getting the message? Is ... | <p>The response from the IMAP server is a nested tuple containing a status message, envelope information, and the actual contents of the email you requested. There is no simple way to avoid saying which parts of the response tuple you need, though perhaps you will want to look for a higher-level wrapper around Python'... | python|imaplib | 0 |
6,571 | 65,262,973 | callback causes ValueError | <p>The codes were working fine for the past months but somehow went wrong after something I have done but I cannot restore it.</p>
<pre><code>def bi_LSTM_model(X_train, y_train, X_test, y_test, num_classes, loss,batch_size=68, units=128, learning_rate=0.005,epochs=20, dropout=0.2, recurrent_dropout=0.2):
class... | <p>The problem is not the callback function. The error shows up because you pass the same optimizer to two different models, which is not possible since they are two different computational graphs.</p>
<p>Try to define the optimizer inside the function where you define the model before the <code>model.compile()</code> ... | python|tensorflow|machine-learning | 1 |
6,572 | 71,931,540 | How to sum values in a file and update the file with the new values in python | <p>let's say i have a file with data like that:</p>
<pre><code>Bicycle,204,28,271,193
Bicycle,136,190,79,109
</code></pre>
<p>I want to add the numbers with each other so that the new lines will be like that</p>
<pre><code>Bicycle,204,28,475,221 #as 271+204=475 and 28+193=221
Bicycle,136,190,215,229 #as 136+79=215 and ... | <pre><code># your default code that reads in the csv
with open(filepath) as f:
matrix=[line.split(',') for line in f]
f.close()
# 'w' means to write over the file and its existing content
with open(filepath, 'w') as f:
# loop over each row in your matrix
for row in matrix:
# add 2nd positi... | python|file | 1 |
6,573 | 68,765,748 | Resize image according to other model fields | <p>How do I use the value of other model fields in some field? I want to resize an image to the width and height specified in their respective fields:</p>
<pre><code>class MyImage(models.Model):
name = models.CharField(max_length=128, blank=False)
width = models.PositiveIntegerField(blank=False) #--->
h... | <p>You can create an exchange function, where through ORM you take all your objects and walk through them exchanging the necessary values</p>
<p><a href="https://stackoverflow.com/questions/21249374/django-orm-query-how-to-swap-value-of-a-attribute">Django ORM query: how to swap value of a attribute?</a></p> | python|python-3.x|django|django-models | 0 |
6,574 | 71,491,088 | Months between two dates - pandas series and datetime.date.today() | <p>I am trying to calculate the number of months between two dates. I am running the operation on a pandas Series.</p>
<p>Sample series:</p>
<pre><code>3645 2014-06-24
3646 2020-11-03
3647 2016-06-28
3648 2017-07-20
3649 2000-03-27
Name: lastSaleDate, Length: 1797, dtype: datetime64[ns]
</code></pre>
<p>I'd l... | <p>As the error says, the types don't match. You have to either convert <code>datetime.date</code> object to pandas datetime or you could use <code>to_datetime('today')</code> instead:</p>
<pre><code>df['mos'] = df['lastSaleDate'].rsub(pd.to_datetime('today'))/np.timedelta64(1, 'M')
</code></pre>
<p>or (more readably)<... | python|pandas|datetime | 1 |
6,575 | 10,518,333 | Intermittent KeyError raised and can not reproduce it | <p>I tried to reproduce it with some simpler functions but didn't succeed. So the following code shows the relevant methods for a KeyError which get's thrown by our production servers, a lot. </p>
<pre><code>class PokerGame:
...
def serialsNotFold(self):
return filter(lambda x: not self.serial2player[x].is... | <p>I guess you use threads and self.serial2player gets modified by a different thread.</p> | python | 0 |
6,576 | 62,883,172 | Add additional attribute to keepass record in python | <p>I'm using pykeepass to do bulk modification on several hundred keepass files and I'd like to add some additional attributes to the keepass entries.</p>
<p>I tried to do it like this:</p>
<pre><code>def updateRecord(record, recordParent, recordGrandparent, recordGreatGrandparent, kdbxHandle):
record.custom_propert... | <p>Ok I can answer my own question - setting a custom property is done like this:</p>
<p><code>record.set_custom_property("keepass2", recordGrandparent)</code></p> | python-3.x|keepass | 0 |
6,577 | 62,006,693 | how to python opencv size increase and decrease window for a live cam | <p>How can python opencv size increase and decrease window for a live cam.
The cammera work but I don,t how Its larger and smaller interface live cam.</p> | <p>This is the solution of your Questions.
Check it's Now..</p>
<p>Click this links...</p>
<p><a href="https://stackoverflow.com/a/61848405/13491597">https://stackoverflow.com/a/61848405/13491597</a></p>
<p>After you whaterver set your size whatever you want..</p> | python|numpy|opencv|cv2 | 2 |
6,578 | 67,184,609 | Pandas: How to get the sample rows from each category from specific column in dataframe and save in single csv? | <p>Below is the dataframe (df). I want to save the sample of 3 rows from each category of 'country' column.
Following is my code but it's not saving based on category. I need single csv having the samples. Please suggest.</p>
<pre><code>data = {'country':['India', 'Nepal', 'Canada', 'USA','India', 'Nepal', 'Canada', 'U... | <p>GroupBy and then sample</p>
<pre><code>df.groupby('country').sample(3)
country Age
2 Canada 19
6 Canada 19
10 Canada 19
4 India 20
0 India 20
12 India 20
1 Nepal 21
13 Nepal 21
9 Nepal 21
3 USA 18
11 USA 18
19 USA 18
</code></pre> | python|pandas | 0 |
6,579 | 67,532,887 | Parsing variables in context.bot.send_message() | <p>I'm currently developing a bot with the help of <a href="https://python-telegram-bot.readthedocs.io/en/stable/index.html" rel="nofollow noreferrer">python-telegram-bot</a> and I've encountered myself with a bit of a problem.</p>
<p>See the goal is that when the user runs the command <strong>/casosspain</strong> the ... | <p>You can use python's f strings <a href="https://docs.python.org/3/tutorial/inputoutput.html#formatted-string-literals" rel="nofollow noreferrer">7.1.1. Formatted String Literals</a></p>
<pre><code>text = f"Los casos confirmados en españa son: {var}"
</code></pre>
<pre><code>>>> var = "12.321.... | python|python-3.x|telegram|telegram-bot|py-telegram-bot-api | 0 |
6,580 | 60,496,204 | WebDriverWait for multiple conditions (OR logical evaluation) | <p>Using python, the method WebDriverWait is used to wait for 1 element to be present on the webpage.
How can this method be used without multiple try/except?
Is there an OR option for multiple cases using this method?
<a href="https://selenium-python.readthedocs.io/waits.html" rel="nofollow noreferrer">https://seleni... | <p>Without using multiple <code>try/except{}</code> to induce <em>WebDriverWait</em> for two elements through OR option you can use either of the following solutions:</p>
<ul>
<li><p>Using <code>CSS_SELECTOR</code>:</p>
<pre><code>element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR... | python|selenium|selenium-webdriver|webdriver|webdriverwait | 8 |
6,581 | 71,162,332 | Make Folium map interactible from page where it's embedded | <p>I'm working on an app that uses ReactJS for front end.</p>
<p>I'm using Folium to generate different kind of maps (choropleth / heatmap / markercluster).</p>
<p>My goal is to be able to control some features of the map from the other components of the app (for instance highlighting markers or area when they're selec... | <p>Ok I've done it, but it's bloody hideous.</p>
<pre class="lang-js prettyprint-override"><code>document.getElementById('testBtn').onclick= () => {
// Get the 'window' object of the iFrame
const mapWindow = document.getElementById('mapFrame').contentWindow;
let keys = Object.keys(mapWindow);
// Fol... | javascript|python|reactjs|folium | 0 |
6,582 | 53,188,883 | Pandas Dataframe automatically renames duplicate columns name | <p>I have a dataframe with 10 columns and 160 rows. Column names are based on month and year for e.g Jun'17, July'17, Mar'18 etc.
However in excel some columns are repeating like Jun'17 two times
When I import them to pandas dataframe it renames duplicate columns to Jun'17 and Jun'17.1</p>
<p>This '.1' is extra and di... | <p>I dont think it is a good idea have more columns with the same name, and i wouldnt suggest this, but if you want to go with that, you can do in this way:</p>
<pre><code>df = df.rename(columns = {"Jun'17.1":"Jun'17"})
</code></pre>
<p>To access to the 2 different columns then do in this way:</p>
<pre><code>df["Jun... | python|pandas|dataframe | 2 |
6,583 | 70,336,328 | how to group two columns in one column order by id python | <p>Hy I have a dataframe with the following structure</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Id</th>
<th>Vehicle1</th>
<th>Vehicle2</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>car</td>
<td>motorcycle</td>
</tr>
<tr>
<td>2</td>
<td>bike</td>
<td>car</td>
</tr>
<tr>
<td>3</td>
<t... | <pre><code>df.set_index("Id").stack()
</code></pre>
<p>This will sort all elements with the same Id by their respective column order.</p> | python|pandas|group-by|pandas-groupby | 0 |
6,584 | 10,935,265 | django request with two date field | <p>I am trying to attempt a request with a filter on a combination of a date, and an integer which represent a year, and I encounter some trouble doing it.</p>
<p>Here is my model :</p>
<pre><code>class Exemple(models.Model):
date_field = models.DateField()
year_field = models.IntegerField()
</code></pre>
<p... | <p>That's exactly the problem. You can't do complex calculations like that with just the ORM. However, you might be able to take advantage of the <code>__year</code> lookup to simplify the math:</p>
<pre><code>Exemple.objects.filter(date_field__year__lt=F('year_field'))
</code></pre>
<p>Anything more complex than tha... | python|django|date|filter|request | 0 |
6,585 | 10,959,858 | Tkinter Canvas move item to top level | <p>I have a Tkinter Canvas widget (Python 2.7, not 3), and on this Canvas I have different items. If I create a new item that overlaps an old item, It will be in front. How can I now move the old item in front of the newly created one, or even in front of all other items on the Canvas?</p>
<p>Example code so far:</p>
... | <p>Use the <code>tag_lower()</code> and <code>tag_raise()</code> methods for the <code>Canvas</code> object:</p>
<pre><code>canvas.tag_raise(firstRect)
</code></pre>
<p>Or:</p>
<pre><code>canvas.tag_lower(secondRect)
</code></pre> | python|tkinter|widget|tkinter-canvas | 16 |
6,586 | 70,392,317 | Matplotlib plotting custom colormap with the plot | <p>I have been following a tutorial on plotting F1 data over a circuit, color coded with the <code>fastf1</code> library.
I wanted to add some extra's to the script to utilize the official team colors.
It works but the end result shows the colormap with the circuit covering the <code>n bins 100</code>. <a href="https:/... | <p>Instead of creating a whole custome cmap, I got rid of this piece of code:</p>
<pre class="lang-py prettyprint-override"><code># Create custom colormap
teamcolor1 = to_rgb('{}'.format(team1_color))
teamcolor2 = to_rgb('{}'.format(team2_color))
colors = [teamcolor1, teamcolor2]
n_bins = [3, 6, 10, 100]
cmap_name = 'c... | python|matplotlib | 0 |
6,587 | 56,472,995 | Spliting ls results in python to only show first result | <p>After using glob to obtain the <code>ls</code> results that have <code>.log</code> files, I now need to only take the first result of the list.</p>
<pre><code>l=glob.glob('*.log*')
l=radius.log.2019-04-03_17', 'radius.log.2019-04-03_12', 'radius.log.2019-04-02_01', 'radius.log.2019-04-02_06', 'radius.log.2019-04-0... | <p>The <code>glob.glob('*.log*')</code> command will return a list. I believe <code>l</code> here is a list, although your code shows something else.</p>
<p>If you select only the first element using <code>l[0]</code>, you'll get the first element. If you want to store that in a variable you could do something like</p... | python | 1 |
6,588 | 17,751,322 | Python 2: AttributeError: 'list' object has no attribute 'strip' | <p>I have a small problem with list. So i have a list called <code>l</code>:</p>
<pre><code>l = ['Facebook;Google+;MySpace', 'Apple;Android']
</code></pre>
<p>And as you can see I have only 2 strings in my list. I want to separate my list <code>l</code> by <strong>';'</strong> and put my new 5 strings into a new list... | <p><a href="http://docs.python.org/2/library/string.html#string.strip"><code>strip()</code></a> is a method for strings, you are calling it on a <code>list</code>, hence the error.</p>
<pre><code>>>> 'strip' in dir(str)
True
>>> 'strip' in dir(list)
False
</code></pre>
<p>To do what you want, just d... | python|list|split | 24 |
6,589 | 66,159,269 | How can i make matrix 20*20 with solution (python) | <pre><code>mx = 20
my = 20
t0_matrix = np.array((mx, my))
for i in range(mx):
for j in range(my):
t0_matrix[i][j] = u(0, i, j, mx, my)
print(t0_matrix)
</code></pre>
<blockquote>
<p>TypeError Traceback (most recent call
last)
in ()
4 for i in range(mx):
5 for j in range(... | <p>The function <code>np.array</code> takes as argument a list (of lists...) that is converted into a numpy array. You can instead use the function <code>np.zeros</code> to intialize your t0_matrix, e.g. by doing <code>t0_matrix = np.zeros(shape=(mx, my))</code></p>
<p>The problem is that your code is going to result i... | python | 2 |
6,590 | 72,619,003 | Calculating BIOCLIM variables using Xarray and UKCP18 - Multivariable indexing | <p>I am currently generating several bioclimatic variables (climatic derivatives) to apply to some biodiversity work using UKCP18 data. I am generating bioclimatic variable "Bio 19": Precipitation of the Coldest Quarter (<a href="https://pubs.usgs.gov/ds/691/ds691.pdf" rel="nofollow noreferrer">https://pubs.u... | <p>This sounds like a case for <a href="https://docs.xarray.dev/en/latest/user-guide/indexing.html#more-advanced-indexing" rel="nofollow noreferrer">xarray's advanced indexing</a>! Get excited - this is one of the most fun & powerful features of xarray in my opinion :)</p>
<p>Here's a quick <a href="/help/mcve">MRE... | python|python-xarray | 1 |
6,591 | 59,207,505 | Fill in missing zipcodes by randomly selecting one from the neighbourhood | <p>I have a pandas dataframe like below and I'm trying to replace missing values in the zipcode field by selecting any random value from a similar neighbourhood_group_cleansed. Below is my attempt but this does not work quite well. Please help.</p>
<pre><code>zipcodes = a_df[['neighbourhood_group_cleansed','zipcode']]... | <p>This should work</p>
<pre><code>df['zipcode'] = df.apply(lambda x: random.choice(df[df['neighbourhood_group_cleansed'] == x['neighbourhood_group_cleansed']].zipcode.dropna().values) if np.isnan(x['zipcode']) else x['zipcode'], axis=1)
</code></pre> | python|pandas|group-by|data-cleaning | 1 |
6,592 | 59,444,973 | How to make json file a list in Python | <p>as said, I'd like to open a json file and make it into a list, in order to append new elements to it and then dump all back into the json file.</p>
<p>Here is my code(the commented part is what I previously tried):</p>
<pre><code>class Carta:
def __init__(self,filename):
self.__filename = filename
... | <pre class="lang-py prettyprint-override"><code>import json
#read from file
with open("demofile.txt", "r") as f: x = f.read()
#parse
y = json.loads(x)
#edit
y["user"] = { "fname": "John", "lname": "Who"}
#save to file
with open("demofile.txt", "w") as f: f.write(json.dumps(y))
</code></pre>
<p><a href="https://re... | python|json | 0 |
6,593 | 72,888,629 | How to cast the key to int type in dictionary comprehension in Python? | <p>Suppose I have two dictionaries</p>
<pre><code>dict_a_to_c = {'803': 2, '808': 8, '30': 9, '37': 11, '38': 12, '39': 13, '481': 18, '816': 21, .....}
# length of dict_a_to_c is huge.
dict_a_to_b = {480:2, 37:5, 40: 9, 816:20, 148: 18}
</code></pre>
<p>And I am mapping them through keys using:</p>
<pre><code># conv... | <p>You can cast to str instead of to int:</p>
<pre><code>dict_c_to_b = {dict_a_to_c[str(k)]: dict_a_to_b[k]
for k in dict_a_to_b if str(k) in dict_a_to_c}
</code></pre> | python|dictionary|data-structures | 1 |
6,594 | 63,292,816 | Checking whether 2 list has same value or value,index | <p>I have this 2 list</p>
<pre><code>a = [3,9,1,4,5]
b = [7,2,1,0,1]
</code></pre>
<p>Im trying to print a line based on some condition (same value or same index and value in 2 list), and the output should be</p>
<pre><code>"Same Value(for duplicate number)"
"Same Value + Index(for duplicate number and s... | <p>Your logic is faulty in looking up the number:</p>
<pre><code>for x in a:
for y in b:
if x == y:
if (a.index(x) == b.index(y)):
</code></pre>
<p><code>index</code> finds the <em>first</em> occurence of the value. Your desired output depends on knowing <em>which</em> index you have. Instead,... | python|list | 2 |
6,595 | 62,915,167 | opencv python not enough values to unpack | <p>I'm trying to do a gesture controlled smart mirror. But then when I try to run the <code>test.py</code>, the camera was on for one second, and then suddenly closed. This is the output that I got.</p>
<pre><code>DEBUG:asyncio:Using selector: SelectSelector
Exception in thread Thread-1:
Traceback (most recent call las... | <p><code>cv2.findContours()</code> function will return 2 values, not 3.</p>
<p>Read them as:</p>
<pre><code>contours, _ = cv2.findContours(...)
</code></pre> | python|opencv | 0 |
6,596 | 63,222,717 | Feature scaling in an incremental analysis | <p>I'm doing an incremental analysis of my data. The data belongs to 4 age groups (day1, day2, day3 and day4). Before I feed my data to the model, I standardize the features using the standard scaler implementation in sklearn. When I think of it, 3 approaches comes to my mind.</p>
<pre><code>Approach (1)standardize the... | <p>approach 1 is the best one and in fact the only correct one</p> | python|scikit-learn|data-analysis|standardized|feature-scaling | 0 |
6,597 | 62,996,988 | pandas resample with absolute max | <p>I have a DataFrame (with datetime index) e.g.</p>
<pre><code>2017-01-01 00:00:00 -8.64
2017-01-01 01:00:00 1.02
2017-01-01 02:00:00 1.03
2017-01-01 03:00:00 0.00
2017-01-01 04:00:00 -1.01
2017-01-01 05:00:00 -3.57
2017-01-01 06:00:00 -4.18
2017-01-01 07:00:00 7.73
</code></pre>
<p>I'd like... | <p>We can pass to <code>apply</code></p>
<pre><code>df.resample('4h').apply(lambda x : max(x, key = abs))
Out[234]:
2017-01-01 00:00:00 -8.64
2017-01-01 04:00:00 7.73
Freq: 4H, Name: caonima, dtype: float64
</code></pre> | python|pandas | 4 |
6,598 | 63,065,647 | Convert unicode String to Dictionary in python | <p>I have a variable which holds the table name and columns as a string.
Below is the sample:</p>
<pre><code>[(u'USER_SSO_PROPERTIES', u'[\n "FULL_NAME",\n "NAME"\n]'), (u'USERS', u'[\n "EMAIL",\n "NAME"\n]'), (u'PITCH_RECIPIENTS', u'[\n "EMAIL",\n "ID"\... | <p>Use <code>eval()</code> to quickly convert literals to actual Python values.</p>
<p>This code can convert your example.</p>
<pre><code>string = r'''[(u'USER_SSO_PROPERTIES', u'[\n "FULL_NAME",\n "NAME"\n]'), (u'USERS', u'[\n "EMAIL",\n "NAME"\n]'), (u'PITCH_RECIPIENTS', u'... | python | 1 |
6,599 | 62,227,883 | python email new line | <p>I tried to send an email which present stocks data and send it by email,
it goes to Yahoo and take the stock price and compare to a target and present it with <code>%</code> from the target
unfortunately it all came without a space between the stocks
I tried <code>\n</code> and <code>\r\n</code> but without success... | <p>You can try with html formatting:</p>
<pre><code>import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
message = MIMEMultipart('alternative')
message['subject'] = 'my subject'
message['from'] = 'from'
lb = ""
for symbol,price in stock.items():
lb += """<p>
... | python|email|newline | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.