【问题标题】:Pandas dataframe :convert the numeric value to 2 to power of numeric valuePandas dataframe:将数值转换为2的数值次方
【发布时间】:2023-02-04 04:49:04
【问题描述】:

enter image description here 我如何在 df 的另一个列中获得这个 2^ 值

我需要计算 2^ 值 有没有简单的方法可以做到这一点

Value 2^Value
0 1
1 2

【问题讨论】:

    标签: python pandas dataframe numeric calc


    【解决方案1】:

    您可以使用 numpy.power

    import numpy as np
    
    df["2^Value"] = np.power(2, df["Value"])
    

    的 输出 :

    print(df)
    
       Value  2^Value
    0      0        1
    1      1        2
    2      3        8
    3      4       16
    

    【讨论】:

    • 有没有你不能使用2 ** df["Value"]的原因?
    【解决方案2】:

    您可以将 .apply 与 lambda 函数一起使用

    df["new_column"] = df["Value"].apply(lambda x: x**2)
    

    在 python 中,幂运算符是**

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-06
      • 1970-01-01
      • 1970-01-01
      • 2019-08-04
      • 2020-02-10
      • 2023-03-31
      相关资源
      最近更新 更多