如何找到两行之间的差异,然后将结果除以两行之和?

时间:2019-04-05 03:11:21

标签: python python-3.x pandas

如何找到两行之间的差异并将结果除以两行之和?

这是在Excel中的操作方法。

enter image description here

这是我要使用Python复制的公式。

=ABS(((B3-B2)/(B3+B2)/2)/((A3-A2)/(A3+A2)/2))

我知道可以使用df.diff()来计算差异,但是我不知道该如何求和。

import pandas as pd
data = {'Price':[50,46],'Quantity':[3,6]}
df = pd.DataFrame(data)
print(df)

3 个答案:

答案 0 :(得分:3)

基本上,您已经有 # Set up a key handler that cancels the prompt on pressing ESC (as Ctrl-C would). Set-PSReadLineKeyHandler -Key Escape -Function CancelLine try { # Prompt the user: Write-Host -NoNewline 'Enter account name you wish to disable: ' $_Name = PSConsoleHostReadLine # If ESC was pressed, $_Name will contain the empty string. # Note that you won't be able to distinguish that from the user # just pressing ENTER. $canceled = $_Name -eq '' # ... act on potential cancellation } finally { # Remove the custom Escape key handler. Remove-PSReadlineKeyHandler -Key Escape } ,然后已经有两行diff

  

sum以来:diff

根据您的情况,总和可以通过

计算
x[2]-x[1] Then 'sum' : x[2]+x[1]=x[2]*2-(x[2]-x[1])

所以输出是

df*2-df.diff()
Out[714]: 
   Price  Quantity
0    NaN       NaN
1   96.0       9.0

答案 1 :(得分:3)

可以使用窗口大小为2的num_times = 3 j = 0 list_trial = [] while j < num_times: my_guess = 0 counter = 0 num = random.randint(1, 3) while my_guess != num: my_guess = int(input('Make a guess --> ')) counter += 1 if my_guess < num: print('Too low!') elif my_guess > num: print('Too high!') else: print('Finally, you got it !') print('It took you ' + str(counter) + ' tries...') list_trial.append(counter) j += 1 print(list_trial) # prints the number of trials... print(sum(list_trial) / len(list_trial)) # prints the average of the trials...

rolling.sum

答案 2 :(得分:2)

对于小型数据帧,使用.eval()效率不高。

以下是某些100.000行的最快处理方法:

df = (df.diff() / df.rolling(2).sum()).div(2) df['result'] = abs(df.Quantity / df.Price)

每个循环32.9 ms ± 1.05 ms

(mean ± std. dev. of 7 runs, 10 loops each) 与 每个循环39.6 ms ± 931 µs的{​​{1}}