如何找到两行之间的差异并将结果除以两行之和?
这是在Excel中的操作方法。
这是我要使用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)
答案 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}}