亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Pandas 計算增量列

使用 Pandas 計算增量列

瀟瀟雨雨 2021-11-09 20:25:09
我有一個如下所示的數據框: Name Variable FieldA   2.3 412A   2.9 861A   3.5 1703B   3.5 1731A   4.0 2609B   4.0 2539A   4.6 2821B   4.6 2779A   5.2 3048B   5.2 2979A   5.8 3368B   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%我已經用熊貓嘗試了一些東西,比如: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')   有什么簡單可行的想法嗎?謝謝
查看完整描述

1 回答

?
富國滬深

TA貢獻1790條經驗 獲得超9個贊

每組只有一個'A'值'Variable',創建一個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


查看完整回答
反對 回復 2021-11-09
  • 1 回答
  • 0 關注
  • 323 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號