You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas DataFrame中新增列存储原列数值的2次幂

在Pandas DataFrame中生成某列数值的2次幂列

方法1:使用pow()方法

直接对目标列调用Pandas的pow()方法,指定底数为2,即可生成对应次幂列:

import pandas as pd

# 创建示例DataFrame
df = pd.DataFrame({'Value': [0, 1, 2, 3]})
# 生成2的次幂列
df['2^Value'] = df['Value'].pow(2)

执行后DataFrame结果:

Value2^Value
01
12
24
38

方法2:使用算术运算符**

用Python原生的幂运算符号**,写法更贴近数学表达式:

df['2^Value'] = 2 ** df['Value']

方法3:结合numpy.power()计算

如果需要借助NumPy的计算能力,可使用numpy.power()函数:

import numpy as np

df['2^Value'] = np.power(2, df['Value'])

以上三种方法都能实现需求,前两种在Pandas日常使用中更为便捷。

内容的提问来源于stack exchange,提问作者Saraswathy Rajamani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 15:25:39