Print from PrettyTable with Python2 vs Python3 - python

I am playing a little with PrettyTable in Python and I noticed completely different behavior in Python2 and Python 3. Can somebody exactly explain me the difference in output? Nothing in docs gave me satisfied answer for that. But let's start with little code. Let's start with creating my_table
from prettytable import PrettyTable
my_table = PrettyTable()
my_table.field_name = ['A','B']
It creates two column table with column A and column B. Let's add on row to it, but assume that value in cell can have multi lines, separated by Python new line '\n' , as the example some properties of parameter from column A.
row = ['parameter1', 'component: my_component\nname:somename\nmode: magic\ndate: None']
my_table.add_row(row)
Generally the information in row can be anything, it's just a string retrieved from other function. As you can see, it has '\n' inside. The thing that I don't completely understand is the output of print function.
I have in Python2
print(my_table.get_string().encode('utf-8'))
Which have me output like this:
+------------+-------------------------+
| Field 1 | Field 2 |
+------------+-------------------------+
| parameter1 | component: my_component |
| | name:somename |
| | mode: magic |
| | date: None |
+------------+-------------------------+
But in Python3 I have:
+------------+-------------------------+
| Field 1 | Field 2 |
+------------+-------------------------+
| parameter1 | component: my_component |
| | name:somename |
| | mode: magic |
| | date: None |
+------------+-------------------------+
If I completely removes the encode part, it seems that output looks ok on both version of Python.
So when I have
print(my_table.get_string())
It works on Python3 and Python2. Should I remove the encode part from code? It is save to assume it is not necessary? Where is the problem exactly?

Related

PrettyTable Python table structure

I wanted to construct a table in the Below format using python.
Edit : Sorry for not writing the question properly
I have used PrettyTable
t = PrettyTable()
t.field_names =["TestCase Name","Avg Response", "Response time "]
But for Spanning the columns R1 and R2 I am struggling.
I am trying to add data to column Testcase Name,but TestCase Name is again adding as a column at the end.
I am trying to do using the Prettytable library
t.add_column("TestCase Name", ['', 'S-1', 'S-2'])
| Test Case Name | Avg Response | Response time |
+----------------+----------------+----------------+
| | R1 | R2 | R1 | R2 |
+----------------+------+---------+-------+--------+
| S-1 | | | | |
+----------------+------+---------+-------+--------+
| S-2 | | | | |
+--------------------------------------------------+```
Thank You
If you want to display the table in the terminal/console. See https://pypi.org/project/tabulate/ or https://pypi.org/project/prettytable/
Although, I’ve only ever used tabulate so can only recommend that one.
If you want proper data visualisation reports with complex data structures. I’d probably go with using NumPy and/or Pandas.
yeah have a look at https://pypi.org/project/tabulate/
and if you wanna use it just do
pip install tabulate
in cmd

Creating table from dictionary & string formatting - Python [duplicate]

This question already has answers here:
Python - Printing a dictionary as a horizontal table with headers
(7 answers)
Closed 2 years ago.
Basically, I have a dictionary and I'd like to construct a table from it.
The dictionary is of the form:
dict={
'1':{'fruit':'apple',
'price':0.60,
'unit':'pieces',
'stock':60
},
'2':{'fruit':'cherries',
'price':15.49,
'unit':'kg',
'stock':5.6
},
and so on.
}
I want the table to look like with correct alignment of numbers:
no |item | price | stock
----+----------+-------+----------
1 |apple | 0.60 | 60 pieces
----+----------+-------+----------
2 |cherries | 15.49 | 5.6 kg
and so on...
I do NOT want to print this table out, I'm trying to write a function that takes the dict as input and RETURNS this table as a string.
Here's my attempt:
def items(dct)
table="{0:<2} | {1:<33} | {2:^8} | {3:^11}".format("no", "item", "price","stock")
...
return table
I'm having trouble with formatting strings, I've tried to add line breaks and play around with different things but I always get various errors and things just aren't working out :(
I'm new to Python, could someone educate me pls.
Thanks!
def table_create(dct):
dashes = "{0:<2} + {1:<33} + {2:^8} + {3:^11} \n".format("-"*2, "-"*33, "-"*8, "-"*11)
table="{0:<2} | {1:<33} | {2:^8} | {3:^11} \n".format("no", "item", "price", "stock")
table+=dashes
for key, value in dct.items():
table+="{0:<2} | {1:<33} | {2:^8} | {3:^11} \n".format(key, value["fruit"], value["price"],str(value["stock"])+" "+value["unit"])
table+=dashes
return table
print(table_create(dct))
# output
no | item | price | stock
-- + --------------------------------- + -------- + -----------
1 | apple | 0.6 | 60 pieces
-- + --------------------------------- + -------- + -----------
2 | cherries | 15.49 | 5.6 kg
-- + --------------------------------- + -------- + -----------
the same way you stored the header of the table, you can store its entries and print them or do whatever you want.
dict={
'1':{'fruit':'apple','price':0.60,'unit':'pieces','stock':60},
'2':{'fruit':'cherries','price':15.49,'unit':'kg','stock':5.6}
}
def items(dct):
table="{0:<2} | {1:<33} | {2:^8} | {3:^11}".format("no", "item", "price","stock")
print(table)
for i in dict:
print("{0:<2} | {1:<33} | {2:^8} | {3:^11}".format(i,dict[i]['fruit'] ,dict[i]['price'],str(dict[i]['stock'])+' '+dict[i]['unit']))
items(dict)
You can check these questions:
Python - Printing a dictionary as a horizontal table with headers
Printing Lists as Tabular Data
Instead of printing the data, just concatenate it in a string.

Pyspark : How to escape backslash ( \ ) in input file

I am loading a csv file into postgresql using pyspark. I have a record in the input file which looks like below -
Id,dept,city,name,country,state
1234,ABC,dallas,markhenry\,USA,texas
When I load it into the postgresql database then it gets loaded like this which is not correct -
Id | dept| city | name | country | state
1234 | ABC | dallas | markhenry,USA | texas | null
correct output in postgresdb should be -
Id | dept| city | name | country | state
1234 | ABC | dallas | markhenry | USA | texas
I am reading the file like below -
input_df = spark.read.format("csv").option("quote", "\"").option("escape", "\"").option("header",
"true").load(filepath)
Is there a way I can modify my code to handle the backslash () coming in the data. Thanks in advance
The purpose of the "quote" option is to specify a quote character, which wraps entire column values. Not sure if that is needed here, but you can use the regexp_replace function to remove specific characters (just select everything else as-is and modify the name column this way).
from pyspark.sql.functions import *
df = spark.read.option("inferSchema", "true").option("header", "true").csv(filepath)
df2 = df.select(col("Id"), col("dept"), col("city"), regexp_replace(col("name"), "\\\\", "").alias("name"), col("country"), col("state"))
df2.show(4, False)
Output:
+----+----+------+---------+-------+-----+
|Id |dept|city |name |country|state|
+----+----+------+---------+-------+-----+
|1234|ABC |dallas|markhenry|USA |texas|
+----+----+------+---------+-------+-----+

I want to display variables in table format that should be perfectly align in python [duplicate]

This question already has answers here:
Printing Lists as Tabular Data
(20 answers)
Closed 3 years ago.
I want to make a table in python
+----------------------------------+--------------------------+
| name | rank |
+----------------------------------+--------------------------+
| {} | [] |
+----------------------------------+--------------------------+
| {} | [] |
+----------------------------------+--------------------------+
But the problem is that I want to first load a text file that should contain domains name and then I would like to making a get request to each domain one by one and then print website name and status code in table format and table should be perfectly align. I have completed some code but failed to display output in a table format that should be in perfectly align as you can see in above table format.
Here is my code
f = open('sub.txt', 'r')
for i in f:
try:
x = requests.get('http://'+i)
code = str(x.status_code)
#Now here I want to display `code` and `i` variables in table format
except:
pass
In above code I want to display code and i variables in table format as I showed in above table.
Thank you
You can achieve this using the center() method of string. It creates and returns a new string that is padded with the specified character.
Example,
f = ['AAA','BBBBB','CCCCCC']
codes = [401,402,105]
col_width = 40
print("+"+"-"*col_width+"+"+"-"*col_width+"+")
print("|"+"Name".center(col_width)+"|"+"Rank".center(col_width)+"|")
print("+"+"-"*col_width+"+"+"-"*col_width+"+")
for i in range(len(f)):
_f = f[i]
code = str(codes[i])
print("|"+code.center(col_width)+"|"+_f.center(col_width)+"|")
print("+"+"-"*col_width+"+"+"-"*col_width+"+")
Output
+----------------------------------------+----------------------------------------+
| Name | Rank |
+----------------------------------------+----------------------------------------+
| 401 | AAA |
+----------------------------------------+----------------------------------------+
| 402 | BBBBB |
+----------------------------------------+----------------------------------------+
| 105 | CCCCCC |
+----------------------------------------+----------------------------------------+

How do I save the header and units of an astropy Table into an ascii file

I'm trying to create an ascii table with some information on the header, the names and units of the columns and some data, it should look like this:
# ... Header Info ...
Name | Morphology | ra_u | dec_u | ...
| InNS+B+MOI | HH:MM:SS.SSS | ±DD:MM:SS:SSS| ...
==============| ========== | ============ | ============ | ...
1_Cam_A | I | 04:32:01.845 | +53:54:39.03 ...
10_Lac | I | 22:39:15.679 | +39:03:01.01 ...
...
So far I've tried with numpy.savetxt and astropy.ascii.writhe, numpy won't really solve my problems and with ascii.write I've been able to get something similar but not quite right:
Name | Morphology | ra_u | dec_u | ...
================== | ========== | ============ | ============ | ...
1_Cam_A | I | 04:32:01.845 | +53:54:39.03 ...
...
I'm using this code:
formato= {'Name':'%-23s','Morphology':'%-10s','ra_u':'%s','dec_u':'%s',...}
names=['Name','Morphology','ra_u','dec_u','Mag6']
units=['','InNS+B+MOI','HH:MM:SS.SSS','±DD:MM:SS:SSS',...]
ascii.write(data, output='pb.txt',format='fixed_width_two_line',position_char='=',delimiter=' | ',names=names, formats=formato)
So if I make a print in my terminal the table looks as it should except for the header info, but as I save it into a file the units disappear...
Is there any way to include them in the file?, or I need to save the file and edit it later?
P.D.: I'm also tried some other formats such as IPAC for ascii.write, in that case the problem is that includes a 4th row in the header like: '| null | null |.....' and I don't know how to get rid of it...
Thanks for the help
Un saludo.
There doesn't appear to be a straightforward way to write out the units of a column in a generic way using astropy.table or astropy.io.ascii. You may want to raise an issue at https://github.com/astropy/astropy/issues with a feature request.
However, there is a pretty simple workaround using the format ascii.ipac:
tbl.write('test.txt', format='ascii.ipac')
with open('test.txt', 'r') as fh:
output = []
for ii, line in enumerate(fh):
if ii not in (1,3):
output.append(line)
with open('test.txt', 'w') as fh:
fh.writelines(output)
which will write out in the IPAC format, then remove the 2nd and 4th lines.
Unless your table absolute has to be in that format, if you want an ASCII table with more complex metadata for the columns please consider using the ECSV format.

Categories

Resources