Ham*_*ami 5 python numpy data-analysis dataframe pandas
0 1.0 25.0
1 1.0 31.0
2 2.0 97.0
3 1.0 25.0
4 1.0 26.0
Run Code Online (Sandbox Code Playgroud)
我想要得到一个索引从 1 到(包括 97)的数组,表示每个索引是间隔中有多少次,例如 1 是 4 个间隔(前两个和最后两个间隔),3 是 5 个间隔,96 是就在 1 个间隔内。请注意,我不能使用循环,我必须使用数组操作(numpy,pandas)来完成它。
我想要得到类似的东西:
1 4
2 5
3 5
.
.
.
25 5
26 3
27 2
28 2
29 2
30 2
31 2
32 1
33 1
34 1
.
.
.
97 1
Run Code Online (Sandbox Code Playgroud)
首先我们需要知道每个值的开盘价和收盘价区间有多少:
>>> df
col_1 col_2
0 1.0 25.0
1.0 1.0 31.0
2.0 2.0 97.0
3.0 1.0 25.0
4.0 1.0 26.0
>>> idx = pd.RangeIndex(1, 98)
>>> opencount = df['col_1'].value_counts().reindex(idx, fill_value=0)
>>> closecount = df['col_2'].value_counts().reindex(idx, fill_value=0)
>>> opencount
1 3
2 1
3 0
4 0
5 0
..
93 0
94 0
95 0
96 0
97 0
Name: col_1, Length: 97, dtype: int64
>>> closecount
1 0
2 0
3 0
4 0
5 0
..
93 0
94 0
95 0
96 0
97 1
Name: col_2, Length: 97, dtype: int64
Run Code Online (Sandbox Code Playgroud)
请注意,我们过去常常在和reindex中不可用的所有值处添加零。col_1col_2
如果实际上间隔的结尾包含在间隔中(根据注释),您只需将其closecount向下移动 1:
>>> closecount = closecount.shift(fill_value=0)
>>> closecount
1 0
2 0
3 0
4 0
5 0
..
93 0
94 0
95 0
96 0
97 0
Name: col_2, Length: 97, dtype: int64
Run Code Online (Sandbox Code Playgroud)
然后我们可以计算每个点的区间数,即之前打开的区间的总和减去之前关闭的区间的总和。这可以通过以下方式完成cumsum
>>> opencount.cumsum() - closecount.cumsum()
1 4
2 5
3 5
4 5
5 5
..
93 1
94 1
95 1
96 1
97 1
Length: 97, dtype: int64
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
381 次 |
| 最近记录: |