Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8967591
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T17:16:40+00:00 2026-06-15T17:16:40+00:00

I have lots of data in PostgreSQL. But I need to do some pivot

  • 0

I have lots of data in PostgreSQL. But I need to do some pivot tables like it does SPSS.
For example i have table with cities and states.

 create table cities
(
    city integer,
    state integer
);
insert into cities(city,state) values (1,1);
insert into cities(city,state) values (2,2);
insert into cities(city,state) values (3,1);
insert into cities(city,state) values (4,1);

Actually in this table i have 4 cities and 2 states.
I want to do pivot table with percentage like

city\state |state-1| state-2|
city1      |33%    |0%      |
city2      |0%     |100%    |
city3      |33%    |0%      |
city4      |33%    |0%      |
totalCount |3      |1       |

I understant how do to this in this particulary case with sql. But all i want is to cross one variable by another (just count distinct values and devide it by “count(*) where variable_in_column_names=1 and so on) using some stored function. Im looking now at plpython.Some my questions are:

  1. How to output set of records with not having temporary table with
    shape that fits number and type of output columns.
  2. Maybe there is working solutions?

As i can see, input will be table name, column name of first variable, column name of second variable. Doing lots of queries in function’s body (count(*),loop thru every distinct value in variables and count it and so on) and then return a table with percentage.

  1. Actually i dont have a lot of rows in one query(about 10k), and
    may be the best way to do such things in raw python,not plpython?
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T17:16:41+00:00Added an answer on June 15, 2026 at 5:16 pm

    You might want to give pandas a try, which is an excellent python data analysis library.

    To query a PostgreSQL database:

    import psycopg2
    import pandas as pd
    from pandas.io.sql import frame_query
    
    conn_string = "host='localhost' dbname='mydb' user='postgres' password='password'"
    conn = psycopg2.connect(conn_string)
    df = frame_query('select * from cities', con=conn)
    

    Where df is a DataFrame like:

        city    state
    0    1   1
    1    2   2
    2    3   1
    3    4   1
    

    You can then create a pivot table using pivot_table and dividing by the total to get percentages:

    totals = df.groupby('state').size()
    pivot = pd.pivot_table(df, rows='city', cols='state', aggfunc=len, fill_value=0) / totals
    

    Giving you the result:

    state   1   2
    city        
    1    0.333333   0
    2    0          1
    3    0.333333   0
    4    0.333333   0
    

    Finally to get the layout you want, you just need to rename the index and columns, and append the totals:

    totals_frame = pd.DataFrame(totals).T
    totals_frame.index = ['totalCount']
    
    pivot.index = ['city%i' % item for item in pivot.index]
    final_result = pivot.append(totals_frame)
    final_result.columns  = ['state-%i' % item for item in final_result.columns]
    

    Giving you:

                state-1     state-2
    city1       0.333333    0
    city2       0.000000    1
    city3       0.333333    0
    city4       0.333333    0
    totalCount  3.000000    1
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have lots of tables with statistical data (environment related) and wondering if there
I have a htlm table with lots of data the user might want to
I have lots of data to display on the Google Map but what I
So I have lots of application data for my application. However, This data does
i have lots of data like this 1:0x00a4c7d9fb3849... 2:0x79821309bd789c7689c97... 3:0x0178dce67fe898... they are more than
I have lots of math to do on lots of data but it's all
I have lots of data in a UITableView but I don't want any of
I have lots of data. I would like to make a formula to use
I have lots of data like this type1, type2, type3 aax, ert, ddd asx,
We (my company) runs a website which have lots of data recorded like user

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.