基于移位值/递归算法的级数计算

时间:2018-10-20 04:55:45

标签: python pandas dataframe recursion series

我有以下内容:

Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
Debug.Log("Did Hit");

此行基本上只接受df ['Alpha'],而不接受df ['PositionLong']。shift(1)。它无法识别它,但我不明白为什么?

它产生了这个:

df['PositionLong'] = 0
df['PositionLong'] = np.where(df['Alpha'] == 1, 1, (np.where(np.logical_and(df['PositionLong'].shift(1) == 1, df['Bravo'] == 1), 1, 0)))

但是我想要的代码是这样的:

df['Alpha']  df['Bravo']   df['PositionLong']
0               0             0
1               1             1
0               1             0
1               1             1
1               1             1

我相信解决方案是循环每一行,但这将花费很长时间。

你能帮我吗?

1 个答案:

答案 0 :(得分:2)

您正在寻找递归函数,因为先前的PositionLong值取决于Alpha,而PositionLong本身就是用来确定numpy.where的。

但是df['PositionLong'].shift(1)是常规函数,因此0被评估为一系列0值,因为您使用from numba import njit @njit def rec_algo(alpha, bravo): res = np.empty(alpha.shape) res[0] = 1 if alpha[0] == 1 else 0 for i in range(1, len(res)): if (alpha[i] == 1) or ((res[i-1] == 1) and bravo[i] == 1): res[i] = 1 else: res[i] = 0 return res df['PositionLong'] = rec_algo(df['Alpha'].values, df['Bravo'].values).astype(int) 初始化了序列。

手动循环不必太昂贵。您可以使用numba有效地实现递归算法:

print(df)

   Alpha  Bravo  PositionLong
0      0      0             0
1      1      1             1
2      0      1             1
3      1      1             1
4      1      1             1

结果:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.size = {

total_size_1 : {s_size : "1st size", a : "10", b : "7"}, 
total_size_2 : {s_size : "2nd size", a : "12", b : "4"},
total_size_3 : {s_size : "3rd size", a : "11", b : "1"}
}
});