如何绘制长格式数据集中分类列的比率?
How does one plot the ratio of of a categorical column in a long form data set?
我有一个包含列 type
和 date
的长格式数据集。 type
有两个类别 gold
和 silver
。我想按日期绘制两者的比率。为此,必须进行一系列转变。他们在 pandas
中看起来像这样
mock_df = df.groupby(["date"])["type"].value_counts().unstack()
mock_df["gs_ratio"] = mock_df["gold"]/mock_df["silver"]
mock_df
数据
import pandas
df = pd.DataFrame.from_records([
{"date": "2020-04-20", "type": "gold"},
{"date": "2020-04-20", "type": "silver"},
{"date": "2020-04-20", "type": "silver"},
{"date": "2020-04-21", "type": "gold"},
{"date": "2020-04-21", "type": "gold"},
{"date": "2020-04-21", "type": "silver"},
{"date": "2020-04-22", "type": "gold"},
{"date": "2020-04-22", "type": "silver"},
{"date": "2020-04-22", "type": "silver"},
{"date": "2020-04-22", "type": "silver"}
])
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_counts()
。你应该做的是使用 count()
按 type
. 分组
- 使用
transform_aggregate
而不是transform_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"
)
我有一个包含列 type
和 date
的长格式数据集。 type
有两个类别 gold
和 silver
。我想按日期绘制两者的比率。为此,必须进行一系列转变。他们在 pandas
mock_df = df.groupby(["date"])["type"].value_counts().unstack()
mock_df["gs_ratio"] = mock_df["gold"]/mock_df["silver"]
mock_df
数据
import pandas
df = pd.DataFrame.from_records([
{"date": "2020-04-20", "type": "gold"},
{"date": "2020-04-20", "type": "silver"},
{"date": "2020-04-20", "type": "silver"},
{"date": "2020-04-21", "type": "gold"},
{"date": "2020-04-21", "type": "gold"},
{"date": "2020-04-21", "type": "silver"},
{"date": "2020-04-22", "type": "gold"},
{"date": "2020-04-22", "type": "silver"},
{"date": "2020-04-22", "type": "silver"},
{"date": "2020-04-22", "type": "silver"}
])
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_counts()
。你应该做的是使用count()
按type
. 分组
- 使用
transform_aggregate
而不是transform_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"
)