import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
output:
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
10 11
11 12
12 13
13 14
14 15
15 16
16 17
17 18
18 19
19 20
dtype: int64
我想通过以下内容将系列划分为4个系列:
- 第一个系列将包含1-5之间的数字
- 第二个系列将包含6-10之间的数字
- 第三个系列将包含11-15之间的数字
- 第四个系列将包含16-20之间的数字
尝试使用:
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20])
s1 = s[0:5]
s2 = s[5:10]
s3 = s[10:15]
s4 = s[15:]
您可以使用numpy
的array_split()
s_split = np.array_split(s, 4)
[0 1
1 2
2 3
3 4
4 5
dtype: int64,
5 6
6 7
7 8
8 9
9 10
dtype: int64,
10 11
11 12
12 13
13 14
14 15
dtype: int64,
15 16
16 17
17 18
18 19
19 20
dtype: int64]
通过s_split[0],..s_split[1]
访问它们
使用numpy.array_split(https://numpy.org/doc/stable/reference/generated/numpy.array_split.html)!
这将把一个数组拆分为多个子数组。
import numpy as np
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
result = np.array_split(s, 4)
result
Out[2]:
[0 1
1 2
2 3
3 4
4 5
dtype: int64, 5 6
6 7
7 8
8 9
9 10
dtype: int64, 10 11
11 12
12 13
13 14
14 15
dtype: int64, 15 16
16 17
17 18
18 19
19 20
dtype: int64]
通过循环列表或通过索引(例如(访问它们
result[0]
Out[3]:
0 1
1 2
2 3
3 4
4 5
dtype: int64