Issue
How to expand distance between values in pandas dataframe?
A
1 3
2 5
3 6
5 5
6 9
I want to increase the distance between adjacent elements by x times, for example by two times.
Expected output:
A B
1 3 3
2 5 7 # (3 + 2 * 2)
3 6 9 # (7 + 1 * 2)
5 5 7 # (9 - 1 * 2)
6 9 15 # (7 + 4 * 2)
Solution
You can actually use a vectorial code as suggested by @MatBailie:
df['B'] = df['A']*2 - df['A'].iloc[0]
For generic code with any N
:
N = 2
df['B'] = df['A']*N - df['A'].iloc[0]*(N-1)
Output:
A B(N=1) B(N=2) B(N=3)
1 3 3 3 3
2 5 5 7 9
3 6 6 9 12
5 5 5 7 9
6 9 9 15 21
Some explanation is however needed to understand why:
For each step, assuming a(n)
the current value and b(n)
the output. The output b(n)
is equal to b(n-1) + (a(n) - a(n-1)) * 2
, which is equal to b(n-2) + (a(n-1) - a(n-2)) * 2 + (a(n) - a(n-1)) * 2
which simplifies to b(n-2) + (a(n) - a(n-1)) * 2)
. By recursion, this becomes b(n) = b(0) + (a(n) - a(0))*2
which is b(n) = 2*a(n) - a(0)
if n=2
since b(0)
= a(0)
, in the generic case this is b(n) = a(n)*N - a(0)*(N-1)
.
Output:
A B
1 3 3
2 5 7
3 6 9
5 5 7
6 9 15
Original answer:
You probably can't solve it in a vectorial way since your nth value depends on the output of the step n-1, I believe you must iterate:
def expand_dist(s):
s = list(s)
prev = s[0]
out = []
for v in s:
out.append(prev+(v-prev)*2)
return out
df['B'] = expand_dist(df['A'])
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.