如何在熊猫中拆分系列?

时间:2020-07-27 08:47:25

标签: python pandas

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之间的数字

3 个答案:

答案 0 :(得分:0)

尝试使用:

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:]

答案 1 :(得分:0)

您可以使用numpy的{​​{1}}

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]

访问它们

答案 2 :(得分:0)

使用 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