【问题标题】:How can I create a pandas series based on two other series and their index?如何根据其他两个系列及其索引创建熊猫系列?
【发布时间】:2018-03-28 20:13:07
【问题描述】:

给定两个具有相同索引的熊猫系列:

a = pd.DataFrame([5, 11], columns=['A'], index=[1, 2])
b = pd.DataFrame([2, 3], columns=['B'], index=[1, 2])

    A  
1   5  
2  11  

   B  
1  2  
2  3  

什么是创建具有相同索引的新系列的有效方法,其中每个值为(value of A - index) / value of B,即

  C
1 2  (= (5 - 1) / 2)
2 3  (= (11 - 2) / 3)

感谢您的帮助!

编辑:我注意到我的问题的标题是关于系列的,但文本和答案是关于数据框的。因此,如果有人想对系列 a 和 b 做同样的事情,方法如下:(a - a.index) / b

【问题讨论】:

    标签: python pandas indexing


    【解决方案1】:

    你可以这样做:

    c = ((a['A'] - a.index) / b['B'])
    #1    2.0
    #2    3.0
    #dtype: float64
    

    如果您希望将结果作为 DataFrame:

    c = pd.DataFrame(c, columns=["C"])
    print(c)
    #     C
    #1  2.0
    #2  3.0
    

    【讨论】:

      【解决方案2】:

      选项 1

      a.A.sub(a.index).div(b.B).to_frame('C')
      
           C
      1  2.0
      2  3.0
      

      选项 2

      a.join(b).eval('C = (A - index) / B', inplace=False)
      
          A  B    C
      1   5  2  2.0
      2  11  3  3.0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-06
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        • 1970-01-01
        • 2023-01-20
        • 1970-01-01
        相关资源
        最近更新 更多