questions stringlengths 50 48.9k | answers stringlengths 0 58.3k |
|---|---|
data-frame remove duplicate indexed rows I have a DataFrame (df) marksnap_time 140000 8250.0140000 8250.0141000 8252.0141000 8252.0142000 8249.0I'm trying to remove any rows with the same snap_time indexI've tried:df.drop_duplicates(subset=None, keep=False, inplace=False)But it's ... | try explicitly telling which columns to check for matching duplicatesdf.drop_duplicates(subset=['snap_time', 'mark'], keep=False) |
I need help visualising the font metrics in Wand Normally when I write a sentence in Wand using draw.text the letter spacing is taken care of, however I need to write one letter at a time to build frames for a text animation. The problem with this is that by moving the left offset (here is the documentation for the dra... | I figured out that y2 is height of the letters from the origin. It is the bearingY in documentation.y1 is height below the origin. |
How to convert a list to dict? I have lists like this:['7801234567', 'Robert Post', '66 Hinton Road']['7809876543', 'Farrukh Ahmed', '101 Edson Crest']['7803214567', 'Md Toukir Imam', '34 Sherwood Park Avenue']['7807890123', 'Elham Ahmadi', '8 Devon Place']['7808907654', 'Rong Feng', '32 Spruce Street']['7801236789', '... | Use zip to associate the keys with their values by indexkeys = ('tel', 'name', 'address')values = ['7801234567', 'Robert Post', '66 Hinton Road']d = dict(zip(keys, values))# {'tel': '7801234567', 'name': 'Robert Post', 'address': '66 Hinton Road'}Edit: Obviously, you can use this technique to create more complex struct... |
Python: Why does interpreter search for variable assignment in a function below the line being executed? ContextI am relatively new to python / computer programming and trying to wrap my head around some basic concepts by playing around with them.In my understanding, python is an interpreted language i.e. it evaluates ... | In my understanding, python is an interpreted language i.e. it evaluates the line of code as it is being executed.No.1 Python compiles a module at a time. All function bodies are compiled to bytecode, and the top-level module code is compiled to bytecode. That's what a .pyc file is—all those bytecode objects marshale... |
Python installed in multiple paths, is this bad? I am newish to python and Mac and may have messed up when installing python. Will this cause future errors?Also why are some paths listed multiple times?~ % where python3/opt/homebrew/bin/python3/Library/Frameworks/Python.framework/Versions/3.6/bin/python3/opt/homebrew/b... | First, what are these?/opt/homebrew/bin/python3 — this was installed by Homebrew./Library/Frameworks/whatever — This was probablyinstalled by an installation package from the Python website./usr/bin/python3 — this one probably came with Xcode.If you want Xcode installed, you're probably not going to get rid of (3), so ... |
Why all these decimals with sympy.solve? I have this system to solve:(y-1) x = 0(x-1) (1/2-x) y = 0I want to use Sympy's solve, but it gives me:[(0.0, 0.0), (0.500000000000000, 1.00000000000000), (1.00000000000000, 1.00000000000000)]Why all these decimals? I don't want them! what's wrong?import sympy as smx, y = sm.sym... | Try to modify the expression below...Y = -y*(1-x)*((1-x-x)/2...and wonder why the outcome is now what you want. |
astropy.io.fits: How to append new cards to a header of a fits file? I'm trying to insert/append new cards to an existing header (the PRIMARY header) of a FITS file. With the code I have below, I can see on the terminal that I am 'successful' in performing this action. But when I open the FITS file in DS9 and check the... | Indeed with your code you're not saving the updated file. You must use the update mode and call .flush():from astropy.io import fitswith fits.open('my.fits', mode='update') as hdul: hdr = hdul[0].header hdr.append(('NEWCARD', 'value', 'A comment.'), end=True) hdul.flush() # changes are written back to origina... |
sum of as many pairwise distinct positive integers Task. The goal of this problem is to represent a given positive integer as a sum of as many pairwise distinct positive integers as possible. That is, to find the maximum such that can be written as 1 + 2 + · · · + where 1, . . . , are positive integers and ̸= fo... | Using a greedy algorithm which selects the smallest available number is a good approach you chose.n = 17 # The inputx = 0 # The running totalfor k in range(1, n): # The maximum number is bounded above by n x += k if n - x < k + 1: # The next number is too big print(k) # Print k print(*list(range(... |
concatenate specific columns on Pandas dataframes I've been trying to add a multiples sets of data but can't seem to make it work.Say, I have three 3x9 dataframesdfA:A: Wave heightA: Wave periodA: Wave dirB: Wave heightB: Wave periodB: Wave dirC: Wave heightC: Wave periodC: Wave dir1/1/20011.15904.55903.151002/1/20011... | You can't have duplicated index values using pd.concatBut you can try with merge and parameter 'outer' :pd.merge(dfA, dfB, on="name_of_colum_index", how="outer")Set index name before. |
Django how to compute the Percentage using annotate? I want to compute the total average per grading categories and multiply it by given number using annotatethis is my views.py from django.db.models import Fgradepercategory = studentsEnrolledSubjectsGrade.objects.filter(grading_Period = period).filter(Subjects = subje... | You can do this using F ExpresisonsFrom the Docs:Reporter.objects.all().update(stories_filed=F('stories_filed') + 1)So your example would be something like:studentsEnrolledSubjectsGrade.objects.all().annotate(grade_percent=(.8 * F('Grading_Categories')) * (.15 * F('PercentageWeight') / 100)(as a side note, it is django... |
How to get the list of available encode/decode codecs? The documentation for open states:encoding is the name of the encoding used to decode or encode thefile. This should only be used in text mode. The default encoding isplatform dependent, but any encoding supported by Python can bepassed. See the codecs module for... | help(codecs)list the help for encode() as well.The following docs page also lists out the supported encodings.https://docs.python.org/3/library/codecs.html |
pandas multindex choose/drop rows based on second column Copying the example from this question, consider the following dataframe:mux = pd.MultiIndex.from_arrays([ list('aaaabbbbbccddddd'), list('tuvwtuvwtuvwtuvw')], names=['one', 'two'])df = pd.DataFrame({'col': np.arange(len(mux))}, mux) colone two ... | use head(2) with groupbydf.groupby('one').head(2)Out[246]: colone twoa t 0 u 1b t 4 u 5c u 9 v 10d w 11 t 12 |
Python: how can i replace the header by the first row of a web scraped table import pandas as pdurl = "http://hkureis.versitech.hku.hk/data.php"table = pd.read_html(url)[0]print(table)table.to_excel("Reis.xlsx")How can I get rid of the first row and the first column. Replacing them by the next row a... | Try it with the .to_string(index=False, header=False) method:print(table.to_string(index=False, header=False))Result:Save to Excel (.to_excel()):table.to_excel("data.xlsx", index=False, header=False) |
Does pre-processing run in parallel via dask? I am loading many netCDF4 files like so:theDataset=xr.open_mfdataset(input_files, concat_dim='time', preprocess=preprocess_dims, chunks={'time':chunk_size})The preprocessing function subsets... | According to the docstring for open_mfdataset it should do if you pass parallel=True.Here is the github pull request where parallel opening and preprocessing in open_mfdataset was implemented, I suggest you have a read. |
Create a list from a char and remove an element in Python? I have written the following function that gets a char, creates a list by a specified length of a char from it, and finally removes an element from the newly created list.def create_list_from_char(char, remove_elem): n = int(len(remove_elem)) ... | use this:def create_list_from_char(char, remove_elem): n = int(len(remove_elem)) my_list = [char[i:i+n] for i in range(0, len(char), n)] print("Created list is: ", my_list) print(remove_elem in my_list) my_list.remove(remove_elem) pr... |
screen looks like pushed toward left and up when rotating it in OpenCV Window have empty space in right and bottom about 3cm. It looks like the screen had pushed away. I rotate my screen to reference this page.Here is pictureimport cv2 cap = cv2.VideoCapture(0) #return 0 or -1while cap.isOpened(): ret, img = cap.rea... | The problem lies in the line img = cv2.warpAffine(img, M, (h, w)) where h and w must be interchanged. The function cv2.warpAffine() creates a new image with the rotation matrix M. But since w and h have been interchanged the resulting frame appears to have been translated resulting in the black region.Replace the above... |
How do I call an entry on tkinter? I'm new to Python and I'm struggling to figure out what's wrong with my code. import tkinter as tkr = tk.Tk()r.title('PROJECT')def file_entry(): global ent tk.Label(r, text = "ENTRY").grid(row = 2) ent = tk.Entry(r).grid(row = 2, column = 1) b_ent = tk.Button(r, text="OK"... | It appears that chaining the grid to the entry widget is not acceptable. If you put it on a separate line, the ent variable get properly assigned and get the inputted value as opposed to not working and being assigned None.Try this:def file_entry(): global ent tk.Label(r, text="ENTRY").grid(row=2) ent = tk.Ent... |
Why is Index being graphed and not country? Using Matplotlib Horizontal Bar Graph I'm pretty new to all of this. I've been looking online how to change my y-ticks to represent a column that I wanted to initially graph.Anyway, I have a dataframe that I created by using a SQL command...it's called eastasia_pac. The colum... | By default, matplotlib plots according the index of a specified dataframe. You can solve this by either setting the index of the data or by overwriting the values.Overwrite method:# I'm assuming this is what's creating your ploteastasia_pac.plot.barh()# Set your ticksplt.yticks(eastasia_pac.country, rotation= 90)# Set ... |
Adding value to Maximum Value in a dataframe column I have a dataframe:Region | A | B | C | Total===============================================================Africa | 100.10 | 20.135 | 10.02 | 130.255---------------------------------------------------------------E... | Using mul with bool maskdf=df.set_index('Region')df+=(df==df.max()).mul(df.loc['Unknown']) df=df.drop('Unknown',axis=0)df.Total=df.iloc[:,:-1].sum(1)df A B C TotalRegion Africa 100.1 20.135 10.02 130.255Europe 202.71 50.102 18.31 271.122India 30.... |
In Google Colab, I created a file with Pickle Library but I can't find it in Google Drive #Saving the best model with Pickle (Neural %83.43)import picklepickle.dump(classifier, open("NeuralNews", 'wb'))loading = pickle.load(open("NeuralNews", 'rb'))predictionPickleNeural = loading.predict(testResult2)predictionPickleNe... | Its inside the current directory of Google Cloud VM. You can try:import osos.listdir('.')If you get some output like,['.config', 'sample_data']then you can even get listing by issuing the command like below,!ls sample_datato look inside the sample_data folder. Anyway, you can upload/save it to your Google drive or down... |
Tensorflow: Building graph and label files form checkpoint file I want to build the graph and labels file from inception-resnet-v2.ckpt file. I have already downloaded the check point file formwget http://download.tensorflow.org/models/inception_resnet_v2_2016_08_30.tar.gz.I want to replace the inception5h model in ten... | Not sure, what the label file is, but to convert a checkpoint into a .pb file (which is binary protobuf), you have to freeze the graph. Here is a script I use for it:#!/bin/bash -x# The script combines graph definition and trained weights into# a single binary protobuf with constant holders for the weights.# The result... |
Show fewer pages in Django pagination I am working on a Django application and on one of the pages we use pagination. I have around 200 pages and if I am somewhere in the middle then it has links from page 1 - 4, displays the 4 pages behind the page I am on, 3 after the page I am on and the last 4 pages. Looking like t... | You seem to be using the django-pagination app. It has a setting for the number of items left and right of the current pagePAGINATION_DEFAULT_WINDOW The number of items to the left and to the right of the current page to display (accounting for ellipses).So setting PAGINATION_DEFAULT_WINDOW = 2would set the middle part... |
Save a raw html form django I am trying to save some user data from a raw html form in django.My code looks like this: # This is the view -->if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] age = request.POST['age'] password = request.POST['password'] # Some valid... | I recommend you to follow Django's official documentation - model forms |
maximum recursion depth exceeded when using a class descriptor with get and set I have been playing with my code and I ended up with this:class TestProperty: def __init__(self,func): self.func = func def __set__(self,instance,value): setattr(instance,self.func.__name__,value) def __get__(self,in... | Don't use getattr() and setattr(); you are triggering the descriptor again there! The descriptor handles all access to the TestProp name, using setattr() and getattr() just goes through the same path as p.TestProp would.Set the attribute value directly in the instance.__dict__:def __get__(self,instance,cls): if inst... |
Read innermost value in multiple tuple in python I want to read in the innermost value in tuple.Input - (((False, 2), 2), 2)Output - FalseI want to read only False value. The size of tuple goes vary but I want to read only the most innermost value of innermost tuple directly. | You can flatten the tuple using a generator function and return the first item:from collections import Iterabledef solve(seq): for x in seq: if isinstance(x, Iterable) and not isinstance(x, basestring): for y in solve(x): yield y else: yield x... >>... |
How build two graphs in one figure, module Matplotlib How to build two graphs in one figure from the equations belowy = (x+2)^2y = sin(x/2)^2There is my code:import matplotlib.pyplot as pltimport numpy as npfrom math import siny = lambda x: sin(x / 2) ** 2y1 = lambda x: (x + 2) ** 2fig = plt.subplots()x = np.linspace(-... | Use supplots to make 2 Axes in your Figure:import matplotlib.pyplot as pltimport numpy as npfig, (ax1,ax2) = plt.subplots(nrows=2)x = np.linspace(-3, 3, 100)ax1.plot(x, np.sin(x / 2) ** 2)ax2.plot(x, (x + 2) ** 2) |
Pandas plot multiple series but only showing legend for one series I'm using an ipython notebook (python 2) and am plotting both a barchart and a line plot on the same plot. There are two series (NPS and Count Ratings). However, when I try to display the legend, it only shows a legend for the second series. Below is m... | The following code import numpy as npimport pandas as pdimport matplotlib.pyplot as pltdf=pd.DataFrame({"x" : np.arange(5), "a" : np.exp(np.linspace(3,5,5)), "b" : np.exp(-np.linspace(-1,0.5,5)**2)})ax=df.plot(x="x", y="a", kind='line',color='green',label='NPS')plt.ylabel('Net Promoter S... |
Extract first 3 words from string I am looking for a script code to search for the first 3 words of a string.Example : words = 'I am confused looking for 3 words from the front'Expected results:'I am confused' | You can split the string into a list using the .split() method. Once you've done this you can extract the first 3 words from the sentence using a list slice ([:3]). Finally you'll want to join the result back together into a new string using .join():words = 'I am confused looking for 3 words from the front'' '.join(wor... |
reaching python with R I am trying to install tensorflow in Rstudio, when I run install_tensorflow(), I getError: Prerequisites for installing TensorFlow not available.Execute the following at a terminal to install the prerequisites:$ sudo pip install --upgrade virtualenvBut virtualenv is already installed. I don't kon... | try:install_tensorflow("virtualenv", envname="myenv")this will create a new python virtualenv environment. |
Don't understand error message on SQLalchemy I've got three tables: users, funds, and fund types. Each fund has a fund type, each user has a list of funds, and each user can also have a list of fund types that they have created.Schema:class Fund(Base): __tablename__ = 'fds_funds' fds_fund_id = Column(Integer, pri... | I'm not really sure what fixed it, but I did some rearranging and messing with the references. For posterity, this works:user_funds = Table('usf_user_funds', Base.metadata, Column('usf_usr_user_id', Integer, ForeignKey('usr_users.usr_user_id')), Column('usf_fds_fund_id', Integer, ForeignKey('fds_funds.fds_fund_id... |
django deploying separate web & api endpoints on heroku I have a web application with an associated API and database. I'd like to use the same Django models in the API, but have it served separately by different processes so I can scale it independently. I also don't need the API to serve static assets, or any of the o... | As Daniel said you could just use two settings files, with a shared base. If you want to serve a subset of the urls you should just also create separate url definitions in the ROOT_URLCONF setting. So your project structure would be something like this:project/ project/ settings/ __init__.py ... |
How to import CSV file to django models I have Django models like thisclass Revo(models.Model): SuiteName = models.CharField(max_length=255) Test_Case = models.CharField(max_length=255) FileName = models.CharField(max_length=255) Total_Action = models.CharField(max_length=255) Pass = models.Ch... | You can use the built in csv module to turn your csv file into a dict like object:import csvwith open('import.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: # The header row values become your keys suite_name = row['SuiteName'] test_case = row['Test Case'] # etc.... |
How to get data from pickle files into a pandas dataframe I'm working on a social media sentiment analysis for a class. I have gotten all of the tweets about the Kentucky Derby for a 2 month period saved into pkl files.My question is: how do I get all of these pickle dump files loaded into a dataframe?Here is my code:... | You can use pd.read_pickle(filename)add it to a listthen pd.concat(thelist) |
Attach label information when averaging predictions across users I have 3 datasets that contains predictions, usernames and labels, respectively. Using the code below I average the predictions across users (based on help from Jaime and ali_m from Average using grouping value in another vector (numpy / Python)). The lab... | You can do this by passing return_index=True to np.unique. From the docs:return_index : bool, optionalIf True, also return the indices of ar that result in the unique array.This gives you the set of indices into user_data that give unique values in unq. To get the labels corresponding to each value in unq, you just use... |
Unexplained paramiko error When using ssh with paramiko to execute the command on remote system. When executing it gives errordef execute(self,command): to_exec = self.transport.open_session() to_exec.exec_command(command) stdout.write("\r%s" % "Executed") stdout.flush()get_c... | You haven't got a Transport stream object. Maybe try creating one with self.transport = self.get_transport() like this:def execute(self,command): self.transport = self.get_transport() to_exec = self.transport.open_session() to_exec.exec_command(command) stdout.write("\r%s" % "Executed") ... |
Issue installing Virtualenvwrapper on Ubuntu 18.04? Fresh Ubuntu 18.04 install. Following these instructions here are the commands I've run so far.sudo apt updatesudo apt upgradepython3 -V sudo apt install python3-pipsudo apt install build-essential libssl-dev libffi-dev python3-devsudo apt install python3-venvsource /... | on Ubuntu 18.04 I had to add this to my .bash_profile# virtualenv and virtualenvwrapperexport WORKON_HOME=$HOME/.virtualenvexport VIRTUALENVWRAPPER_LOG_DIR="$WORKON_HOME"export VIRTUALENVWRAPPER_HOOK_DIR="$WORKON_HOME"export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3source ~/.local/bin/virtualenvwrapper.shThen run sourc... |
If I have a starting and an ending IP, how can I find the subnet? I need to block some IPs from some countries but I'm only given the starting IP and the ending IP like this:11.22.33.44 - 11.22.35.200I'd like to calculate the subnet to have it like this:(not accurate)11.22.33.44/14How can I determine the subnet given a... | I haven't spent much time networking recently, but here's how I think you can do this most efficiently.First of all, it's important to recognize that not all IP ranges can be represented as a single subnet. Let's take a look at a common subnet like192.168.0.0/24The /24 indicates that the first 24 bits of 192.168.0.0 gi... |
nested loop to display all data from models django I need to display all data from models in Django I have two list one has all rows and another has all columns, what is want to do something like {{student.username }}I am trying to use nested loop to get all data, I know this "row.{{column}} " is wrong but did not find... | You can query the student and fetch only the required columns using values_list Ex:student = student.objects.values_list('column_1', 'column_2')Then in your template {% for column in student %} <tr> <td>{{ column }} }}</td> </tr> {% endfor %}MoreInfo |
django formset not saving EDIT: Turns out my form was not validating. I added print(formset.errors) as an else in my view, which revealed that I had a required field not being completed.I am trying to manually render formset fields in a template, but the fields are not being saved when I submit. My method works for a ... | Turns out my form was not validating. I added print(formset.errors) as an else in my view, which revealed that I had a required field not being completed. |
How to retrieve data from an irregularly formatted text database in Python? I'm working on code to calculate various thermodynamic properties of a given set of molecules. To do so, I have to plug in 9 coefficients into a set of equations to get the desired values. These coefficients, which vary from molecule to molec... | I'll address the question of extracting the data you want from a record in your text database.Once you find a record you are interested in (if species_name in line:) you need to advance to the seventh and eighth lines of that record and extract the coefficients. The record format indicates that each line is 80 charact... |
Define multiple bluetooth dongles in python-bluez (scan from specific device) I'm building a bluetooth application in Python, using python-bluez (under linux)But my computer has 2 bluetooth adapters (one built in, one usb dongle)How can I choose which one to scan from, because now it randomly picks one.The code right n... | #Automatic selection: nearby_devices = discover_devices(lookup_names=True, device_id=-1) #First adapter nearby_devices = discover_devices(lookup_names=True, device_id=0) #Secon adapter nearby_devices = discover_devices(lookup_names=True, device_id=1) #..etc |
WLST execute stored variable "connect()" statement So, I am passing a environment variable from bash to python;#!/usr/bin/env python2import os#connect("weblogic", "weblogic", url=xxx.xxx.xxx.xxx:xxxx)os.environ['bash_variable']via wlst.sh I can print exported bash_variable, but how do I execute stored variable? Basica... | Question though, why wouldn't you called the script with the variable as an argument and use sys.argv[] ?By example something like this.import osimport sysimport tracebackfrom java.io import *from java.lang import *wlDomain = sys.argv[1]wlDomPath = sys.argv[2]wlNMHost = sys.argv[3]wlNMPort = sys.argv[4]wlDPath="%s/%s" ... |
Can a form class of ModelForm change the attributes? I've read a few posts in StackOverflow about the forms.Form vs forms.ModelForm.It seems that when there is already a table in database for the form, it is better to use ModelForm so that you don't have to declare all the attribute again as they already exist in the c... | It seems like "validation" would be kind of a big answer to 3 - it's usually a major feature of web frameworks. As for not using HTML tags, there's the DRY principle: if you're already defining what the fields of a form are (for validation purposes), why would you have to duplicate that in your templates? Have a single... |
On Windows, running “import tensorflow” generates No module named '_pywrap_tensorflow_internal' error This is a different error than On Windows, running "import tensorflow" generates No module named "_pywrap_tensorflow" error as it points on _pywrap_tensorflow_internal. I also checked and MSVCP140.d... | For cpu I found the solution and it workedRun below command it will clear all dependencies and then update it or remove and install the latest version of tensor flow `pip install tensorflow==1.5` |
Using Python Subprocess module to run a Batch File with more than 10 parameters I'm using this code:test.py:cmd_line = str('C:\mybat.bat') + " "+str('C:\')+" "+str('S:\Test\myexe.exe')+" "+str('var4')+" "+str('var5')+" "+str('var6')+" "+str('var7')+ " "+str('var8') + " "+str('var9')+ " "+ str('var10')process = subproc... | Batch file supports only %1 to %9. To read 10th parameter (and the next and next one) you have to use the command (maybe more times)shiftwhich shifts parameters:10th parameter to %9, %9 to %8, etc.:+--------------+----+----+----+----+----+----+----+----+----+----+------+| Before shift | %0 | %1 | %2 | %3 | %4 | %5 | %6... |
Django CRUD update object with many to one relationship to user I followed along the awesome tutorial How to Implement CRUD Using Ajax and Json by Vitor Freitas. For my project I have an object with a many to one relationship with the user that I want users to be able to add and update. I can add the object, but when... | After a lot of trial and error I found a solution. I had been using inline formsets because I kept finding answers that pointed that direction, but I would rather do it manually if possible and I had been trying, but how I had been doing this did not work in this instance for some reason. I had been trying something ... |
Can I only log when some variable is set to true in python? I want my code to only log debug level messages when some variable is set to true. Is it possible? Here is my config for the logging module. Right now, I have to comment and uncomment at different places in my code to enable or disable the logging...formatter ... | if my_var: logger.setLevel('Warning') check the doc |
How to add duplicates in python text file? I have this text file which is ppe.txt where it contains thisGH,FS,25KH,GL,35GH,FS,35how do I identify GH as they appeared twice and add the values so it becomesGH,FS,60KH,GL,35is it possible to do this? | Open the file for reading. Split each line into 3 tokens. Form a tuple from the first 2 tokens and use that as the key to a dictionary (result). Append the int value of the 3rd token to the value of the tuple/key.Finally, iterate over the dictionary's items and print the result.result = {}with open('ppe.txt') as ppe: ... |
Difference between two types of class properties definition? Is there a difference betweenclass Foo(object): bar = 1 def __init__(self): ... etc.andclass Foo(object): def __init__(self): ... etc.Foo.bar = 1In both cases bar is a property of the class and it is same for all instances of the class, ... | I'd say that the only difference is that in the second case, Foo.bar doesn't exist until the Foo.bar = 1 statement is executed while in the first case is already available when the class object is created.That's probably a small difference without any effect in your code (unless there is some code that requires Foo.bar... |
How to delete rows using a key word from columns in Pandas How we can delete the whole row taking a keyword in any column of that row? I have 250 such rows and 28 columns and I want to delete all rows having "income" as a key string in any column from a data frame using pandas | Say for instance you wanted to drop any row that had 'c' in a columnIn [5]: import pandas as pdIn [7]: data = [['a', 'b'], ['a', 'c'], ['c', 'd']] df = pd.DataFrame(data, columns=['col1', 'col2'])In [9]: dfOut[9]: col1 col20 a b1 a c2 c dIn [10]: df.loc[~(df == 'c').sum(axis=1).astype(bool)]Ou... |
How to split by newline and ignore blank lines using regex? Lets say I have this datadata = '''a, b, cd, e, fg. h, i j, k , l'''4th line contains one single space, 6th and 7th line does not contain any space, just a blank new line.Now when I split the same using splitlinesdata.splitlines()I get['a, b, c', 'd, e, f', '... | List comprehension approachYou can add elements to your list if they are not empty strings or whitespace ones with a condition check.If the element/line is True after stripping it from whitespaces, then it is different from an empty string, thus you add it to your list.filtered_data = [el for el in data.splitlines() if... |
How to get a text from html using Selenium WebDriver with python-Using CSS selector Anyone know how to get the text from the below html code. Just I need '383' as a text by using CSS selector from the below html.<td align="right" style="background-color: rgb(147, 191, 179); color: rgb(255, 255, 255);&... | First start the webdriverfrom selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.chrome.service import Serviceyour_chromedriver_path = '...'driver = webdriver.Chrome(service=Service(your_chromedriver_path))then load the webpageurl = '...'driver.get(url)then find the td elementtd... |
How to parse Python files to see if they are compatible with Python 3.7 I am currently deploying some code on a fleet of raspberry pi systems. The systems all have python 3.7.x installed but one of my team's custom libraries has some python 3.8 features (a few walrus operators, etc). I need to modify my library to remo... | Run a static analysis tool, like pylint or mypy, and make sure that it's running on the appropriate version of Python. One of the first things these tools do is parse the code using the Python parser, and they'll report any SyntaxErrors they find. |
Resize Image before Upload to Google App engine I would like to be able resize an image blob before I save it to a database with google app engine from google.appengine.api import imagesfrom google.appengine.ext import blobstorefrom google.appengine.ext.webapp import blobstore_handlersfrom google.appengine.ext import d... | now blobstore support write file directlyhttps://developers.google.com/appengine/docs/python/blobstore/overview#Writing_Files_to_the_Blobstoreso you can have something like this.# resize your img# create filefile_name = files.blobstore.create(mime_type='application/octet-stream')with files.open(file_name, 'a') as f: ... |
Byte Code File for Python I am unable to see Compiled Python File (Byte Code) on my hard drive.I can only see script file with py extension but no Compiled file with pyc extensionI have Windows 7 OS installed. | Only imported modules get a byte-code cache, a .pyc file. For the main script file, the one you run first, no byte cache file is created.Bytecode cache files are only created if Python has write access to the file system.For Python 3.2 newer, these bytecode files have been moved to a subdirectory called __pycache__, se... |
Two 'for' loops at once in python Say I'm iterating through a list in python:lines = [1, 2, 3, 4]linecount = len(lines)#I want to be able to do this:for i, j in range(linecount - 1, -1, -1), range(linecount, -1, -1): print i, j"""This would print out3 42 31 20 10 0"""How could I go about doing this? | for i, j in zip(range(linecount - 1, -1, -1), range(linecount, -1, -1)): print i, j |
wxpython ProgressDialog segmentation fault (lin, not win) Up until recently, a code I have been working on and running in both Windows (8) and Linux (XUbuntu 14.04) environments started to give segmentation faults upon creating a wx ProgressDialog, but only on the latter platform. This minimal code sample illustrates t... | The call to Pulse() does seem to cause it to break on my system as well. I am using wxPython 2.8.12.1 with Python 2.7 on Xubuntu 14.04. If I swap out Pulse for Update, it works fine:import wximport timeclass MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, 'test ', pos=(... |
acess class attribute in another file I'm new to python.I have a question about accessing attribute in classt1.py#!/usr/bin/pythonimport t2class A: flag = Falseif __name__ == "__main__": t2.f() print(A.flag)t2.py#!/usr/bin/pythonimport t1def f(): t1.A.flag = True print(t1.A.flag)excut... | When you do./t1.pyyou're executing the t1.py file, but it's not executed as the t1 module. It's considered to be the __main__ module. (This is what that if __name__ == '__main__' line checks for.) That means that when this line:import t1in t2.py tries to import t1, Python starts executing the t1.py file again to create... |
Error running tests with Conda and Tox I am having trouble running tests with Tox while having virtual environments created with Conda. The steps to reproduce the error are below.Download the repository (it is small) and cd to it:git clone https://github.com/opensistemas-hub/osbrain.gitcd osbrainCreate the virtual envi... | I managed to work around this by installing virtualenv through conda:conda install virtualenvIt's not recommended to use virtualenv yourself (stick with conda environments). However, when tox looks for the package internally it will at least find a compatible version. |
django.db.migrations.exceptions.CircularDependencyError I have a problem with Django migrations on empty DB. When I want to migrate I have a circular dependency error. Circular dependency error between two apps that related by foreign keys/firstapp/models.py class Person(models.Model): ...class Doctor(Person): h... | Temporarily comment out foreign keys to break the circular dependency. It looks like you could do this by commenting out Hospital.doctor. Remove the existing migrations and run makemigrations to recreate them.Finally, uncomment the foreign keys, and run makemigrations again. You should end up with migrations without an... |
Stacking different types of arrays in numpy I'm having difficulties in stacking different "types" of numpy arrays. array_1 is array([(3,111),(3,222)])array_2 is array([(4,111),(4,222)])array_3 is array([[5,111],[5,222]])(notice the change in brackets in array_3). I can easily use np.hstack to combine array_1 and array_... | convert every array to numpy array and then use np.hstackarray_1 = np.array([(3,111),(3,222)])array_2 = np.array([(4,111),(4,222)])array_3 = np.array([[5,111],[5,222]])np.hstack((array_1,array_2,array_3))I got the following output array([[ 3, 111, 4, 111, 5, 111], [ 3, 222, 4, 222, 5, 222]]) |
Python ord() equivalent in NumPy In Python, to get the ASCII value of a character we can do:>>> x = ord('k')>>> x107What is the equivalent Python "ord" method in NumPy? I see some solutions say to do hacks like list comprehension before passing it NumPy. However, I want a NumPy method to do ... | numpy.ndarray.view returns a view of the same array with another (equally sized) datatype, and should due to not copying anything pretty much be instantaneous.>>> x = np.array(['g', 'h', 'i', 'j'])>>> xarray(['g', 'h', 'i', 'j'], dtype='<U1')>>> y = x.view(np.int32)>>> yarray([103... |
Python - Trying to use a list value in an IF statment I need to ask a user to input a question that will be compared to a list. The matched word will be displayed and then linked to an option menu. I have added the code below. I have managed to get the the program to search the input and return the word in the find lis... | If what you are trying to achieve is given the user input, whether any of the words in the user given by the user is also present in find list. Then you should just check whether the result list is empty or not. If the result list is empty, that means that none of the words in find were present in the list words . Exa... |
Python: Removing all words that start with a Capital Letter and does not arise after punctuation I want to use regex to remove all words from a text that start with a capital Letter and satisfies these two conditions:1) They are followed by only lower case letters or " 's" (possessive) or punctuation (.,?!). 2) They do... | To remove whole words, you want to use \b boundary anchors, so that you don't match a partial word. To remove words that are preceded by punctuation, you can use a negative lookbehind, provided that there is always a fixed amount of whitespace between the punctuation and the first letter.I'm going to assume that there ... |
Parse Apache log with Python 2.7 I'm trying to read a log file from a github url, add some geographic info using the IP as a lookup key, and then write some log info and the geographic info to a file. I've got the reading from and writing to file from the log, but I'm not sure what lib to use for looking up coordinates... | The re module isn't deprecated, and is part of the standard library. Edit: here's the link for the 2.7 moduleYour for loop is opening and closing the file at each iteration. Probably not a big deal but it might be faster for large files to open the file once and write what needs to be written. Just swap the locations o... |
Boto error in Scrapy: "The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256." I'm trying to crawl the following spider:import scrapyfrom tutorial.items import QuoteItemclass QuotesSpider(scrapy.Spider): name = "quotes" custom_settings = { 'FEED_URI': 's... | One solution involves changing the host argument in boto's connect_to_region.Storage backend for exporting to S3 is handled by scrapy.extensions.feedexport.S3FeedStorageYou may subclass that S3FeedStorage class and implement your own one, which resolves the issue of unmatched S3 bucket auth mechanism.You'll also need... |
Python - language-check 1.0 Can anyone please let me know why my code is not providing the correct output.My code:import language_checktool = language_check.LanguageTool('en-US')text='this are bad'matches = tool.check(text)t=len(matches)for i in range(0,t): print(matches[i].ruleId,matches[i].replacements)new=languag... | Could you be using an old version of LanguageTool? I have installed language_check with Python 3.6.1 just to test your code and it gave me the output "these are bad".Edit: Precisely, that's what I get on output with exact same code:THIS_NNS ['these']these are bad |
protocol buffer different languages I'm trying to read a protocol buffer file in Python that was written with Java and I am having issues as i get this error when calling ParseFromString(). File "build/bdist.linux-x86_64/egg/google/protobuf/message.py", line 182, in ParseFromString File "build/bdist.linux-x86_64/egg/... | What is written in the link you post is true, you have to make some sort of delimiter to know where messages start and end. It is also up to you to handle this before pushing the data to the decoder. |
Python - Different ways of printing? I've installed PyDev into Eclipse, and when I do the print method in a .py file as print "Hello World" it didn't work. But then I did print ("Hello World") and it worked. I looked on the internet and everything says to do it without parentheses, but it doesn't work, and gives the er... | You appear to be using Python 3.In Python 2 print was a keyword and the parentheses were not required.In Python 3 print was changed to be a function. When calling a function the parentheses are required. RelatedWhat's New in Python 3 |
Delete all .py files which dont have a corresponding .pyc file We want to ship a smaller chunk of python distribution to the customer.So, the idea here is to use the existing python distribution in our application and to do all possible tests. This will make sure that the .pyc files are created only for those .py files... | Python script that should do the job, but I'd be curious to know if Python will still work after running it.import ospyc_files = []py_files = []for root, dirnames, filenames in os.walk('.'): for filename in filenames: if filename.endswith('.pyc'): pyc_files.append(os.path.join(root, filename)) ... |
Python module Installing I wrote this command to install NLTK python module :sudo pip install -U nltkThe first time it seemed to work well but when I wanted to test it, it didn't. So I re-wrote the command and then I gotThe directory '/Users/apple/Library/Caches/pip/http' or its parent directory is not owned by the cur... | You'll want to create a virtualenv to install Python packages. This prevents the need to install them globally on the machine (and generally makes installing modules less painful). We'll also include virtualenvwrapper to make things easier.The steps are to install virtualenv and virtualenvwrapper with pip:pip install v... |
Python 2: adding integers in a FOR loop I am working on lab in class and came across this problem:Write a program using a for statement as a counting loop that adds up integers that the user enters. First the program asks how many numbers will be added up. Then the program prompts the user for each number. Finally it p... | I think this is what you're asking: Write, using a for loop, a program that will ask the user how many numbers they want to add up. Then it will ask them this amount of times for a number which will be added to a total. This will then be printed.If this is the case, then I believe you just need to ask the user for this... |
calling third party c functions from python I have a requirement of calling third party c functions from inside python.To do this I created a c api which has all the python specific c code ( using METH_VARARGS) to call the third party functions. I linked this code liba.so with the 3 party library libb.soIn my python fi... | You have to include liba.so in your PATH, otherwise Python won't know where to look for it.Try the following code, it'll load the library if it can find it from PATH, otherwise it'll try loading it from the directory of the load scriptfrom ctypes import *from ctypes.util import find_libraryimport osif find_library('a')... |
What does next mean here? Python Instagram API I'm trying to use the Python Instagram API and came across a sample code on its github documentation that I don't understand.In the fifth line, why do we put next? What is next doing?Why aren't we allowed to simply write recent_media = api.user_recent_media(user_ir)?from i... | The second parameter is for pagination. The API call gives you the first "page" of results, and if you want more results you need to get subsequent "pages". If you want to retrieve as many images as possible, and end up with the list of media objects in recent_media, you can do something like:recent_media, next = self.... |
Why does this pattern not match? Using this pattern:(?<=\(\\\\).*(?=\)) and this subject string: '(\\Drafts) "/" "&g0l6P3ux-"' I was expecting to match DraftsHowever, it is not working. Can someone explain why?I am using re module in Python,the following is what I did:>>> pattern = re.compile("(?<=\(... | match.groups() is empty because your pattern does not define any capturing groups. match.group(0) is the complete match, while match.group(1) would be the first capturing group if there was one.To improve readability you should express regex patterns as raw strings. Yours can be written as r"(?<=\(\\).*?(?=\))"To br... |
pygtk custom widgets displaying in separate window I'm having trouble with custom widgets showing up in a separate window. Separate window not in the sense of all widgets being in a window, but they all come up separately with their own window decorations. I'm not sure where the problem would be, but I guessed it might... | Instead of calling do_realize in __init__, I should be calling queue_draw. I got help on the pygtk irc. |
Trie (Prefix Tree) in Python I don't know if this is the place to ask about algorithms. But let's see if I get any answers ... :)If anything is unclear I'm very happy to clarify things.I just implemented a Trie in python. However, one bit seemed to be more complicated than it ought to (as someone who loves simplicity).... | At a glance, it sounds like you've implemented a Patricia Trie. This approach also is called path compression in some of the literature. There should be copies of that paper that aren't behind the ACM paywall, which will include an insertion algorithm.There's also another compression method you may want to look at: lev... |
Benefit of using threads/Threading module python 2.7 1) I have read that if I import the threading module in python, CPU bound loads won't see much benefit from using this library because the GIL forces threads to run 1 at a time even if I run code on a multi-core machine. If this is the case what sort of code would b... | Even with the GIL, threading in Python is useful because input/output operations don't block the program. You can perform operations while waiting for the completion of a disk operation or while waiting for a network event.Threads also play a role in GUI applications, where a program can stay responsive to user input w... |
PyQt: QListView drag and drop reordering signal issue I'm having a bit of trouble implementing drag and drop reordering using a QListView and QStandardItemModel. Using the itemChanged signal for processing checked items is fine however when the items are reordered using drag and drop there seems to be a temporary item ... | Update, I found a workaround on this and it involves using a singleshot timer. After dropping an item in the list, the timer fires the slot and it finds 5 items in the new order instead of 6.import sysfrom PyQt4.QtGui import *from PyQt4.QtCore import *if __name__ == '__main__': app = QApplication(sys.argv) # Our ... |
Access ansible playbook results after run of playbook I am running an ansible script using ansible-pull on a remote machine(client side) which I can't see . I want to make sure that : ansible playbook are executed successfully then should send summary ansible playbook if not executed successfully should send summary ... | AFAIK there is no variable where you could just get this data from.But this screams for a callback plugin. Have a look at the plugin log_plays. It writes its own logfile. You could intercept all the messages, collect them and at the end (define a method def playbook_on_stats(self, stats): in your plugin) do with it wha... |
Python: Accessing list as it is comprehended Is there a way to access the list as it is comprehended? In particular I'd like to iterate once again over elements already added.for example, im looking for something like this:[x for x in range(foo) if x not in self]or[x for x in range(foo) if any(y for y in self)]where se... | In short: No. You cannot do this. Python's list comprehensions (and related constructs like generator expressions) are not as powerful as Haskell's lazy lists (which could do what you want). The syntax is similar, but Python is not pure a functional language with lazy, recursive evaluation as a syntax feature; its inte... |
List index out of range in loop with condition n = input("How many average temperatures do you want to put in?" + "\n").strip()temperatures = []differences = []diff = 0print('')if int(n) > 0 : for x in range (int(n)): temp = input("Input a average temperature: " + "\n").strip() temperatures.append(i... | Here's the problem:diff = temperatures[y+1] - temperatures[y]When y reaches the last valid index in temperatures, the expression y+1 will result in an index outside of the list, causing the error. Define the loop like this instead:for y in range(len(temperatures)-1): diff = temperatures[y+1] - temperatures[y] dif... |
Python - Checking concordance between two huge text files So, this one has been giving me a hard time!I am working with HUGE text files, and by huge I mean 100Gb+. Specifically, they are in the fastq format. This format is used for DNA sequencing data, and consists of records of four lines, something like this:@REC1GAT... | Sampling is one approach, but you're relying on luck. Also, Python is the wrong tool for this job. You can do things differently and calculate an exact answer in a still reasonably efficient way, using standard Unix command-line tools:Linearize your FASTQ records: replace the newlines in the first three lines with tabs... |
How to set loss weight in chainer? First of all I narrate you about my question and situation.I want to do multi-label classification in chainer and my class imbalance problem is very serious.In this cases I must slice the vector inorder to calculate loss function, For example, In multi-label classification, ground tru... | If you work on multi-label classification, how about using softmax_crossentropy loss?softmax_crossentropy can take into account the class imbalance by specifying the class_weight attribute.https://github.com/chainer/chainer/blob/v3.0.0rc1/chainer/functions/loss/softmax_cross_entropy.py#L57https://docs.chainer.org/en/st... |
Downloading Image Data URIs from Webpages via BeautifulSoup I need to retrieve an image from a website using Python. However, the image is not in the form of a linked file, but as a GIF Data URI. How do I download this and store it in a .gif file? | This should get you going in the correct direction.First, I'll assume you have retrieved the image uri data and it is saved in a python variable called img_data:# Exampleimg_data = 'data:image/jpeg;base64,/9j/4A...<lots of data>...k='Now you'll need to decode the picture from base64 and save it to a file:import b... |
Import Tensorflow without NVIDIA GPU (ImportError: Could not find 'nvcuda.dll') I have installed the tensorflow package using Anaconda Navigator. When I try to run import tensorflow in a jupyter notebook I get the following error: OSError Traceback (most recent call last)D:\ProgrammF... | As discussed in the comments, the problem was only in your installation. Using anaconda-navigator isn't the best way to install tensorflow. My assumption is either tensorflow-base or tensorflow-estimate has a GPU dependency which is the reason why it kept showing the posted error message. The best way to install tensor... |
ffmpeg python subprocess error only on ubuntu Im working on an application that is splitting videos from youtube into images. I work on a macbook pro for development, but our app servers run on an ubuntu 12.04 server. The current code on our servers running right now is the followingffmpeg -i {video_file} -vf fps={fps}... | The problem is the range notation {0..3}, which works in bash but not in other shells. While the normal login shell on my Ubuntu system is bash, subprocess.Popen() with shell=True calls /bin/sh, which in my case is not bash but dash, which does not support brace expansion.Since the range is not expanded, the loop runs ... |
How can i properly change the keys name in my dict? trying to change my dictionary keys name using this code :for key in my_dict_other: new_key = key + '/' + str(my_dict[key]) # new_key = key + '/' + str(my_dict[key][0][0]) + '-' + str(my_dict[key][0][1]) my_dict_other[new_key] = my_dict_other.pop(key)however ... | This might work:import rekey = "9-9/[['2550', '1651']]/[]"newkey = re.sub("[\[\]']", "", key.replace("/[]", ""))# '9-9/2550, 1651' |
How do we handle Python xmlrpclib Connection Refused? I don't know what the heck I'm doing wrong here, I wrote have an RPC client trying to connect to a non-existent server, and I'm trying to handle the exception that is thrown, but no matter what I try I can't figure out how I'm supposed to handle this:def _get_rpc():... | _get_rpc returns a reference to unconnected ServerProxy's supervisor method. The exception isn't happening in the call to _get_rpc where you handle it; it's happening when you try to evaluate this supervisor method (in "if not rpc"). Try from the interactive prompt:Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC ... |
Importing a txt to MySQL with different date format What I want to do is transfer the "12/26/17 14:30" in txt to "2017-12-26 14:30:00 " in MySQL I've already tried this Importing a CSV to MySQL with different date format0So my code looks like this create_tb_str = r'''DROP TABLE IF EXISTS TABLENAME; CREATE TABL... | STR_TO_DATE(@time,'%y-%m-%d %H:%i:%S'); is returning null as it's not matching the string input pattern.Try something like this instead: STR_TO_DATE('12/26/17 14:30','%m/%d/%y %k:%i'); After extracting in DATE, convert it to your desired Date format.To do in single step, you can also try: "SELECT CONVERT(datetime, '12/... |
How to Validate a MD5 Hash Being Posted From a Python Script in Laravel Ok , so I have a python script that will register a new user in Laravel if the provided login fails. In the python script I am passing the following:import hashlib import strftimehashedMessage = hashlib.md5()hashedMessage.update("Password"+strftime... | For md5 you can do something as simple as:if (request()->input('hashed_message') === md5('Password+' . now()->format('m/d/Y-H:m'))) { // match}This will fail, however, if the request is sent at the minute boundary - i.e. sent at 3:01:59 but received at 3:02:00. |
XML to XML in Python The xml file contains many datas including some invoices. I would like to extract only the invoices from the xml file and create a new xml file that only contains the invoices.I wrote a code that extract the invoices but when it comes to create a new xml file (with invoices) it only contains one in... | If you want a well-formatted XML you will need a root element in your document, then you can add all your elements to the root and save to your file.root = ET.Element('root')root.extend(doc.findall('bizonylat'))ET.ElementTree(root).write('out.xml', 'utf8') |
Add an element to a list base on the value of the list (python) So I have a list of x elements as such:list = ['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009']If a element is removed (ex: '0004'):['0001', '0002', '0003', '0005', '0006', '0007', '0008', '0009']How can I add an element base on the ... | You can just create a zero padded value adding 1 to to the numeric value at last using str.zfill, then append to the list:lst = ['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009']print(lst.pop(3))val = str(int(lst[-1])+1).zfill(4)lst.append(val)print(lst)OUTPUT:0004['0001', '0002', '0003', '0005', ... |
Python 3: List inside dictionary, list index out of range I have created a dictionary where the entries are lists like this:new_dict{0: ['p1', 'R', 'p2', 'S'], 1: ['p3', 'R', 'p4', 'P'], 2: ['p5', 'R', 'p6', 'S'], 3: ['p7', 'R', 'p8', 'R'], 4: ['p9', 'P', 'p10', 'S'], 5: ['p11', 'R', 'p12', 'S'], 6: ['p13', 'S', 'p14... | Notice that in the first interation of your nested loop, we see the following values that are both in Moves:>>>new_dict[0][1], new_dict[0][3] ('R', 'S')However, on your second iteration in the nested loop, you are trying to evaluate terms that are not included in the dictionary:>>>new_dict[1][5], new_... |
finding the missing value for ValueError: need more than X values to unpack I have a function call that looks like this:a,b,c,x,y,z = generatevalues(q)Its in a try block to catch the error but I also need to find out which value is missing. I can't clear the variables beforehand either. I'd also rather not merge the 6 ... | values = tuple(generatevalues(q))try: a, b, c, x, y, z = valuesexcept ValueError as e: print(len(values)) # for example print(values)To debug this function - it's a good time to learn about the debuggervalues = tuple(generatevalues(q))try: a, b, c, x, y, z = valuesexcept ValueError as e: import pdb; pdb.... |
Does retrbinary() and storbinary() in ftplib raise exception if transfer not successful? Do the retrbinary() and storbinary() functions in ftplib raise exceptions if transfer not successful (or do I need to explicitly check for this)?Eg. I currently have code that does...ftp = ftplib.FTP(<all the connection info>... | Yes, they will throw an exception, if they get an error response from the server or if the connection is lost unexpectedly.Though note that with FTP protocol, in some cases, it's not always possible to tell that the transfer has failed. |
Randomly distribute people into groups based on condition I have a list of people with their departments. I'm trying to distribute them into groups of equal size with the condition that they are not with people from their own departments where possible. I've got a list of 417 people with 19 departments and trying to pu... | Since you already have them sorted by department, with numeric "names", the solution is short.df.groupby(int("Name")%10)If my pre-conditions are wrong, then sort your DF by department, and then distribute by row instead of the numeric name. |
Matplotlib: Secondary axis with values mapped from primary axis I have a graph showing x4 vs y: y is the log of some other variable, say q (i.e. y = log(q) )the value of q is what the layperson will understand when reading this graph.I want to set up a secondary axis on the right side of the graph, where the lines are ... | You can use a twin axis. The idea is following:Create a twin axis and plot the same data on both the axis. This will make sure that the tick positions are axis limits are same on both y-axis.Get the tick labels which are strings, convert them to integers and take their exponent using np.exp() rounding them up to 2 deci... |
How do I make it print the dice of a certain number in a list? How do I make my code print out the dice image according to the random dice it rolled? This is the code that I have so far whhich roll the dice according to what the user input and the value will be stored in the result list. how can i print the dice image ... | I highly encourage you to do (or perhaps continue) a beginners course of python. That being said:for n in result: for line in die_art[n]: print(line) print("\n") |
Splitting Dataset over Multiple GPUs I'm training a large network that inputs and outputs 512x512 images. At the moment, I have 2 Tesla A100 GPUs with 40 GB of memory each, and a dataset comprising 10,000 input and outputs pairs. This adds up to roughly 38 GB of training data, which leads me to run out of memory when s... | Here is my solution. Open to others, especially more memory-efficient options!to_t = lambda array: torch.tensor(array, device=device)class CustomDataset(Dataset):def __init__(self, image, label): self.image = image self.label = labeldef __len__(self): return len(self.label)def __getitem__(self, idx): image ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.