我有一個關于pivot_table python pandas 的問題。
我有一個這樣的資料框
Agent Detail Value
report1 General Section YESS
report1 jobID 558
report1 Priority normal
report1 Run As Owner's Credentials
report1 Schedule Section
report1 disabled TRUE
report1 timeZoneId None
report1 startImmediately FALSE
report1 repeatMinuteInterval None
report1 start date None
report1 start time None
report1 Email Recipient [email protected]
report1 Email Recipient [email protected]
report2 General Section YESS
report2 jobID 559
report2 Priority normal
report2 Run As Owner's Credentials
report2 Schedule Section
report2 disabled TRUE
report2 timeZoneId None
report2 startImmediately FALSE
report2 repeatMinuteInterval None
report2 start date None
report2 start time None
report2 Email Recipient [email protected]
report2 Email Recipient [email protected]
我正在嘗試旋轉資料框并將所有詳細值轉換為列。索引是代理欄位,它是一個報告名稱。每個報告可以有多個收件人。我需要為每個報告的收件人提供每一行。示例輸出如下:
[在此處輸入圖片說明]

我目前的代碼如下:
import csv
import pandas as pd
resultsFile = 'C:\\Oracle\\testfile.csv' #input to transpose file
df=pd.read_csv(resultsFile,skip_blank_lines=True)
df2=df.pivot_table(index='Agent',columns='Detail',values='Value',aggfunc='sum')
df2
這是連接單個欄位中的電子郵件地址,這不是我要找的?如何使用重復的列值旋轉 df 并將它們轉換為多行?
謝謝你的幫助
uj5u.com熱心網友回復:
您可以將您的 df 分組agent并旋轉這些組(以原始索引作為索引)。您必須填充 NaN 值并洗掉重復項,因為每個值都會得到一行:
reports = []
for a, sub_df in df.groupby('Agent'):
rep = sub_df.pivot(None, 'Detail', 'Value').ffill().bfill().drop_duplicates()
rep.insert(0, 'Agent', a)
reports.append(rep)
result = pd.concat(reports).reset_index()
print(result)
輸出:
Detail Agent Email Recipient General Section Priority Run As ... repeatMinuteInterval start date start time startImmediately timeZoneId
0 report1 [email protected] YESS normal Owner's Credentials ... None None None FALSE None
1 report1 [email protected] YESS normal Owner's Credentials ... None None None FALSE None
2 report2 [email protected] YESS normal Owner's Credentials ... None None None FALSE None
3 report2 [email protected] YESS normal Owner's Credentials ... None None None FALSE None
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/376310.html
