用Pandas计算delta列[英] Compute delta column with Pandas

本文是小编为大家收集整理的关于用Pandas计算delta列的处理方法,想解了用Pandas计算delta列的问题怎么解决?用Pandas计算delta列问题的解决办法?那么可以参考本文帮助大家快速定位并解决问题。

问题描述

我有一个如下所示的数据框:

 Name Variable Field
A   2.3 412
A   2.9 861
A   3.5 1703
B   3.5 1731
A   4.0 2609
B   4.0 2539
A   4.6 2821
B   4.6 2779
A   5.2 3048
B   5.2 2979
A   5.8 3368
B   5.8 3216

如您所见,"变量"列的值重复.我想计算 A 和 B 之间每个变量的增量 (%).我要生成的数据框是:

    Name  Variable  Field   Ref field (A)   Delta (A - B)
    A   2.3 412     412     0.0%
    A   2.9 861     861     0.0%
    A   3.5 1703    1703    0.0%
    B   3.5 1731    1703    -1.6%
    A   4.0 2609    2609    0.0%
    B   4.0 2539    2609    2.8%
    A   4.6 2821    2821    0.0%
    B   4.6 2779    2821    1.5%
    A   5.2 3048    3048    0.0%
    B   5.2 2979    3048    2.3%
    A   5.8 3368    3368    0.0%
    B   5.8 3216    3368    4.7%

我已经用 panda 尝试了一些东西,比如:

df["Ref field (A)"] = df.apply(lambda row:df[(df["Variable"] == row["Variable"]) & (df["Name"] == "A")]["Field"][0],axis=1)

但它只是不起作用......:

    File "pandas/_libs/index.pyx", line 106, in pandas._libs.index.IndexEngine.get_value
    File "pandas/_libs/index.pyx", line 114, in pandas._libs.index.IndexEngine.get_value
    File "pandas/_libs/index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc
    File "pandas/_libs/hashtable_class_helper.pxi", line 958, in pandas._libs.hashtable.Int64HashTable.get_item
    File "pandas/_libs/hashtable_class_helper.pxi", line 964, in pandas._libs.hashtable.Int64HashTable.get_item
    KeyError: (0, u'occurred at index 0')   

有什么简单可行的想法吗?谢谢

推荐答案

每个 'Variable' 组只有一个 'A' 值,创建一个 Series 并映射这些值以获取引用.

s = df[df.Name.eq('A')].set_index('Variable').Field
df['RefA'] = df.Variable.map(s)

df['Delta'] = (df.RefA - df.Field)/df.Field*100

输出:(在唯一的B组和C组的末尾添加一行)

   Name  Variable  Field    RefA     Delta
0     A       2.3    412   412.0  0.000000
1     A       2.9    861   861.0  0.000000
2     A       3.5   1703  1703.0  0.000000
3     B       3.5   1731  1703.0 -1.617562
4     C       3.5   1761  1703.0 -3.293583
5     A       4.0   2609  2609.0  0.000000
6     B       4.0   2539  2609.0  2.756991
7     A       4.6   2821  2821.0  0.000000
8     B       4.6   2779  2821.0  1.511335
9     A       5.2   3048  3048.0  0.000000
10    B       5.2   2979  3048.0  2.316213
11    A       5.8   3368  3368.0  0.000000
12    B       5.8   3216  3368.0  4.726368
13    B       6.5   1231     NaN       NaN

本文地址:https://www.itbaoku.cn/post/1728078.html