Formatting API List with for loop in a Table
I want to output a list I get from the API in a table so it looks nicer. The data from the API is returned with a for loop. My problem now is that I don't know how to get it that the header isn't looped every time.
for Example:
And i want one header and the rest under the header
I have managed with some instructions from here that the data will be displayed with "Tabulate" at all in a table. However, the "header" will be inserted at each run again.
head = ["Datum", "Username", "License Server", "Feature Name", "Max. Usage", "Hours Used", "Max Used", "Hours Borrowed", "Max Borrowed"]
for item in (data['data'])
if item['un'] == tecNo:
print(tabulate([[item['fud'], item['un'], str(item['lsn']), str(item['fns']), str(item['musage']), str(item['hu']), str(item['mu']), str(item['hb']), str(item['mb'])]],headers=head, tablefmt="grid"))```
[1]: https://i.stack.imgur.com/ZHODf.png
[2]: https://i.stack.imgur.com/pNci2.png
1 answer
-
answered 2019-07-18 16:02
Moira Jones
You need to put the items in a 2d array, then call
tabulate
at the end.table = [] for item in (data['data']) if item['un'] == tecNo: table.append([ item['fud'], item['un'], str(item['lsn']), str(item['fns']), str(item['musage']), str(item['hu']), str(item['mu']), str(item['hb']), str(item['mb']) ]) tabulate(table, headers=head)
See also questions close to this topic
-
How can I get my public IPV4 address from NAT internal network with python
guys I just want to look up my public ipv4 address from NAT internal network, I know lots of webpages offering that function, only if you visit them by opening webpages with a browser. The thing I figure out is to extract the IP address information from the webpage with python, I had used python's lib called 'requests', but every time the code response without IP information I anticipate when I visit those webpages which can show my public address correctly in a browser. I guess it is probably because those pages used a code-proof visiting strategy. So is there any way that I can use to get my public IP address with python code, just something like restful service?
-
Not able to call a function using the python inheritance?
I am new to python, please help me with the below question-
Question: You have already given a class
base
, now you have to declare a class calledcode
which inherits the classbase
and calls thehello
of thebase
class.Example:
- Input:
4
- Output:
["Hello Python", "Hello Python", "Hello Python", "Hello Python"]
class base: def __init__(self,n): self.n=n def hello(n): return ["Hello Python" for i in range(n)]
I tried as below:
class code(base): def __init__(self): base.__init__(self,5) x=code() x.hello()
but got error:
TypeError Traceback (most recent call last) <ipython-input-88-1a7429b02c84> in <module> 12 base.__init__(self,5) 13 x=code() ---> 14 x.hello() <ipython-input-88-1a7429b02c84> in hello(n) 3 self.n=n 4 def hello(n): ----> 5 return ["Hello Python" for i in range(n)] 6 7 TypeError: 'code' object cannot be interpreted as an integer
- Input:
-
Sorting column for day of week?
I have df as below:
day value Friday 32 Friday 32 Monday 11 Monday 22 Saturday 44 Saturday 25 Sunday 77 Sunday 88 Thursday 88 Thursday 88 Tuesday 88 Tuesday 88 Wednesday 88 Wednesday 88
How can I sort this in order of correct weekday?
I tried:
weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] df.Weekday = pd.Categorical(df.day,categories=weekdays) df = df.sort_values('day')
it runs but does not change output,
thanks
-
How accelerate an algorithm to find the time overlaps?
I have a dataset including 4 attributes :
- an id attribute called "id" (integer)
an attribute called "group" (integer)
an admission time called "aankomstdt" (datetime)
a discharge time called "ontslagdt" (datetime)
The dataset looks like that :
id group aankomstdt ontslagdt 1 A Thu Nov 14 04:31:00 CET 2019 Thu Nov 14 09:43:00 CET 2019 2 A Thu Nov 14 05:38:00 CET 2019 Thu Nov 14 06:19:00 CET 2019 3 A Thu Nov 14 05:52:00 CET 2019 Thu Nov 14 09:14:00 CET 2019 4 A Thu Nov 14 05:54:00 CET 2019 Thu Nov 14 10:02:00 CET 2019 5 B Thu Nov 14 06:06:00 CET 2019 Thu Nov 14 11:22:00 CET 2019
I would like to calculate the number of examples that are simultaneously admitted. As such a new attribute should provide me the number of patients admitted for each patient (id) during his/her admission time frame. I created the following working code :
import pandas as pd import numpy as np from datetime import datetime admission_time = "aankomstdt" discharge_time = "ontslagdt" group = 'group' date_format = '%Y-%m-%d %H:%M:%S' path = 'D:/Lionel/Formations_DataScience/Rapidminer/Tests_Rapidminer/count_overlaps_sven.xlsx' def convert_to_datetime(a) : a = datetime.strptime(str(a), date_format) return a def interval_overlaps(a, b): return min(a[discharge_time], b[discharge_time]) - max(a[admission_time], b[admission_time]) > np.timedelta64(-1) def count_overlaps(df1): return pd.Series([df1.apply(lambda x: interval_overlaps(x, df1.iloc[i]), axis=1).sum() - 1 for i in range(len(df1))], df1.index) #return pd.Series([df1.apply(lambda x: interval_overlaps(x, df1.iloc[i]), axis=1).sum() - 1 for i in range(len(df1))]) def rm_main(): data = pd.read_excel(path) data[admission_time] = data[admission_time].apply(convert_to_datetime) data[discharge_time] = data[discharge_time].apply(convert_to_datetime) data["count"] = data.groupby(group).apply(count_overlaps).values return data
But my original dataset has around 70 000 examples, so I estimate that computation time is around 1 month (24h/24). My question is : Is there a solution to significantly accelerate this algorithm ?
Thanks you,
-
Changing the operation of the turtle graphics
Firstly, I am very new to programming and biting off more than I can chew here. Anyway....
I am trying to build a solar system/orbiting simulation in python using this code as a model:
https://fiftyexamples.readthedocs.io/en/latest/gravity.html
This is my full code:
# Import math and turtle import math from turtle import * import turtle # Gravitational Constant G = 6.67428e-11 # Scale: 1 pixel = 1 astronomical unit # 1 astronomical unit = 1 AU = 149597900 km AU = (149.6e6 * 1000) # 149.6 million km in meters Scale = 250 / AU wn = turtle.Screen() wn = turtle.bgcolor('black') class body(Turtle): # Subclass of turtle representing a body # Additional attributes: # mass in kg # vx, vy: x, y velocities in m/sc # px, py: x, y positions in m # Set background to black # Turtle.bgcolor('black') name = 'body' mass = None vx = vy = 0.0 px = py = 0.0 def attraction(self, other): # (body): (fx, fy) # returns the force exerted on this body by the other body. # Report and error if the other object is the same as this one. if self is other: raise ValueError("Attraction of object %r to itself requested" % self.name) # Compute the distance of the other body: sx, sy = self.px, self.py ox, oy = other.px, other.py dx = (ox - sx) dy = (oy - sy) d = math.sqrt(dx**2 + dy**2) # Report an Error if the distance is 0 # ZeroDivisionError would happen later otherwise if d == 0: raise ValueError("Collision between objects %r and %r" % (self.name, other.name)) # Compute the force of attraction f = G * self.mass * other.mass / (d**2) # Compute the direction of the force theta = math.atan2(dy, dx) fx = math.cos(theta) * f fy = math.sin(theta) * f return fx, fy def updateInfo(step, bodies): # (int, [body]) # Displays infomation about status of simulation. print('Step #{}'.format(step)) for body in bodies: s = '{:<8} Pos.={:>6.2f} Vel.={:>10.3f}'.format(body.name, body.px/AU, body.py/AU, body.vy) print(s) print() def loop(bodies): # (body) # Never returns; loop through the simulation and updates the positions of given bodies timestep = 24*3600 # One Day for body in bodies: body.penup() body.hideturtle() step = 1 while True: updateInfo(step, bodies) step += 1 force = {} for body in bodies: # Adds all the forces exerted on a body totalFx = totalFy = 0.0 for other in bodies: # Don't calculate attraction to itself if body is other: continue fx, fy = body.attraction(other) totalFx += fx totalFy += fy # Record the total force exerted force[body] = (totalFx, totalFy) # Update velocities based on the force. for body in bodies: fx, fy = force[body] body.vx += fx / body.mass * timestep body.vy += fy / body.mass * timestep # Update positions body.px += body.vx * timestep body.py += body.vy * timestep body.goto(body.px*Scale, body.py*Scale) body.dot(5) def main(): sun = body() sun.name = 'Sun' sun.mass = 1.98892 * 10**30 sun.pencolor('yellow') earth = body() earth.name = 'Earth' earth.mass = 5.9742 * 10**24 earth.px = -1*AU earth.vy = 29.783 * 1000 earth.pencolor('blue') venus = body() venus.name = 'Venus' venus.mass = 4.8685 * 10**24 venus.px = 0.723 * AU venus.vy = -35.02 * 1000 venus.pencolor('orange') loop([sun, earth, venus]) if __name__ == '__main__': main()
I have added an
import turtle
line for my window as I want to change the window color to black. I know the the major differences between the two import styles and why some people prefer one over the other (or why one is not good). I want to change the structure of the class so I can have more control over the graphics of the simulation and also move away from thefrom x import *
method. Any advice will be welcome! -
Python Tabulate formats characters as separate columns
Using pandas, I am reading in a tab delimited file that looks like this:
with the following code:
pantry_file = pd.read_csv('/PantryList.txt', sep='\t')
Based on user input, I want to print out a nice looking table of all Items in this file. I am using tabulate to do this. The code looks like this:
print(tabulate(pantry_file.loc[: , "ITEM"], tablefmt='psql', headers=['Pantry Item'], showindex=False))
However, the resulting output treats each character as a column:
Wheres a traditional print statement looks like this:
My question is, why is tabulate treating each letter as a column, and how can I correct this?
Other info: Python 3.6 using Spyder through Anaconda.
-
Trouble importing Tabulate with Python 3.7
I'm running Python 3.7 on Windows 10 and I keep getting
No module named 'tabulate'
error. I have deleted Python 2.I've tried everything suggested in a similar question:
>> pip install tabulate >> pip3 install tabulate >> python -m pip install tabulate
All of the above respond with
>> Successfully installed tabulate-0.8.6
If I try to run it again, I get
>> Requirement already satisfied: tabulate in c:\program files\python37\lib\site-packages (0.8.6)
But I keep getting the same
ModuleNotFoundError
when I try to import it. What can I try still?UPD:
I have double-checked whether old versions of Python were uninstalled, and to my surprise EVERYTHING was still there: the folders, the files, the paths in the PATH... I'm afraid that was the reason of my problems, but I won't be able to test it until later.
-
My imported .txt table does not line up correctly with the headers (Python)
So basically I have to import a preset .txt file and everything works fine except for the one small thing that the preset headers that are in the code don't line up with the .txt file data properly.
import csv from tabulate import tabulate as tb F = input("Enter the name of the file that you would like to import:") fields = list(csv.reader(open(F + '.txt', 'r'), delimiter=';')) print(tb(fields, headers=['Company', 'Registration number.', 'Date', 'Adress', 'Telephone Number']))
And the code prints out this.
Company Registration number. Date Adress Telephone Number ------ --------- ---------------------- ----------------------------- ----------- ------------------ Valve 60006672 03.13.2003. Brown street, Athens, Greece. 14223157963 Google 50003495 10.24.2001. Lenin street, Moscow, Russia. 53221745750 Apple 20000196 03.31.2008. Second street, New York, USA. 55327537161
The information in .txt file:
Valve; 60006672;03.13.2003.;Brown street, Athens, Greece..;14223157963; Google;50003495;10.24.2001.;Lenin street, Moscow, Russia.;53221745750; Apple;20000196;03.31.2008.;Second street, New York, USA.;55327537161;