Python 3.x 如何在长格式数据集中绘制分类列的比率?

Python 3.x 如何在长格式数据集中绘制分类列的比率?,python-3.x,altair,Python 3.x,Altair,我有一个长格式的数据集,其中有一列type和date类型分为两类黄金和白银。我想按日期绘出两者的比率。为此,必须进行一系列转换。它们在熊猫中看起来像这样 mock_df = df.groupby(["date"])["type"].value_counts().unstack() mock_df["gs_ratio"] = mock_df["gold"]/mock_df["silver"] mock_df 资料 已尝试的代码: alt.Chart(df).transform_joinagg

我有一个长格式的数据集,其中有一列
type
date
<代码>类型分为两类
黄金
白银
。我想按日期绘出两者的比率。为此,必须进行一系列转换。它们在
熊猫中看起来像这样

mock_df = df.groupby(["date"])["type"].value_counts().unstack()
mock_df["gs_ratio"] = mock_df["gold"]/mock_df["silver"]
mock_df

资料

已尝试的代码:

alt.Chart(df).transform_joinaggregate(
    gs_count='count(type)',
    groupby=["date:T"]
).transform_pivot(
    'type',
    groupby=['date:T'],
    value='gs_count'
).transform_calculate(
    gs_ratio="datum.gold/datum.silver"
).mark_line().encode(
    x='date:T',
    y="gs_ratio:Q"
)

您的方法中有几个问题:

  • 在转换中不能使用类型速记。因此,您应该使用列的实际名称,
    “date”
    ,而不是
    “date:T”
  • count(type)
    不等同于
    df.type.value\u counts()
    。您应该做的是使用
    count()
    type
    分组
  • 使用
    transform\u aggregate
    而不是
    transform\u joinaggregate
综合起来:

alt.Chart(df).transform_aggregate(
    gs_count='count()',
    groupby=["date", "type"]
).transform_pivot(
    'type',
    groupby=['date'],
    value='gs_count'
).transform_calculate(
    gs_ratio="datum.gold/datum.silver"
).mark_line().encode(
    x='date:T',
    y="gs_ratio:Q"
)

alt.Chart(df).transform_aggregate(
    gs_count='count()',
    groupby=["date", "type"]
).transform_pivot(
    'type',
    groupby=['date'],
    value='gs_count'
).transform_calculate(
    gs_ratio="datum.gold/datum.silver"
).mark_line().encode(
    x='date:T',
    y="gs_ratio:Q"
)