How do i get this 2^ value in another col of a df
i need to calculate 2^ value is there a easy way to do this
Value | 2^Value |
---|---|
0 | 1 |
1 | 2 |
CodePudding user response:
CodePudding user response:
Using rpow
:
df['2^Value'] = df['Value'].rpow(2)
Output:
Value 2^Value
0 0 1
1 1 2
2 2 4
3 3 8
4 4 16
CodePudding user response:
You can use .apply
with a lambda function
df["new_column"] = df["Value"].apply(lambda x: x**2)
In python the power operator is **
CodePudding user response:
You can apply a function to each row in a dataframe by using the df.apply method. See this documentation to learn how the method is used. Here is some untested code to get you started.
# 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 code is a modified version of the code from this G4G example