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)
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)
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)
Numpy broadcast
s.values**np.arange(6)[:,None]
Out[70]:
array([[ 1, 1, 1, 1, 1],
[ 2, 4, 8, 16, 32],
[ 3, 9, 27, 81, 243],
[ 4, 16, 64, 256, 1024],
[ 5, 25, 125, 625, 3125]], dtype=int64)
Assign it back
s= pd.concat([s, pd.DataFrame(s.values**np.arange(6)[:,None],index=s.index)], axis=1)
I would do:
for i in range(6):
xRaw["power: "+str(i)] = xRaw[column_to_be_raised] ** i
This is will generate a new column that takes its base from the column you want to raise for each exponent in the given range.