Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to raise a column in pandas DataFrame to consecutive powers

Is there a pythonic way to raise a column in DataFrame (xRaw) to consecutive powers? Is there something like

xRaw[:,k] = xRaw.pow(k) for k in range(1,6)
like image 1000
Alex Avatar asked Oct 11 '19 20:10

Alex


People also ask

How do you do exponents in pandas?

The exponential of any column is found out by using numpy. exp() function. This function calculates the exponential of the input array/Series. Return: An array with exponential of all elements of input array/Series.

How do you repeat a panda series?

Pandas Series: repeat() functionThe repeat() function is used to repeat elements of a Series. Returns a new Series where each element of the current Series is repeated consecutively a given number of times. The number of repetitions for each element. This should be a non-negative integer.

How do I make a column the same value in Python?

Practical Data Science using Python To add anew column with constant value, use the square bracket i.e. the index operator and set that value.


1 Answers

This is a Vandermonde matrix, which numpy has a built-in function for np.vander

If you have

s = pd.Series([1,2,3,4,5])

Then

np.vander(s, 6)

array([[   1,    1,    1,    1,    1,    1],
       [   1,    2,    4,    8,   16,   32],
       [   1,    3,    9,   27,   81,  243],
       [   1,    4,   16,   64,  256, 1024],
       [   1,    5,   25,  125,  625, 3125]])

To add back to a df, you can use concat

df = pd.concat([df, pd.DataFrame(vander)], axis=1)
like image 115
rafaelc Avatar answered Oct 16 '22 01:10

rafaelc