簡體   English   中英

如何將行轉置為 Pandas 中的列?

[英]How to transpose rows to columns in Pandas?

我正在將 SQL 查詢的結果寫入 Excel 工作表並嘗試將行轉置為列,但似乎無法讓 Pandas 做出讓步; Excel 似乎存在某種難題。 我看過:

如何在熊貓數據框中切換列行

如何在 groupby 之后將數據框中的行值轉換為 Python 中的列標簽?

在 Python Pandas 中將列轉換為行

Python Pandas:將行轉換為列標題

似乎沒有一個工作。

import psycopg2
import pandas as pd
import xlsxwriter

try:
    conn = psycopg2.connect(private stuff cannot be shared)
except:
    print ("I am unable to connect to the database")

cursor = conn.cursor()

writer = pd.ExcelWriter("Z:/AWS/SQLQueries/Phoebe's Request.xlsx",engine = 'xlsxwriter')

query20 = """SELECT 2 AS rowtype
 , source AS "TrafficTypes_Name"
 , COUNT(source) AS "Traffic"
 , to_char(week,'MM/dd/yyyy') AS "Week_Ending"
FROM amazon.tracker
where project_id = 'PCR'
GROUP 
BY source
 , to_char(week,'MM/dd/yyyy')
UNION ALL
SELECT 1 
 , 'Visitor Center Walk-ins'
 , COUNT(source)
 , to_char(week,'MM/dd/yyyy') as week 
FROM amazon.tracker
where project_id = 'PCR'
GROUP 
BY to_char(week,'MM/dd/yyyy')
ORDER 
BY "Week_Ending"
 , rowtype"""

cursor.execute(query20)

result = cursor.fetchall()

first = pd.DataFrame(result, columns = ["rowtype","TrafficTypes_Name","Traffic","Week_Ending"])

first.drop(first.columns[0],axis=1, inplace = True)

first.pivot(index = 'Week_Ending', columns = 'TrafficTypes_Name' , values = 'Traffic' )

first.to_excel(writer, sheet_name = 'Visitor Traffic',index = False)

print ("Query 20 Created")

writer.save()

Excel表格:

TrafficTypes_Name       Traffic          Week_Ending

Visitor Center Walk-ins   18             01/01/2017
Resident Referral          1             01/01/2017
Community Website          1             01/01/2017
Realtor                    1             01/01/2017
Other Website              1             01/01/2017
Social Media               1             01/01/2017
Builder                    3             01/01/2017
Drive-by                   10            01/01/2017

要求:

Week_Ending    Visitor Center Walk-ins       Resident Referral         Community Website            Realtor  ....................
01/01/2017          18                        1                           1                             1  .........................

樞軸在這里工作

df1 = df.pivot(index='Week_Ending', columns='TrafficTypes_Name', values='Traffic')


TrafficTypes_Name   Builder CommunityWebsite    Drive-by    OtherWebsite    Realtor ResidentReferral    SocialMedia VisitorCenterWalk-ins
Week_Ending                             
01/01/2017          3       1                   10          1               1       1                   1            18

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM