亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Pandas 數據透視表查詢中創建包含日期的字典?

如何在 Pandas 數據透視表查詢中創建包含日期的字典?

料青山看我應如是 2023-10-18 11:03:36
我有一個如下所示的數據框:- 我需要創建一個 Pandas 數據透視表,它將輸出如下表:也就是說,它將所有小于 20 年 10 月 1 日的日期匯總為逾期,然后正常匯總從 20 年 10 月 1 日起的所有日期。下面的代碼是我到目前為止所想出的。#!/usr/bin/env python3import pandas as pdimport numpy as np# creating a data frame df = pd.read_csv("CSVData2.csv") table = pd.pivot_table(data=df,index=['Code'], columns=['Process Month'], values = ['Number'], aggfunc=sum)print(table)
查看完整描述

1 回答

?
qq_笑_17

TA貢獻1818條經驗 獲得超7個贊

也許這對你有用?


# Recreating your dataframe in code

df = pd.DataFrame({'Code':'A1 P2 B3 B3 C4 A1 B3 A1 A1'.split(' '),

                  'Branch':'UW2 RQ2 UW2 UW2 X01 X01 DN9 PE7 PE7'.split(' '),

                  'Process Month':'01-Oct-20 01-Nov-20 01-Sep-20 01-Sep-20 01-Aug-20 01-Oct-20 01-Sep-20 01-Dec-20 01-Sep-20'.split(' '),

                  'Number':[1]*9})


#Change string to datetime dtype

df['Process Month'] = pd.to_datetime(df['Process Month'])


# Create mask to defined 'Overdue'    

m = df['Process Month'] < '01-Oct-20'


# Output Process Month back as string

df['Process Month'] = df['Process Month'].dt.strftime('%d-%b-%Y')


# Overwriting Process Month with 'OverDue' per mask above

df.loc[m, 'Process Month'] = 'OverDue'


# Creating a crosstab with totals

df_out = pd.crosstab(df['Code'], df['Process Month'], margins=True, margins_name='Total')


df_out.drop('Total', axis=1) #Don't need row Totals column

輸出:


Process Month  01-Dec-2020  01-Nov-2020  01-Oct-2020  OverDue

Code                                                         

A1                       1            0            2        1

B3                       0            0            0        3

C4                       0            0            0        1

P2                       0            1            0        0

Total                    1            1            2        5


查看完整回答
反對 回復 2023-10-18
  • 1 回答
  • 0 關注
  • 133 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號