在循环内创建一个序列的 Python 数组?

huangapple go评论79阅读模式
英文:

Python - Creating an array for a series within a loop?

问题

I'd like to add values calculated in a for loop to a series so that it can be its own column in a dataframe. So far I've got this: the y values are from a dataframe named block.

N = 12250
for i in range(0, N-1):
    y1 = block.iloc[i]['y']
    y2 = block.iloc[i+1]['y']
    diffy[i] = y2 - y1

I'd like to make diffy its own series instead of just replacing the diffy value on each loop.

英文:

I'd like to add values calculated in a for loop to a series so that it can be its own column in a dataframe. So far I've got this: the y values are from a dataframe named block.

N = 12250
for i in range(0,N-1):
    y1 = block.iloc[i]['y']
    y2 = block.iloc[i+1]['y']
    diffy[i] = y2-y1

I'd like to make diffy its own series instead of just replacing the diffy val on each loop

答案1

得分: 1

以下是已翻译的代码部分:

一些示例数据假设 N = 5):

N = 5

np.random.seed(42)
block = pd.DataFrame({
    'y': np.random.randint(0, 10, N)
})

   y
0  6
1  3
2  7
3  4
4  6

你可以按照以下方式计算 `diffy`:

diffy = block['y'].diff().shift(-1)[:-1]

0   -3.0
1    4.0
2   -3.0
3    2.0
Name: y, dtype: float64

`diffy` 是一个 `pandas.Series`。如果你想要列表请添加 `.to_list()`。如果你想要一个 numpy 数组请添加 `.values`
英文:

Some sample data (assume N = 5):

N = 5

np.random.seed(42)
block = pd.DataFrame({
    'y': np.random.randint(0, 10, N)
})

   y
0  6
1  3
2  7
3  4
4  6

You can calculate diffy as follow:

diffy = block['y'].diff().shift(-1)[:-1]

0   -3.0
1    4.0
2   -3.0
3    2.0
Name: y, dtype: float64

diffy is a pandas.Series. If you want list, add .to_list(). If you want a numpy array, add .values

huangapple
  • 本文由 发表于 2020年1月3日 22:37:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/59580427.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定