英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论