Pandas:计算随时间变化的群组之间的比率

huangapple go评论66阅读模式
英文:

Pandas: calculate ratio between groups over time

问题

我有一个类似这样的数据框:

    时间  类型   值
0   t1    类型1  值1
1   t2    类型1  值2
2   t3    类型1  值3
3   t1    类型2  值4
4   t2    类型2  值5
5   t3    类型2  值6

我想创建的是另一列,该列是在匹配时间步骤上计算的类型1和类型2的值之间的比率,如下所示:

    时间  类型   值 比率
0   t1    类型1  值1   v1/v1
1   t2    类型1  值2   v2/v2
2   t3    类型1  值3   v3/v3
3   t1    类型2  值4   v4/v1
4   t2    类型2  值5   v5/v2
5   t3    类型2  值6   v6/v3

基本上,我想计算随时间变化的类型1与类型2的比率。我看了这个链接:https://stackoverflow.com/questions/50892309/pandas-for-each-group-calculate-ratio-of-two-categories-and-append-as-a-new-col,但我还没有完全适应到我的情况。

英文:

I have a dataframe that looks something like this:

    time  type   values
0   t1    type1  v1
1   t2    type1  v2
2   t3    type1  v3
3   t1    type2  v4
4   t2    type2  v5
5   t3    type2  v6

What I would like to create, is another column that is the ratio between the values of type1 and type2 calculated at matched up time steps, like this:

    time  type   values ratio
0   t1    type1  val1   v1/v1
1   t2    type1  val2   v2/v2
2   t3    type1  val3   v3/v3
3   t1    type2  val4   v4/v1
4   t2    type2  val5   v5/v2
5   t3    type2  val6   v6/v3

Basically I want to calculate the ratio of type1 to type2 over time.

I looked at this: https://stackoverflow.com/questions/50892309/pandas-for-each-group-calculate-ratio-of-two-categories-and-append-as-a-new-col

But I haven't quite been able to adapt this to my situation.

答案1

得分: 2

你可以使用.div.map,其中map作用于dftime列,与"type1"子集相对应:

df["ratio"] = df["values"].div(
    df["time"].map(
        df[df["type"].eq("type1")].set_index("time")["values"]))
英文:

You can use .div with .map, where the map is on the time column against a "type1" subset of df:

df["ratio"] = df["values"].div(
    df["time"].map(
        df[df["type"].eq("type1")].set_index("time")["values"]))

huangapple
  • 本文由 发表于 2023年5月18日 00:03:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76274067.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定