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

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

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.

  1. N = 12250
  2. for i in range(0, N-1):
  3. y1 = block.iloc[i]['y']
  4. y2 = block.iloc[i+1]['y']
  5. 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.

  1. N = 12250
  2. for i in range(0,N-1):
  3. y1 = block.iloc[i]['y']
  4. y2 = block.iloc[i+1]['y']
  5. 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

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

  1. 一些示例数据假设 N = 5):
  2. N = 5
  3. np.random.seed(42)
  4. block = pd.DataFrame({
  5. 'y': np.random.randint(0, 10, N)
  6. })
  7. y
  8. 0 6
  9. 1 3
  10. 2 7
  11. 3 4
  12. 4 6
  13. 你可以按照以下方式计算 `diffy`
  14. diffy = block['y'].diff().shift(-1)[:-1]
  15. 0 -3.0
  16. 1 4.0
  17. 2 -3.0
  18. 3 2.0
  19. Name: y, dtype: float64
  20. `diffy` 是一个 `pandas.Series`如果你想要列表请添加 `.to_list()`如果你想要一个 numpy 数组请添加 `.values`
英文:

Some sample data (assume N = 5):

  1. N = 5
  2. np.random.seed(42)
  3. block = pd.DataFrame({
  4. 'y': np.random.randint(0, 10, N)
  5. })
  6. y
  7. 0 6
  8. 1 3
  9. 2 7
  10. 3 4
  11. 4 6

You can calculate diffy as follow:

  1. diffy = block['y'].diff().shift(-1)[:-1]
  2. 0 -3.0
  3. 1 4.0
  4. 2 -3.0
  5. 3 2.0
  6. 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:

确定