Python 即使列中不存在数据,也可以使用自定义列进行透视
我有以下示例表:Python 即使列中不存在数据,也可以使用自定义列进行透视,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,我有以下示例表: df = pd.DataFrame({'Name': ['Bob', 'Bob', 'Susan', 'Susan', 'Jane','Jane'], 'Status': ['Paid', 'Paid', 'Paid OTP', 'Overdue', '', 'Upsell'], 'Amt': [100, 200, 300, 200, 0,60]}) 我正在尝试创建一个透视表,该透视表使用以下代码:
df = pd.DataFrame({'Name': ['Bob', 'Bob', 'Susan', 'Susan', 'Jane','Jane'],
'Status': ['Paid', 'Paid', 'Paid OTP', 'Overdue', '', 'Upsell'],
'Amt': [100, 200, 300, 200, 0,60]})
我正在尝试创建一个透视表,该透视表使用以下代码:
table = pd.pivot_table(df, values='Amt', index=['Name'],columns=['Status'], aggfunc=np.sum, fill_value=0)
但是,我需要包含一个持久列,例如:无论表中是否有值,都要支付。
这样做的原因是,如果为该特定月份填写了“待付款”,则显示0值
python:3.6.8
pandas:0.25.0用于在列名称中添加新值(如果不存在):
您还可以将“状态”列转换为类别,并确保“待付款”是当前类别,即使该类别未在数据中表示
df = pd.DataFrame({'Name': ['Bob', 'Bob', 'Susan', 'Susan', 'Jane','Jane'],
'Status': ['Paid', 'Paid', 'Paid OTP', 'Overdue', '', 'Upsell'],
'Amt': [100, 200, 300, 200, 0,60]})
df["Status"] = pd.Categorical(df["Status"])
if "To Be Paid" not in df["Status"].cat.categories:
df["Status"].cat.add_categories("To Be Paid", inplace=True)
df.pivot_table(values='Amt', index='Name', columns='Status', aggfunc=np.sum, fill_value=0, dropna=False)
Status Overdue Paid Paid OTP Upsell To Be Paid
Name
Bob 0 0 300 0 0 0
Jane 0 0 0 0 60 0
Susan 0 200 0 300 0 0
df = pd.DataFrame({'Name': ['Bob', 'Bob', 'Susan', 'Susan', 'Jane','Jane'],
'Status': ['Paid', 'Paid', 'Paid OTP', 'Overdue', '', 'Upsell'],
'Amt': [100, 200, 300, 200, 0,60]})
df["Status"] = pd.Categorical(df["Status"])
if "To Be Paid" not in df["Status"].cat.categories:
df["Status"].cat.add_categories("To Be Paid", inplace=True)
df.pivot_table(values='Amt', index='Name', columns='Status', aggfunc=np.sum, fill_value=0, dropna=False)
Status Overdue Paid Paid OTP Upsell To Be Paid
Name
Bob 0 0 300 0 0 0
Jane 0 0 0 0 60 0
Susan 0 200 0 300 0 0