Python Last N Array Elements
python last n array elements array = [“a”, “b”, “c”, “d”] num_elements = 3 print(array[-num_elements:])
python last n array elements array = [“a”, “b”, “c”, “d”] num_elements = 3 print(array[-num_elements:])
python last n list elements array = [“a”, “b”, “c”, “d”] num_elements = 3 print(array[-num_elements:])
python last 3 list elements array = [“a”, “b”, “c”, “d”] num_elements = 3 print(array[-num_elements:])
get last 3 in array python array = [“a”, “b”, “c”, “d”] num_elements = 3 print(array[-num_elements:])
get last 3 in list python array = [“a”, “b”, “c”, “d”] num_elements = 3 print(array[-num_elements:])
get last 3 elements in a list python array = [“a”, “b”, “c”, “d”] num_elements = 3 print(array[-num_elements:])
drop null rows pandas df.dropna() Source:datatofish.com drop na dataframe result.dropna(subset = [“rReview”], inplace=True) Source:www.codegrepper.com drop na dropna
multiple bar graph in python import numpy as np import matplotlib.pyplot as plt X = [‘Group A’,’Group B’,’Group C’,’Group D’] Ygirls = [10,20,20,40] Zboys = [20,30,25,30] X_axis = np.arange(len(X)) plt.bar(X_axis – 0.2, Ygirls, 0.4, label = ‘Girls’) plt.bar(X_axis + 0.2, Zboys, 0.4, label = ‘Boys’) plt.xticks(X_axis, X) plt.xlabel(“Groups”) plt.ylabel(“Number of Students”) plt.title(“Number of Students in … Read more
how to colour letters in python print(“yourtext”) #If you print anything, as default you’ll get white text and black background print(“\033[{effect};{textcolour};{textbackground}myourtext”) #this won’t actually work, you need to change the “{}” by a number “effect: 0 = none, 1 = bold, 2 = underline” “textcolour 30 = black, 31 = red, 32 = green, 33 … Read more
asyncio sleep #will sleep the current corutien for set numner of seconds import asyncio await asyncio.sleep(1) async sleep python import asyncio await asyncio.sleep(1) python sleep import time start = time.time() print(“sleeping…”) time.sleep(0.5) print(“woke up…”) elapsed_time = time.time() – start print(“elapsed time:”, elapsed_time * 1000, “milliseconds”)
how to make convert numpy array to string in python string = “” for element in a_list: string += element # Gives output without spaces. *NOTE*
tkinter simple application #simple application with tkinter from tkinter import * window=Tk() # add widgets here window.title(‘Hello Python’) window.geometry(“300×200+10+20”) window.mainloop()
dataframe python unique values rows # get the unique values (rows) df.drop_duplicates() Source: www.datasciencemadesimple.com
create models in django from django.db import models # Create your models here. class Contact(models.Model): name = models.CharField(max_length=50) email = models.CharField(max_length=50) contact = models.CharField(max_length=50) content = models.TextField() def __str__(self): return self.name + ‘ ‘ + self.email model in django from django.db import models class Musician(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) class … Read more
creation of a model in django from django.db import models class Musician(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) class Album(models.Model): artist = models.ForeignKey(Musician, on_delete=models.CASCADE) name = models.CharField(max_length=100) release_date = models.DateField() num_stars = models.IntegerField() Source: docs.djangoproject.com
discord py edit message await message.edit(content=”newcontent”) #for embed you need to create a new one await message.edit(embed=newembed) Source:stackoverflow.com discord.py edit messages #edit text await message.edit(content=”new content”) #edit embed await message.edit(content=”new content”, embed=new_embed)
get number of zero is a row pandas (pandas_dataframe == 0).sum(axis=1)
vscode pylint missing module docstring “python.linting.pylintArgs”: [“–errors-only”] Source: stackoverflow.com
python randomise between 0 or 1 import random random.random() # Gives you a number BETWEEN 0 and 1 as a float round(random.random()) # Gives you a number EITHER 0 and 1 generate a random number in python between 0 and 1 import random print(random.uniform(0, 1)) Source:www.geeksforgeeks.org random python between 0 and 1 import random … Read more
how to check the type of a variable in python print(type(x)) how to find the data type in python x = 5 print(type(x)) print(type(“python”)
python write to file file = open(“testfile.txt”,”w”) file.write(“Hello World”) file.write(“This is our new text file”) file.write(“and this is another line.”) file.write(“Why? Because we can.”) file.close() python write to file # using ‘with’ block with open(“xyz.txt”, “w”) as file: # xyz.txt is filename, w means write format file.write(“xyz”) # write text xyz in the … Read more
fcm_django pip install fcm-django
file methods in python file = open(filename, filemode) file.readable() file.writable() file.read() file.readlines() file.seek() file.tell() file.write() file.close()
plt text matplotlib white background import numpy as np import matplotlib.pyplot as plt plt.figure() ax = plt.subplot(111) plt.plot(np.linspace(1,0,1000)) t = plt.text(0.03,.95,’text’,transform=ax.transAxes,backgroundcolor=’0.75′,alpha=.5) plt.show()
python getAttr class Student: marks = 88 name = ‘Sheeran’ person = Student() name = getattr(person, ‘name’) print(name) marks = getattr(person, ‘marks’) print(marks) # Output: Sheeran # 88 Source: www.programiz.com
python if string is null or whitespace def IsNullOrEmpty(x): # Returns true if null or empty nullorempty = False if not(x): # checks for nulls nullorempty = True if x.isspace(): # checks for blank strings nullorempty = True return nullorempty
how delete an entry tkinter import tkinter as tk class App(tk.Frame): def __init__(self, master): tk.Frame.__init__(self, master, height=42, width=42) self.entry = tk.Entry(self) self.entry.focus() self.entry.pack() self.clear_button = tk.Button(self, text=”Clear text”, command=self.clear_text) self.clear_button.pack() def clear_text(self): self.entry.delete(0, ‘end’) def main(): root = tk.Tk() App(root).pack(expand=True, fill=’both’) root.mainloop() if __name__ == “__main__”: main() Source: stackoverflow.com
multiple variables in for loop python >>> for i, j in [(0, 1), (‘a’, ‘b’)]: … print(‘i:’, i, ‘j:’, j) … i: 0 j: 1 i: a j: b Source:stackoverflow.com multiple variables in for loop python for i, j in zip(range(x), range(y)): # Stuff… Source:stackoverflow.com how to create multiple variables in a loop python # … Read more
pandas see all columns pd.set_option(‘display.max_columns’, None) pd.set_option(‘display.max_rows’, None) pd.set_option(‘display.max_columns’, None) pd.set_option(‘display.max_columns’, None) pd.set_option(‘display.max_rows’, None) #used for expanding the no o viible columns of dataframe view all columns in pandas dataframe pd.options.display.max_columns = None pd.options.display.max_rows = None view all columns pandas print(dataframe.columns)
dataframe to list df.values.tolist() Source:datatofish.com pandas list to df # import pandas as pd import pandas as pd # list of strings lst = [‘Geeks’, ‘For’, ‘Geeks’, ‘is’, ‘portal’, ‘for’, ‘Geeks’] # Calling DataFrame constructor on list df = pd.DataFrame(lst) df convert list to dataframe L = [‘Thanks You’, ‘Its fine no problem’, ‘Are you … Read more