Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,950 questions

51,892 answers

573 users

How to transform structured data into a table with multiple columns in Python

2 Answers

0 votes
import pandas as pd
from tabulate import tabulate

data = {
   'name': ['AAA', 'BBBB', 'CCCC'],
   'age': [36, 47, 52],
   'salay_2025': [120000, 90000, 85000],
   'salay_2026': [130000, 100000, 95000]}

df = pd.DataFrame(data)

print(tabulate(df, headers='keys', tablefmt='psql'))



'''
run:

+----+--------+-------+--------------+--------------+
|    | name   |   age |   salay_2025 |   salay_2026 |
|----+--------+-------+--------------+--------------|
|  0 | AAA    |    36 |       120000 |       130000 |
|  1 | BBBB   |    47 |        90000 |       100000 |
|  2 | CCCC   |    52 |        85000 |        95000 |
+----+--------+-------+--------------+--------------+

'''

 



answered 15 hours ago by avibootz
0 votes
import pandas as pd
from tabulate import tabulate

data = {
   'name': ['AAA', 'BBBB', 'CCCC'],
   'age': [36, 47, 52],
   'salay_2025': [120000, 90000, 85000],
   'salay_2026': [130000, 100000, 95000]}

df = pd.DataFrame(data)

melt_df = df.melt(
   id_vars=['name', 'age'],
   value_vars=['salay_2025', 'salay_2026'],
   var_name='year',
   value_name='salary')

print(tabulate(melt_df, headers = 'keys', tablefmt = 'psql'))



'''
run:

+----+--------+-------+------------+----------+
|    | name   |   age | year       |   salary |
|----+--------+-------+------------+----------|
|  0 | AAA    |    36 | salay_2025 |   120000 |
|  1 | BBBB   |    47 | salay_2025 |    90000 |
|  2 | CCCC   |    52 | salay_2025 |    85000 |
|  3 | AAA    |    36 | salay_2026 |   130000 |
|  4 | BBBB   |    47 | salay_2026 |   100000 |
|  5 | CCCC   |    52 | salay_2026 |    95000 |
+----+--------+-------+------------+----------+

'''

 



answered 15 hours ago by avibootz
...