Python:基于数组的方程式



我有一个500行长4列的数据帧。我需要找到合适的python代码,将当前行除以下面的行,然后将该值乘以每列中每一个值的最后一行中的值。我需要基本上复制这个excel公式。

目前尚不清楚您的数据是否存储在Numpy提供的数组中,如果是真的,您会将原始数据包含在a

b = a[-1]*(a[:-1]/a[+1:])

a[-1]是最后一行,a[:-1]是没有最后一行的数组,a[+1:]是没有第一行(索引为零,即(的数组

假设您谈论的是Panda DataFrame

import pandas as pd
import random
# sample DataFrame object 
df = pd.DataFrame((float(random.randint(1, 100)),
float(random.randint(1, 100)),
float(random.randint(1, 100)),
float(random.randint(1, 100)))
for _ in range(10))
def function(col):
for i in range(len(col)-1):
col[i] = (col[i]/col[i+1])*col[len(col)-1]
print(df) # before formula apply
df.apply(function)
print(df) # after formula apply
>>>
0     1     2      3
0  10.0  78.0  27.0   23.0
1  72.0  42.0  77.0   86.0
2  82.0  12.0  58.0   98.0
3  27.0  92.0  19.0   86.0
4  48.0  83.0  14.0   43.0
5  55.0  18.0  58.0   77.0
6  20.0  58.0  20.0   22.0
7  76.0  19.0  63.0   82.0
8  23.0  99.0  58.0   15.0
9  60.0  57.0  89.0  100.0
0           1           2           3
0    8.333333  105.857143   31.207792   26.744186
1   52.682927  199.500000  118.155172   87.755102
2  182.222222    7.434783  271.684211  113.953488
3   33.750000   63.180723  120.785714  200.000000
4   52.363636  262.833333   21.482759   55.844156
5  165.000000   17.689655  258.100000  350.000000
6   15.789474  174.000000   28.253968   26.829268
7  198.260870   10.939394   96.672414  546.666667
8   23.000000   99.000000   58.000000   15.000000
9   60.000000   57.000000   89.000000  100.000000

最新更新