Pandas Dataframe :将数值转换为2的数值幂

ac1kyiln  于 2023-02-07  发布在  其他
关注(0)|答案(4)|浏览(128)

如何在df的另一列中得到这个2^值
我需要计算2^值有简单的方法吗
| 价值|2 ^值|
| - ------|- ------|
| 无|1个|
| 1个|第二章|

6vl6ewon

6vl6ewon1#

您可以使用numpy.power

import numpy as np

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

或者简单地说,如@* B Remmelzwaal * 所建议的2 ** df["Value"]
输出:

print(df)

   Value  2^Value
0      0        1
1      1        2
2      3        8
3      4       16
  • 以下是一些统计数据/时间:*

kiz8lqtg

kiz8lqtg2#

使用rpow

df['2^Value'] = df['Value'].rpow(2)

输出:

Value  2^Value
0      0        1
1      1        2
2      2        4
3      3        8
4      4       16
kqlmhetl

kqlmhetl3#

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

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

在python中,幂运算符是**

bq9c1y66

bq9c1y664#

你可以通过使用df.apply方法对 Dataframe 中的每一行应用一个函数。参见this documentation来学习如何使用这个方法。这里有一些未经测试的代码可以帮助你入门。

# a simple function that takes a number and returns
# 2^n of that number
def calculate_2_n(n):
    return 2**n

# use the df.apply method to apply that function to each of the 
# cells in the 'Value' column of the DataFrame
df['2_n_value'] = df.apply(lambda row : calculate_2_n(row['Value']), axis = 1)

此代码是this G4G example中代码的修改版本

相关问题