questions stringlengths 50 48.9k | answers stringlengths 0 58.3k |
|---|---|
Increase a variable up to a maximum size I'm working on a simple game that you put the number of enemies and you hit them or cure yourself. But, the player has a maximum amount of 500 of life. The cure uses random.randint(10,14).if player_sp >= 10: if player_vida < 500: cura = random.randint(10,14) ... | How about replacing:player_vida += curawith:player_vida = min(500, player_vida + cura) |
How to create a data structure in a Python class class CD(object): def __init__(self,id,name,singer): self._id = id self.n = name self.s = singer def get_info(self): info = 'self._id'+':'+ ' self.n' +' self.s' return infoclass coll... | You can use simple loop with enumerate for this.# I don't know what you mean by 'file has list of tuples',# so I assume you loaded it somehowtuples = [("Shape of you", "Ed Sheeran"), ("Shape of you", "Ed Sheeran"), ("I don't wanna live forever", "Zayn/Taylor Swift"), ("Fake Love", "Drake"), ("Starboy"... |
Memory leak using fipy with trilinos I am currently trying to simulate a suspension flowing around a cylindrical obstacle using fipy. Because I'm using fine mesh and my equations are quite complicated, the simulations take quite a long time to converge. Which is why I want to run them in parallel. However, when I do th... | This is an issue we have reported against PyTrilinos |
My Tensorflow lite model accuracy and Image Classification issues First off, I've succeed in deploying my fine tuned Xception model to my android application, it working fine, except some harsh image that it predicted wrong, however, on my computer, with that image, it's predicted correct even though the accuracy was a... | Conversion to TensorFlow Lite is expected to reduce accuracy, especially for outlier inputs such as the one you describe.If you provide an input from a class that the model was not trained on, the output is 'undefined' - the logits will essentially be garbage.If you want a model that has more labels than the one you ha... |
How do you get a field related by OneToOneField and ManyToManyField in Django? How do you get a field related by OneToOneField and ManyToManyField in Django?For example,class A(models.Model): myfield = models.CharField() as = models.ManyToManyField('self')class B(models.Model): a = models.OneToOneField(A)If I ... | Models.pyclass Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def __str__(self): # __unicode__ on Python 2 return "%s the place" % self.nameclass Restaurant(models.Model): place = models.OneToOneField( Place, on_delete=... |
SWF file loads a new url, how to grab it using Python? I'll start with saying I'm not very familiar with AS3 coding at all, which I'm pretty sure SWF files are coded with (someone can correct me if I'm wrong)I have a SWF file which accepts an ID parameter, within the code it takes the ID and performs some hash routines... | Looks like I was making things too complicatedI was able to just use python hashlib.md5 to produce the same results as the AS3 codem = hashlib.md5()m.update('test')m.hexdigest() |
Why the two threading implementation behaves differently? Why the two threading implementations in python are behaving differently ?I have two codes:1.from threading import Threadimport pdbimport timedef test_var_kwargs(**kwargs): time.sleep(5) print kwargs['name'] for key in kwargs: print "another keyword arg: %... | It took me a little while to figure the problem out... This line:thr = Thread(target=test_var_kwargs(name='xyz', roll=12))Is incorrect. Try:thr = Thread(target=test_var_kwargs, kwargs={'name':'xyz', 'roll': 12})The first example is blocking on the 5 seconds time.sleep because you are calling the target function just be... |
Selecting Rows with DateTimeIndex without referring to date Is there a way to select rows with a DateTimeIndex without referring to the date as such e.g. selecting row index 2 (the usual Python default manner) rather than "1995-02-02"?Thanks in advance. | Yes, you can use .iloc, the positional indexer:df.iloc[2]Basically, it indexes by actual position starting from 0 to len(df), allowing slicing too:df.iloc[2:5]It also works for columns (by position, again):df.iloc[:, 0] # All rows, first columndf.iloc[0:2, 0:2] # First 2 rows, first 2 columns |
How to fix the false positives rate of a linear SVM? I am an SVM newbie and this is my use case: I have a lot of unbalanced data to be binary classified using a linear SVM. I need to fix the false positives rate at certain values and measure the corresponding false negatives for each value. I am using something like th... | The class_weights parameter allows you to push this false positive rate up or down. Let me use an everyday example to illustrate how this work. Suppose you own a night club, and you operate under two constraints:You want as many people as possible to enter the club (paying customers)You do not want any underage people ... |
Python - Split PDF based on list I'm trying to split a PDF into separate PDF files into new files based on a list. Code as follows:import sysimport osfrom PyPDF2 import PdfFileReader, PdfFileWriterdef splitByStudent(file, group): inputPdf = PdfFileReader(open(file,"rb")) output = PdfFileWriter() path = os.path... | The line output = PdfFileWriter() should be inside the for loop:def splitByStudent(file, group): inputPdf = PdfFileReader(open(file,"rb")) path = os.path.dirname(os.path.abspath(file)) os.chdir(path) numpages = int(inputPdf.numPages/len(group)) for s in group: output = PdfFileWriter() start... |
How to find the rows having values between -1 and 1 in a given numpy 2D-array? I have a np.array of shape (15,3).final_vals = array([[ 37, -84, -143], [ 29, 2, -2], [ -18, -2, 0], [ -3, 6, 0], [ 361, -5, 2], [ -23, 4, 8], [ 0, -1, 0], [ -1... | You could take the absolute value of all elements, and check which rows's elements are smaller or equal to 1. Then use np.flatnonzero to find the indices where all columns fullfil the condition:np.flatnonzero((np.abs(final_vals) <= 1).all(axis=1)) Output array([6, 7], dtype=int64) |
From JSON to JSON-LD without changing the source There are 'duplicates' to my question but they don't answer my question.Considering the following JSON-LD example as described in paragraph 6.13 - Named Graphs from http://www.w3.org/TR/json-ld/:{ "@context": { "generatedAt": { "@id": "http://www.w3.org/ns/prov#... | No, unfortunately that's not possible. There exist, however, libraries and tools that have been created exactly for that reason. JSON-LD Macros is such a library. It allows declarative transformations of JSON objects to make them usable as JSON-LD. So, effectively, all you need is a very thin layer on top of an off-the... |
What is the best manner to run many Scrapy with multiprocessing? currently I use Scrapy with multiprocessing. I made a POC, in order to run many spider.My code look like that:#!/usr/bin/python # -*- coding: utf-8 -*-from multiprocessing import Lock, Process, Queue, current_processdef worker(work_queue, done_queue): ... | It would be better to launch a Scrapy instance for each URL or launch a spider with x URL (ex: 1 spider with 100 links) ?Launching an instance of Scrapy is definitely a bad choice, because for every URL you would be suffering from the overhead of Scrapy itself.I think it would be best to distribute URLs evenly across... |
Appending and formatting a new SubElement via ElementTree Using the following code, I can successfully add a subElement where I want, and functionally it works. For readability, I want to format the way item.append inserts the new sub elements.My Code:import xml.etree.ElementTree as ETtree = ET.parse(file.xml)root = tr... | Consider using .find() to walk down to your needed node and then simply use SubElement to add. No need for string versions of markup when working with DOM libraries like etree:import xml.etree.ElementTree as ETtree = ET.parse("input.xml")root = tree.getroot()while True: item_add = input("Enter item to add: ") if ... |
Is there a way to make a function run after a specified amount of time in Python without the after method? I am trying to create a simple program that tracks a user's clicks per second in Tkinter, but I have no idea how to make the program wait without freezing the program using the after method. The problem is that I ... | Give it a tryfrom tkinter import *root = Tk()root.geometry('600x410')screen = Canvas(root)h = 6 # button heightw = 12 # button widthc = 0 # counts amount of times clickedstart_btn = 0 # logs clicks of the start buttonhigh_score = 0 # logs the highest scoretime = 0def count_hs(): global high_score if c > h... |
Creating Lexicon and Scanner in Python I'm new here in the world of coding and I haven't received a very warm welcome. I've been trying to learn python via the online tutorial http://learnpythonthehardway.org/book/. I've been able to struggle my way through the book up until exercise 48 & 49. That's where he turn... | I wouldn't use a list to make the lexicon. You're mapping words to their types, so make a dictionary.Here's the biggest hint that I can give without writing the entire thing:lexicon = { 'north': 'directions', 'south': 'directions', 'east': 'directions', 'west': 'directions', 'go': 'verbs', 'stop': 've... |
Removing rows that are similar in Python My data looks something like this: Source Target Value1 Charlie Mac 0.65309452 Dennis Fank 0.72962343 Charlie Frank 0.47508754 Mac Dennis 0.39617875 Charlie Dennis 0.62137516 Mac Frank 0.97274547 Frank Charlie 0.47508758 Mac Charlie 0.... | df[~pd.DataFrame(np.sort(df[['Source', 'Target']], 1), df.index).duplicated()] Source Target Value1 Charlie Mac 0.6530952 Dennis Frank 0.7296233 Charlie Frank 0.4750874 Mac Dennis 0.3961795 Charlie Dennis 0.6213756 Mac Frank 0.972745 |
Pandas - moving average grouped by multiple columns New to Pandas, so bear with me.My dataframe is of the formatdate,name,country,tag,cat,score2017-05-21,X,US,free,4,0.05732017-05-22,X,US,free,4,0.06262017-05-23,X,US,free,4,0.05842017-05-24,X,US,free,4,0.05632017-05-21,X,MX,free,4,0.05372017-05-22,X,MX,free,4,0.0640201... | IIUC:(df.assign(moving_score=df.groupby(['name','country','tag'], as_index=False)[['score']] .rolling(2, min_periods=2).mean().fillna(0) .reset_index(0, drop=True)))Output: date name country tag cat score moving_score0 2017-05-21 X US free 4... |
Find a word in a line no matter how it's written I'm trying to find a word in a simple string no matter how it's written. For example:'Lorem ipsum dolor sit amet lorem.'Let's say I search for 'lorem' written in lowercase and I'd like to replace both 'lorem' and 'Lorem' with 'example'.The thing is, I want to search and ... | import resentence = "Lorem ipsum dolor sit amet lorem."search_key = "Lorem"print(re.sub(r'%s' % search_key.lower(), 'example', sentence.lower()))>>> example ipsum dolor sit amet example. |
How can I pass JSON of flask to Javascript I have an index page, which contains a form, fill in the form and sends the data to a URL, which captures the input, and does the search in the database, returning a JSON.How do I get this JSON, and put it on another HTML page using Javascript?Form of index:<form action="{{... | Your HTML page after you submit the form. let's call it response.html<!DOCTYPE html><html><head> <title>hello</title></head><body> <p id="test"></p> <p id="test1"></p> <script> var b = JSON.parse('{{ a | tojson | safe}}'); ... |
Is subclasing django base classes to intermediate ones a bad idea? I have subclassed ModelForm to an intermediate ModelForm2 to make sure some form elements have certain css classes / widgets and to remove the label suffix.My question is:Is this a bad idea since it makes the code less portable in case they drop ModelFo... | No, this is not a bad idea, this is very normal 'best practice' Django.ModelForm is a core part of Django, it is pretty unthinkable they would drop it.Typical Django project will have many sub-classes from Django base classes.I will often have an app in my project I call core, or something similar, where I keep some cl... |
What is the meaning of `[[[1,2],[3,4]],[[5,6],[7,8]]]` in Python? x=[[[1,2],[3,4]],[[5,6],[7,8]]]print(x[1][0][1])could you please tell me the output and how's it obtained | list[i] takes the (i+1)-th element of the list, so [0] means the first element and [1] the second element from the list. Counting in computer science always starts at 0.x[1] = [[5,6],[7,8]]x[1][0] = [5,6]x[1][0][1] = 6 |
How to convert dictionary of tuple coordinates keys to sparse matrix I stored the non-zero values of a sparse matrix in a dictionary. How would I this into an actual matrix?def sparse_matrix(density,order): import random matrix = {} for i in range(density): matrix[(random.randint(0,order-1), rand... | Option 1 :Instead of keeping values in list and later creating the matrix, you can directly create the matrix and update the values in it.Please note you can have less number of non zero values than "order" as randint can return same number again.Sample code : import randomimport numpy as npdef sparse_matrix(density,or... |
Python use curl with subprocess, write outpute into file If I use the following command in the Git Bash, it works fine. The Output from the curl are write into the file output.txtcurl -k --silent "https://gitlab.myurl.com/api/v4/groups?page=1&per_page=1&simple=yes&private_token=mytoken&all?page=1&pe... | You cannot use redirection directly with subprocess, because it is a shell feature. Use check_output:import subprocesscommand = ["curl", "-k", "--silent", "https://gitlab.myurl.com/api/v4/groups?page=1&per_page=1&simple=yes&private_token=mytoken&all?page=1&per_page=1"]output = subprocess.check_outpu... |
Python - How to create a tunnel of proxies I asked this question: Wrap packets in connect requests until reach the last proxyAnd I learnt that to create a chains of proxies I have to:create a socketconnect the socket to proxy Acreate a tunnel via A to proxy B - either with HTTP or SOCKSprotocol similar create a t... | There is no Host header with CONNECT. I.e. to request HTTP proxy A to create a tunnel to HTTP proxy B you just use:>>> CONNECT B_host:B_port HTTP/1.0>>><<< 200 connections established<<<And then you have this tunnel to proxy B via proxy A. Inside this tunnel you then can create anoth... |
Replace the first characters if the object contain the symbol Python Pandas I have the string objects in the pandas Dataframe: ['10/2014', '2014','9/2013']How to replace them to get this result:['2014','2014','2013'] | If you want the last set of characters separated by '/', try this :[k.split('/')[-1] for k in ['10/2014', '2014','9/2013']]OUTPUT :['2014', '2014', '2013'] |
SQLAlchemy - Return filtered table AND corresponding foreign table values I have the following SQLAlchemy mapped classes: class ShowModel(db.Model): __tablename__ = 'shows' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100)) episodes = db.relationship('EpisodeModel', backref='e... | Because you have lazy loading enabled, the joined tables will only be set when they are accessed. What you can do is force a join. Something like the following should work for you:shows = session.query(ShowModel) .join(EpisodeModel) .join(InfoModel) .filter(ShowModel.name == "f... |
PyAudio IOError: [Errno Invalid input device (no default output device)] -9996 I am attempting to run a simple python file that uses pyaudio to record input. However whenever I run this file I end up with this error. I had it working once and I have no idea what changed. I have tried import pyaudiopa = pyaudio.PyAud... | I got this error because I accidentally ran# p = pyaudio.PyAudio()# ...p.terminate()and then tried to open another stream. |
Watershed Transform of Distance Image with OpenCV In Matlab, we can perform a watershed transform on the distance transform to separate two touching objects: The first image above is the image with touching objects that we wish to separate. The second image is its distance transform.So, if the black and white image is ... | You'd berrer get to know what readlly happen in the function of watershed.it starts flooding with its seeds and put the coordinate and the gradient of their neighbours in a priority queue.As you know, when you apply distanceTransform on img, the gradient of circles becomes 0 or 1, but the background always be 0;So, now... |
Regex replace conditional character I need to remove any 'h' in a string if it comes after a vowel.E.g. John -> Jon Baht -> Bat Hot -> Hot (no change) Rhythm -> Rhythm (no change)Finding the words isnt a problem, but removing the 'h' is as I still need the original vowel. Can this be done in one... | The regex for matching h after a vowel would be a positive lookbehind one(?<=a|e|y|u|o|a)hAnd you can dore.sub(r"([a-zA-Z]*?)(?<=a|e|y|u|o|a)h([a-zA-Z]*)",r"\1\2",s)However, if you can have more than one h after a vowel in a string, you would need to do several iterations, since regex doesn't support dynamic matc... |
Python sum and then multiply values of several lists Is there way to write following code in one line?my_list = [[1, 1, 1], [1, 2], [1, 3]]result = 1for l in list: result = result * sum(l) | Use reduce on the summed sublists gotten from map.This does it:>>> from functools import reduce>>> reduce(lambda x,y: x*y, map(sum, my_list))36In python 2.x, the import will not be needed as reduce is a builtin:>>> reduce(lambda x,y: x*y, map(sum, my_list))36 |
What should be the size of input and hidden state in GRUCell of tensorflow (python)? I am new to tensorflow (1 day of experience).I am trying following small code to create a simple GRU based RNN with single layer and hidden size of 100 as follows:import pickleimport numpy as npimport pandas as pdimport tensorflow as t... | Input to the GRUCell's call operator are expected to be 2-D tensors with tf.float32 type. The following ought to work :input_data = tf.placeholder(tf.float32, [batch_size, input_size])cell = tf.nn.rnn_cell.GRUCell(hidden_size)initial_state = cell.zero_state(batch_size, tf.float32)hidden_state = initial_stateoutput_of_c... |
python qt float precision from boost-python submodule I have made a cpp submodule with boost-python for my PyQt program that among others extracts some data from a zip data file.It works fine when testing it in python:import BPcmodsBPzip = BPcmods.BPzip()BPzip.open("diagnostics/p25-dev.zip")l=BPzip.getPfilenames()t=BPz... | Well it was related to using std::stod to convert my strings of data from my datafile to doubles. I don't know why, but changing to:boost::algorithm::trim(s);double val = boost::lexical_cast<double>(s);made it work as it was supposed to, also in pyqt. |
Difference between tuples (all or none) I have two sets as follows:house_1 = {('Gale', '29'), ('Horowitz', '65'), ('Galey', '24')}house_2 = {('Gale', '20'), ('Horowitz', '65'), ('Gale', '29')}Each tuple in each set contains attributes that represent a person. I need to find a special case of the symmetric set differenc... | You could count the occurences of names in the result and print only tuples that correspond to the names with the count of 1:from collections import defaultdictcount = defaultdict(list)for x in house_1 ^ house_2: count[x[0]].append(x)for v in count.values() if len(v) == 1: print(*v) |
How do I tell lxml which charset to use? I'm working with html and using lxml to parse it. For testing purposes I have an html document saved as a string in a python file with encoding=utf-8 at the top.Whenever I try to parse the html using lxml I get weird html encodings if the html does not have the <meta charset=... | Turns out I just need to pass in a custom parser to the fromstring method. So this fixes it:parser = html.HTMLParser(encoding="utf-8")t = lxml.html.fromstring(page_html, parser=parser)print lxml.html.tostring(t) |
How to get real quotient in python 2 Since the division operator "/" only returns floor quotient.When numerator or denominator is a minus number, operator "/" will not return the real quotient. Like -1/3 returns -1 rather than 0.How can i get the real quotient? | Try like this,a = 1b = 3print -(a / b) |
Passing a class's "self" to a function outside it such that the class's variables are accessible and modifiable? Can I pass the self instance variable of the class from within the class to some helper function outside the class? For example, will the following work when an object of SomeClass is initialized? Isn't ther... | The easiest way would have been to try it out :)yes, it works, as you expectclass SomeClass(): var1 = 7 def __init__(self): some_func(self) # passing self instead of self.var1def some_func(instance): instance.var1 += 1x = SomeClass()print x.var1But in most cases it would be better to make some_func to a... |
Zip a folder on S3 using Django I have an application where in I need to zip folders hosted on S3.The zipping process will be triggered from the model save method.The Django app is running on an EC2 instance.Any thoughts or leads on the same?I tried django_storages but haven't got a breakthrough | from my understanding you can't zip files directly on s3. you would have to download the files you'd want to zip, zip them up, then upload the zipped file. i've done something similar before and used s3cmd to keep a local synced copy of my s3bucket, and since you're on an ec2 instance network speed and latency will be ... |
How to display y-bar values in the bar chart? Hello friends I am creating a bar chart using seaborn or matplotlib. I make a successful graph, but I don't know how to display y bar values on the plot. Please give me suggestion and different techniques to display y-bar values on the plot.Please help me to solve the quest... | Short answer: You need customized auto label mechanism.First let's make it clear. If you mean byI don't know how to display y bar values on the plotthat on bars (inner), then this answer can be helpful.that on top of bars (outer), except for this answer for seaborn, there are some auto label solutions here you can use ... |
How to get parameters from strings in Python? How can I get some parameters from a string in Python.Let's say the string contains two words which I want to use as parameters. These are of course separated by spaces.Example:string = "Lorem Ipsum"def funct(hereLorem, hereIpsum) | You can try a string.split(optional delimiter). This returns a list.Example:l = string.split()and if you're expecting a certain patternarg1 = l[0]arg2 = l[1]... |
telegram doesn't show the image preview link always with my amazon afiliates I have a telegram channel and since yesterday it does not show the image preview of the links that I send with a bot.I send links with my ID of amazon afiliates and it doesn't work.Anyone knows how to solve it?bot = telegram.Bot(bot_token)bot.... | If your goal is to create a link preview and not using html markup, then this might help you:bot = telegram.Bot(bot_token)bot.send_message( bot_chatID, text='''*Hello*[https://www.amazon.es/dp/B076MMCQWW?psc=1](https://www.amazon.es/dp/B076MMCQWW?psc=1)''', parse_mode=telegram.ParseMode.MARKDOWN, disable... |
How to create a seaborn.heatmap() with frames around the tiles? I rendered a heatmap with seaborn.heatmap() works nicely. However, for a certain purpose I need frames around the plot. matplotlib.rcParams['axes.edgecolor'] = 'black'matplotlib.rcParams['axes.linewidth'] = 1both don't work. | ax = sns.heatmap(x)for _, spine in ax.spines.items(): spine.set_visible(True) |
processing a set of unique tuples I have a set of unique tuples that looks like the following. The first value is the name, the second value is the ID, and the third value is the type. ('9', '0000022', 'LRA') ('45', '0000016', 'PBM') ('16', '0000048', 'PBL') ('304', '0000042', 'PBL') ('7', '0000014', 'IBL') ('12'... | itertools.groupby with some additional processing of what it outputs will do the job:from itertools import groupbydata = { ('9', '0000022', 'LRA'), ('45', '0000016', 'PBM'), ('16', '0000048', 'PBL'), ...}def group_by_name_and_id(s): grouped = groupby(sorted(s), key=lambda (name, id_, type_): (name_, id))... |
Python the whole Module Normally when you execute a python file you do python *.pybut if the whole Module which contain many .py files insidefor example MyModule contain many .py file and if I do python -m MyModule $* what would happen as oppose python individual python file? | I think you may be confusing package with module. A python module is always a single .py file. A package is essentially a folder which contains a special module always named __init__.py, and one or more python modules. Attempting to execute the package will simply run the __init__.py module. |
How to create a conditional task in Airflow I would like to create a conditional task in Airflow as described in the schema below. The expected scenario is the following:Task 1 executesIf Task 1 succeed, then execute Task 2aElse If Task 1 fails, then execute Task 2bFinally execute Task 3All tasks above are SSHExecuteOp... | Airflow has a BranchPythonOperator that can be used to express the branching dependency more directly.The docs describe its use: The BranchPythonOperator is much like the PythonOperator except that it expects a python_callable that returns a task_id. The task_id returned is followed, and all of the other paths are ski... |
Analyzing the probability distribution of nodes in a network through networkx I am using python's networkx to analyze the attributes of a network, I want to draw a graph of power law distribution.This is my code.degree_sequence=sorted(nx.degree(G).values(),reverse=True) plt.loglog(degree_sequence,marker='b*')plt.show()... | You just need to construct a histogram of the degrees, i.e. hist[x] = number of nodes with degree x, and then normalize hist to sum up to one.Alternatively flip your axes and normalize such that the values sum to one. |
Tkinter PIR sensor I'm trying to create a smart mirror that displays different information such as the weather, 3 day forecast, news feed, and a tweet. I have all of this information printing in a window arranged how I want, but the final piece of the program I need to get to function with the rest of the program is a ... | You can't have a tkinter program with an infinate while loop and expect the tkinter mainloop to run.Suggest that you make use of the callbacks in gpiozero to call a function to enable the screen when motion is detected and perhaps a tkinter.after method to turn the screen off after a specified time period.def myScreenO... |
Keras Neural Network accuracy only 10% I am learning how to train a keras neural network on the MNIST dataset. However, when I run this code, I get only 10% accuracy after 10 epochs of training. This means that the neural network is predicting only one class, since there are 10 classes. I am sure it is a bug in data... | Here is the list of some weird points that I see :Not rescaling your images -> ImageDataGenerator(rescale=1/255)Batch Size of 1 (You may want to increase that)MNIST is grayscale pictures , therefore color_mode should be "grayscale".(Also you have several unused part in your code, that you may want to delete from the qu... |
How can I create a user in Django? I am trying to create a user in my Django and React application (full-stack), but my views.py fails to save the form I give it.Can someone explain me the error or maybe give me other ways to create an user?Below there is the code:# Form folderdef Registration(request): if request.m... | In your module where you call User in the django server you want to call something likeuser = User.objects.create_user(username, email, password)if not user: raise Exception("something went wrong with the DB!")It may be helpful to read the django docs on User table, I've linked directly to the part describ... |
how to find if any character in a string is a number in python? .isnumeric and .isdigit isn't working I need to determine if there are alphabetic and numeric characters in a string. My code for testing the alphabetic one seems to work fine, but numeric is only working if all of the characters are a digit, not if any.Th... | As the comments have pointed out, both your contains_alphabetic and contains_numeric functions don't do what you think they're doing, because they terminate prematurely - during the very first iteration. You start a loop, inspect the current character (which will be the first character of the string during the first it... |
Is it possible to name a variable 'in' in python? I am making a unit converter for a homework assignment, and I am using abbreviations for the various units of measurement as variable names, but when I try to define 'in' as a variable, it thinks I mean to use the word 'in' as if I wanted to say 'for x in y' or somethin... | in is a python keyword, so no you cannot use it as a variable or function or class name.See https://docs.python.org/2/reference/lexical_analysis.html#keywords for the list of keywords in Python 2.7.12. |
How can I reduce a tensor's last dimension in PyTorch? I have tensor of shape (1, 3, 256, 256, 3). I need to reduce one of the dimensions to obtain the shape (1, 3, 256, 256). How can I do it? Thanks! | If you intend to apply mean over the last dimension, then you can do so with:In [18]: t = torch.randn((1, 3, 256, 256, 3))In [19]: t.shapeOut[19]: torch.Size([1, 3, 256, 256, 3])# apply mean over the last dimensionIn [23]: t_reduced = torch.mean(t, -1)In [24]: t_reduced.shapeOut[24]: torch.Size([1, 3, 256, 256])# equiv... |
Searching for a key in python dictionary using "If key in dict:" seemingly not working I'm iterating through a csv file and checking whether a column is present as a key in a dictionary.This is an example row in the CSV file833050,1,109,B147599,162560,0I'm checking whether the 5th column is a key in this dictionary{162... | {162560: True} # {int:bool}{'162560': True} # {str:bool}So, mt_budgets does not contain '162560' (str), it contains 162560 (int)Your code should be:def check(self, mt_budgets): present = {} cwd = os.getcwd() path = cwd with open(path + 'file.csv.part') as f: csv_f = csv.reader(f) for row in c... |
Read text files from website with Python Hello I have got problem I want to get all data from the web but this is too huge to save it to variable. I save data making it like this:r = urlopen("http://download.cathdb.info/cath/releases/all-releases/v4_2_0/cath-classification-data/cath-domain-list-v4_2_0.txt")r = Beautifu... | I think the code below can do what you want. Like mentioned in a comment by @alecxe, you don't need to use BeautifulSoup. This problem should be a problem to retrieve content from text files online and is answered in this Given a URL to a text file, what is the simplest way to read the contents of the text file?from u... |
How to format print outputs of a text file? I have a text file called animal.txt.1.1 Animal Name : Dog Animal Type : Mammal Fur : Yes Scale : No1.2 Animal Name : Snake Animal Type : Reptile Fur : No Scale : Yes1.3 Animal Name : Frog Animal Type : Amph... | Use \t between the items you are printing. So print animal_name\t, then so on through the rest of your code.with open('animal.txt', 'r') as fp:for line in fp: header = line.split(':')[0] if 'Animal Name' in header: animal_name = line.split(':')[1].strip() print animal_name\t, elif 'Animal Type' i... |
Django - How to filter a ListView by user without using CBV? Is it possible to do this? I've been looking for quite a while, but every solution I've seen involves subclassing ListView which I don't want to do. I'm sure there's a way to filter results by user without having to resort to class-based views, I just can't... | When you send a request to view you have already instance of the current user in the request:views.pydef my_not_cb_view(request): user = request.user games = Game.objects.filter(user=User.user) context = {'games': games, 'user': user} render_to_response(request, 'user profile.html', context=context)urls.py... |
Fitting Log-normal distribution (Python plot) I am trying to fit a log-normal distribution to the histogram data. I've tried to follow examples of other questions here on the Stack Exchange but I'm not getting the fit, because in this case I have a broken axis. I already put the broken axis on that plot, I tried to pre... | You're trying at the same time to do fancy graphs and fit. you help you with fit, graphs are secondary problem.First, use NumPy arrays for data, helps a lot. Second, your histogram function is denormalized.So if in the first of your programs I'll normalize freqs arrayx=np.asarray([0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 0.... |
Looking for method / module to determine the compiler which was used for building the CPython interpreter When I start the Python interpreter in command line mode I get a message saying which compiler was used for building it. Is there a way to get this information in Python ? I know I could start the interpreter with ... | Use platform.python_compiler(). |
Google AppEngine images API suddenly corrupting images We have been using AppEngine's images API with no problem for the past year. Suddenly in the last week or so the images API seems to be corrupting the image. We use the images API to do a few different operations but the one that seems to be causing the problem i... | This turned out to be due to a recent change to the images API that introduced a bug which affected operations involving TIFF files, which has since been reverted. More information is in the original bug report.https://code.google.com/p/googleappengine/issues/detail?id=9284 |
Single line commands from Python I am trying to change certain entries in a file using python, which is possible in Perl with the command below , do we have anything similar in python, here the string in the file is replaced successfully. [root@das~] perl -pi -w -e 's/unlock_time=1800/#unlock_time=1900/g;' /etc/pam.d/c... | you need to add a print statement (with surrounding brackets for python 3.4; without for python 2.7).[root@das~] python -c 'import os ; print(os.uname()[1])'the other line could then be programmed this way (this will replace the input file!):import fileinputfor line in fileinput.input('test.txt', inplace=True): if l... |
iMacros script questions timeout/errormsg/popupignore etc I have 1000+ URLs that I want to scrape to retrieve the title info from. After trying different things, I ultimately used iMacros scripts, which I don't know anything about. Nonetheless, I managed to make a script after reading guides.My script is working perfec... | SET !DATASOURCE urls.txtSET !DATASOURCE_LINE {{!LOOP}}SET !TIMEOUT_STEP 1SET !TIMEOUT_PAGE 10 SET !ERRORIGNORE YESURL GOTO={{!COL1}}SET !ERRORIGNORE NOSET !EXTRACT_TEST_POPUP NOTAG POS=1 TYPE=TITLE ATTR=* EXTRACT=TXTSET dblSP " "SET !EXTRACT {{!COL1}}{{dblSP}}{{!EXTRACT}}SAVEAS TYPE=EXTRACT FOLDER=d:\ FILE=links.txtWA... |
Counting the number of men and women from a CSV file I want to count the number of male and female riders (which are coded as 1 or 2) in a CSV file, but my code does not seem to be working. This is my code:Men = 0Women = 0import csvwith open('dec2week.csv') as csvfile: reader = csv.DictReader(csvfile) for... | Use a Counter dict to do the counting:import csvfrom collections import Counterfrom itertools import chainwith open('dec2week.csv') as csvfile: next(csvfile) counts = Counter(chain.from_iterable(csv.reader(csvfile)))Then just get the count using the key:print("Total male = {}".format(counts["1"]))print("Total fem... |
efficiency of Python's itertools.product() So I'm looking at different ways to compute the Cartesian product of n arrays, and I came across the rather elegant solution (here on SO) of using the following code:import itertools for array in itertools.product(*arrays): print arrayLooking at the python doc page (... | You are absolutely right. That is, in the special case of two arrays input, both of the size n. In the general case of k arrays of the sizes n[i] for i in 1..k it will be O(Product of all n[i]).Why is this the case and why is there no way to optimize this any further?Well, in this case the size of the output is direc... |
Sentence tokenization for texts that contains quotes Code:from nltk.tokenize import sent_tokenize pprint(sent_tokenize(unidecode(text)))Output:[After Du died of suffocation, her boyfriend posted a heartbreaking message online: "Losing consciousness in my arms, your breath and heartbeat became weaker and weake... | I'm not sure what is the desired output but I think you might need some paragraph segmentation before nltk.sent_tokenize, i.e.:>>> text = """After Du died of suffocation, her boyfriend posted a heartbreaking message online: "Losing consciousness in my arms, your breath and heartbeat became weaker and weaker. F... |
TypeError for cookielib CookieJar cookie in requests Session I'm trying to use a cookie from a mechanize browser that I use to log in to a site in a requests Session, but whenever I make a request from the session I get a TypeError.I've made a convenience class for using an api exposed by the site (most of the actually... | You don't want to set the value of a single cookie in cookies to a CookieJar: it already is a CookieJar:>>> s = requests.Session()>>> type(s.cookies)<class 'requests.cookies.RequestsCookieJar'>You'll probably have a better time by simply setting s.cookies to your cookiejar:def new_cookie(self): ... |
Region finding based on VTK polylines I have the following domain that is made up of VTK poly lines -- each line starts and ends at a 'x', may have many points, and is assigned a left and right flag to denote the region on the left and right of that line, determined if you we walking down the line from start to end.For... | Every line on the perimeter of the sub-domain of interest (SDOI) must have the SDOI as one of its bordering domains. So you can flood fill (or expand a circle) in the domain that rp is in.Find what is the common domain neighboured by of all these lines.That is you SDOI.UNLESS:Special case: rp is in a ring (ie. domain 1... |
Python while loop not breaking when conditions are met I'm just wondering why the loop doesn't break when it meets those conditions and filters over into my other functions? I fixed it by doing a while true loop and just breaking in each if statement, but I'd like to know what is wrong with doing this way.def main_entr... | Of course it doesn't break, your condition can never be false(choice != 1) or (choice != 2) or (choice != 3)Think about it for a minute, any selection of choice cannot make this expression false.choice = 1False or True or True --> Truechoice = 2True or False or True --> Truechoice = 3True or True or False --> ... |
IronPython: Trouble building a WPF ShaderEffect I'm trying to build an extensible program where users, among other things, can build their own shader effects.Google searching got me this far;class Test(ShaderEffect): inputProperty = ShaderEffect.RegisterPixelShaderSamplerProperty("Input", type(Test()), 0)But I still... | You will need to use Reflection to access protected memeber of .NET class - you don't have a Python subclass where you can access such member directly.Try somethink like this (I have't tested it):inputPropertyType = ShaderEffect.GetType().GetMember( 'RegisterPixelShaderSamplerProperty', BindingFlags.Instance | Bi... |
How do I convert a string to a buffer in Python 3.1? I am attempting to pipe something to a subprocess using the following line:p.communicate("insert into egg values ('egg');");TypeError: must be bytes or buffer, not strHow can I convert the string to a buffer? | The correct answer is:p.communicate(b"insert into egg values ('egg');");Note the leading b, telling you that it's a string of bytes, not a string of unicode characters. Also, if you are reading this from a file:value = open('thefile', 'rt').read()p.communicate(value);The change that to:value = open('thefile', 'rb').rea... |
Python: Removing characters from beginnings of sequences in fasta format I have sequences in fasta format that contains primers of 17 bp at the beginning of the sequences. And the primers sometimes have mismatches. I therefore want to remove the first 17 chars of the sequences, except from the fasta header.The sequence... | If I understand correctly, you have to remove the primer only from the first 17 characters of a potentially multiline sequence. What you ask is a bit more difficult. Yes, a simple solution exists, but it can fail in some situations.My suggestion is: use Biopython to perform the parsing of the FASTA file. Straight from ... |
Python ternary invalid syntax Writing a very simply function to mask all but the last 4 digits of a string with "#" characters. This is what I have so far:def maskify(cc): res = "#" * (len(cc) - 4) if len(cc) > 4 else return cc res += cc[len(cc) - 4:] return res print(maskify("12355644"))If I write out t... | You don't need a ternary expression at all here, just slice and use the length minus 4 times "#' to generate the prefix:def maskify(cc): return "#" * (len(cc) - 4) + cc[-4:]If the len(cc) - 4 value is 0 or smaller the multiplication produces an empty string.Demo:>>> def maskify(cc):... return "#" * (len... |
ValueError: invalid literal for float(): Reading in Latitude and Longitude Data Given the following script to read in latitude, longitude, and magnitude data:#!/usr/bin/env python# Read in latitudes and longitudeseq_data = open('lat_long')lats, lons = [], []for index, line in enumerate(eq_data.readlines()): if index... | It appears you have one or more lines of corrupt data in your input file. Your traceback says as much:ValueError: invalid literal for float(): -18.381 -172.320 5.9Specifically what is happening:The line -18.381 -172.320 5.9 is read in from eq_data.split(',') is called on the string "-18.381 -172.320 5.9". Since t... |
check carriage return is there in a given string i,m reading some lines from a file and i'm checking whether each line has windows type of CRLF or not. If either '\n' or '\r' is absent in any line, it has to report an error. I tried with the below code, even if the line doesnt have '\r', it is not reporting any errorOp... | This isn't working because Loop_Counter is never adjusted at all; whatever the initial value is, it's not changing and the while loop either runs indefinitely or never passes. Your code is pretty unclear here; I'm not sure why you'd structure it that way.What you're suggesting would be easier to do like this:infile = ... |
Joining data sets in Spark What are different ways to join data in Spark?Hadoop map reduce provides - distributed cache, map side join and reduce side join. What about Spark?Also it will be great if you can provide simple scala and python code to join data sets in Spark. | Spark has two fundamental distributed data objects. Data frames and RDDs.A special case of RDDs in which case both are pairs, can be joined on their keys. This is available using PairRDDFunctions.join(). See: https://spark.apache.org/docs/1.5.2/api/scala/index.html#org.apache.spark.rdd.PairRDDFunctionsDataframes also a... |
Dividing into sentences based on pattern I would like to divide a text into sentences based on a delimiter in python. However, I do not want to split them based on decimal points between numbers, or comma between numbers. How do we ignore them. For example, I have a text like below. I am xyz.I have 44.44$. I would like... | This works for your example, although there's a trailing full stop (period) on the last part if that matters.import res = 'I am xyz. I have 44.44$. I would like, to give 44,44 cents to my friend.'for part in re.split('[.,]\s+', s): print(part)OutputI am xyzI have 44.44$I would liketo give 44,44 cents to my friend.Wi... |
Downloading file using multithreading in python I am trying to put multiple files(ard 25k) into a zip file using multithreading in python cgi. I have written the script below, but somehow the response I get has content length 0 and there is no data in the response. This is my first time using multithreading in python. ... | The problem should be that ZipFile.write() (ZipFile in general) is not thread safe.You must somehow serialize thread access to the zip file. This is one way to do it (in Python 3):ziplock = threading.Lock()def read_file(link): fname = link.split('/') fname = fname[-1] with ziplock: z.write(link, fname)T... |
Mitmproxy, push own WebSocket message I inspect a HTTPS WebSocket traffic with Mitmproxy. Currently I can read/edit WS messages with:class Intercept: def websocket_message(self, flow): print(flow.messages[-1])def start(): return Intercept().. as attached script to Mitmproxy.How do I push/inject my own mess... | You can do this with inject.websocket:from mitmproxy import ctxclass Intercept: def websocket_message(self, flow): print(flow.messages[-1]) to_client = True ctx.master.commands.call("inject.websocket", flow, to_client, b"Hello World!", True)def start(): return Intercept()T... |
Librosa Constant Q Transform (CQT) contains defects at the beginning and ending of the spectrogram Consider the following codeimport numpy as npimport matplotlib.pyplot as pltfrom librosa import cqts = np.linspace(0,1,44100)x = np.sin(2*np.pi*1000*s)fmin=500cq_lib = cqt(x,sr=44100, fmin=fmin, n_bins=40)plt.imshow(abs(c... | I think you might want to try out pad_mode which is supported in cqt. If you checkout the np.pad documentation, you can see available options (or see the end of this post). With the wrap option, you get a result like this, though I suspect the phase is a mess, so you should make sure this meets your needs. If you ar... |
ImportError when importing tensorflow I've recently installed TensorFlow using pip install --upgrade tensorflow then when I import it, I get the following error:ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed.Failed to load the native TensorFlow runtime. | try this:pip install setuptoolsif wont change anything uninstall tensorflow and try (if you have conda env):conda install tensorflow |
How to run an attribute value through a regular expression after extracting via BeautifulSoup? I have a URL that I want to parse a part of, particularly the widgetid:<a href="http://www.somesite.com/process.asp?widgetid=4530">Widgets Rock!</a>I've written this Python (I'm a bit of a newbie at Python -- vers... | This question doesn't have anything to do with BeautifulSoup.The problem is that, as the documentation explains, match only matches at the beginning of the string. Since the digits you want to find are at the end of the string, it returns nothing.To match on a digit anywhere, use search - and you probably want to use t... |
Python Detect Alert I am trying to make my python script detect an alert box on a pageimport urllib2url = raw_input("Please enter your url: ")if urllib2.urlopen(url).read().find("<script>alert('alert');</script>") == 0: print "Alert Detected!"How can I make it detect the alert? | urllib2.urlopen(url).read().find("<script>alert('alert');</script>") == 0 tourllib2.urlopen(url).read().find("<script>alert('alert');</script>") >= 0 |
Count only the words in a text file Python I have to count all the words in a file and create a histogram of the words. I am using the following python code.for word in re.split('[,. ]',f2.read()): if word not in histogram: histogram[word] = 1 else: histogram[word]+=1f2 is the file I am reading.I tr... | from collections import Counterfrom nltk.tokenize import RegexpTokenizerfrom nltk import bigramsfrom string import punctuation# preparatory stuff>>> tokenizer = RegexpTokenizer(r'[^\W\d]+')>>> my_string = "this is my input string. 12345 1-2-3-4-5. this is my input"# single words>>> tokens = t... |
Python extract elements from Json string I have a Json string from which I'm able to extract few components like formatted_address,lat,lng, but I'm unable to extract feature(values) of other components like intersection, political, country, a... | I would go for json_normalize, thought of one line answer but I dont think its possible i.e (Here I did only for px_val and py_val you can do similar things for other columns) from pandas.io.json import json_normalizeimport pandas as pdimport jsonwith open('dat.json') as f: data = json.load(f)result = json_normalize... |
Interpreting numpy array obtained from tif file I need to work with some greyscale tif files and I have been using PIL to import them as images and convert them into numpy arrays: np.array(Image.open(src))I want to have a transparent understanding of exactly what the values of these array correspond to and in partic... | A TIFF is basically a computer file format for storing raster graphics images. It has a lot of specs and quick search on the web will get you the resources you need.The thing is you are using PIL as your input library. The array you have is likely working with an uint8 data type, which means your data can be anywhere w... |
Python reading Popen continuously (Windows) Im trying to stdout.readline and put the results (i.e each line, at the time of printing them to the terminal) on a multiprocessing.Queue for us in another .py file. However, the call:res = subprocess.Popen(command, stdout=subprocess.PIPE, bufsize=1 )with res.stdout: for l... | As explained by @eryksun, and confirmed by your comment, the cause of the buffering is the use of printf by the C application.By default, printf buffers its output, but the output is flushed on newline or if a read occurs when the output is directed to a terminal. When the output is directed to a file or a pipe, the ac... |
Django POST form validation to an another page I'm trying to make a TV show manager with Django and I have a problem with form validation and redirection.I have a simple page with a form where people can search a Tv show, and an other page where the result of the query is displaying. (for the query I'm using the API of... | Base on your description and views.py, you stay on step 2 that's why:User is on page '/step_1/'He submit formBecause action param in form is point to '/step_2/', it's going to that urlIn view request.method == 'POST' is True, but form is not valid.You are rendering template from '/step_1', but not redirecting User.So h... |
Pandas dataframe in pyspark to hive How to send a pandas dataframe to a hive table?I know if I have a spark dataframe, I can register it to a temporary table using df.registerTempTable("table_name")sqlContext.sql("create table table_name2 as select * from table_name")but when I try to use the pandas dataFrame to regist... | I guess you are trying to use pandas df instead of Spark's DF.Pandas DataFrame has no such method as registerTempTable.you may try to create Spark DF from pandas DF.UPDATE:I've tested it under Cloudera (with installed Anaconda parcel, which includes Pandas module).Make sure that you have set PYSPARK_PYTHON to your anac... |
Import error "No module named selenium" when returning to Python project I have a python project with Selenium that I was working on a year ago. When I came back to work on it and tried to run it I get the error ImportError: No module named selenium. I then ran pip install selenium inside the project which gave me Requ... | Is it possible that you're using e.g. Python 3 for your project, and selenium is installed for e.g. Python 2?If that is the case, try pip3 install selenium |
Python Virtualenv : ImportError: No Module named Zroya I was trying to work with python virtualenv on the Zroya python wrapper around win32 API. Although I did installed the modules using pip, and although they are shown in cli using the command pip freeze,when trying to execute the .py file that uses the modules it... | Installing zroya should solve your problem.Installation instructions: https://pypi.python.org/pypi/zroya |
Package and module import in python Here is my folder structure:|sound|-__init__.py|-model |-__init__.py |-module1.py |-module2.py|-simulation |-sim.pyThe file module1.py contains the code:class Module1: def __init__(self,mod): self.mod = modThe file module2.py contains the code:class Module2: def __in... | The simple FIX :Move sim.py one folder up into soundTry import module2sound_1 = module2.Module2() |
Error while trying to parse a website url using python . how to debug it? #!/usr/bin/pythonimport jsonimport urllibfrom BeautifulSoup import BeautifulSoupfrom BeautifulSoup import BeautifulStoneSoupimport BeautifulSoup def showsome(searchfor): query = urllib.urlencode({'q': searchfor}) url = 'http://ajax.googleapis.... | What is the wrong in this code ?Your indentation is all wonky in the for loop, and this line:import BeautifulSoup should be deleted, as it masks this earlier import:from BeautifulSoup import BeautifulSoup |
Calculating length between 2 dates using Tkinter calendar I am trying to create a Tkinter application where the user selects a date in a calendar and then presses a button and a label then displays the number of days between the current date and the date they have selected. I have figured out how to calculate the numbe... | Add date_pattern="m/d/y" to Calender(...):cal = Calendar(root, date_pattern="m/d/y", background="#99cbd8", disabledbackground="blue", bordercolor="#99cbd8", headersbackground="light blue", normalbackground="pink", foreground="blue", normalf... |
How to modify single object inside dict values stored as a set? I have a dictionary which represents graph. Key is Node class and values are set of Nodes. So it has this structure:dict[Node] = {Node, Node, Node}class Node:def __init__(self, row, column, region): self.id = f'{str(row)}-{str(column)}' self.region =... | I've figured it out. I was storing different Node objects as key and what was in values set in my dictionary.I created context of all Nodes and get Node from there by its id.def get_node_from_context(self, row, column, region): node = Node(row, column, region) if node not in self.__graph_context__: ... |
I wrote a code that should identify which of the elements of the sequence are equal to the sum of the elements of two different arrays, but it's wrong I am given two int arrays of different lentgh. Also I'm given a sequence of integers. I need to write a code, that prints "YES" for each element of the sequenc... | To make your solution work you have to break out of the second for loop as well:for c in C: flag = False for a in A: for b in B: if c == a + b: flag = True break if flag: break print('YES' if flag else 'NO') |
How to add samesite=None in the set_cookie function django? I want to add samesite attribute as None in the set_cookie functionThis is the code where I call the set_cookie functionredirect = HttpResponseRedirect( '/m/' )redirect.set_cookie( 'access_token', access_token, max_age=60 * 60 )This is the function where I set... | You can use this library to change the flag if you're using django2.x or older: https://pypi.org/project/django-cookies-samesite/If you're using django3.x, it should be built-in |
NotImplementedError: data_source='iex' is not implemented I am trying to get some stock data through pandas_datareader in jupyter notebook. I was using google, but that does not work anymore, so I am using iex.import pandas_datareader.data as webimport datetimestart = datetime.datetime(2015,1,1)end = datetime.datetime(... | Many DataReader sources are deprecated, see updated list here.Many now require API key, IEX is one of them: Usage of all IEX readers now requires an API key.Get API key from IEX Cloud Console, which can be stored in the IEX_API_KEY environment variable. Just execute this is separate cell in Jupyter Notebook:os.enviro... |
Downloading QtDesigner for PyQt6 and converting .ui file to .py file with pyuic6 How do I download QtDesigner for PyQt6? If there's no QtDesigner for PyQt6, I can also use QtDesigner of PyQt5, but how do I convert this .ui file to .py file which uses PyQt6 library instead of PyQt5? | As they point out you can use pyuic6:pyuic6 -o output.py -x input.uibut in some cases there are problems in that the command is not found in the CMD/console, so the command can be used through python:python -m PyQt6.uic.pyuic -o output.py -x input.ui |
Reading a text file and replacing it to value in dictionary I have a dictionary made in python. I also have a text file where each line is a different word. I want to check each line of the text file against the keys of the dictionary and if the line in the text file matches the key I want to write that key's value to ... | you can try:for line in all_lines: for val in dic: if line.count(val) > 0: print(dic[val])this will look through all lines in the file and if the line contains a letter from dic, then it will print the items associated with that letter in the dictionary (you will have to do something like all_li... |
How to move just two columns of pandas dataframe to specific positions? I have a dataset of 100 columns like follows:citycode AD700 AD800 AD900 ... AD1980 countryname citynameI want the output dataframe to have columns as follows:citycode countryname cityname AD700 AD800 AD900 ... AD1980 I can't use code likecols = [A,... | One of possible solutions is:df = df[['citycode', 'countryname', 'cityname'] + list(df.loc[:, 'AD700':'AD1980'])]Note that you compose the list of column names from:a "by name" list (first 3),a "by range" list (all other columns).This way, from a source DataFrame like: citycode AD700 AD800 AD900... |
How to search via Enums Django I'm trying to a write a search function for table reserving from a restaurant, I have a restaurant model:class Restaurant(models.Model): """ Table Restaurant ======================= This table represents a restaurant with all necessary information. "&quo... | Instead of using a list of tuples I would recommend extending the IntegerChoices or TextChoices classes provided by Django. Here's an example of how you can use IntegerChoices:>>> class KitchenType(models.IntegerChoices):... TURKISH = 1... ITALIAN = 2... GERMAN = 3... >>> if 1 in KitchenTy... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.