扫码一下
查看教程更方便
本节主要介绍 pandas 数据结构 series 的基本的功能。
下面是series基本功能的列表
序号 | 功能 | 描述 |
---|---|---|
1 | axes | 返回行轴标签列表 |
2 | dtype | 返回对象的数据类型。 |
3 | empty | 如果 series 为空,则返回 true。 |
4 | ndim | 返回基础数据的维数。定义为1 |
5 | size | 返回基础数据中的元素数。 |
6 | values | 将 series 作为 ndarray 返回。 |
7 | head() | 返回前 n 行。 |
8 | tail() | 返回最后 n 行。 |
现在让我们创建一个 series 并依次查看上面列出的所有属性操作。
import pandas as pd
import numpy as np
#使用 4 个随机数创建一个series
s = pd.series(np.random.randn(4))
print(s)
运行结果如下
0 1.571247
1 0.756607
2 -0.759702
3 -0.963747
dtype: float64
返回 series 的标签列表。
import pandas as pd
import numpy as np
#使用 4 个随机数创建一个series
s = pd.series(np.random.randn(4))
print ("the axes are:")
print(s.axes)
运行结果如下
the axes are:
[rangeindex(start=0, stop=4, step=1)]
上面的结果表示一个从 0 到 4,步长为 1 的这样一个数组,即 [0,1,2,3,4]。
返回布尔值,说明对象是否为空。true 表示对象为空。
import pandas as pd
import numpy as np
#使用 4 个随机数创建一个series
s = pd.series(np.random.randn(4))
print ("is the object empty?")
print(s.empty)
运行结果如下
is the object empty?
false
返回对象的维数。根据定义,series 是一维数据结构,因此它返回 1
import pandas as pd
import numpy as np
#使用 4 个随机数创建一个series
s = pd.series(np.random.randn(4))
print ("the dimensions of the object:")
print(s.ndim)
运行结果如下
the dimensions of the object:
1
返回series的大小(长度)。
import pandas as pd
import numpy as np
#使用 4 个随机数创建一个series
s = pd.series(np.random.randn(4))
print ("the size of the object:")
print(s.size)
运行结果如下
the size of the object:
4
以数组形式返回 series 中的实际数据。
import pandas as pd
import numpy as np
#使用 4 个随机数创建一个series
s = pd.series(np.random.randn(4))
print ("the actual data series is:")
print(s.values)
运行结果如下
the actual data series is:
[-0.22330251 -0.30335819 -1.07751877 1.71897936]
head()返回前n行(观察索引值)。如果没有传递值,则默认显示的元素个数为5。
import pandas as pd
import numpy as np
#使用 6 个随机数创建一个series
s = pd.series(np.random.randn(6))
print ("the first three rows of the data series:")
print(s.head(3))
运行结果如下
the first three rows of the data series:
0 0.052514
1 -1.403173
2 1.908502
dtype: float64
tail()返回最后n行(观察索引值)。如果没有传递值,则默认显示的元素个数为5。
import pandas as pd
import numpy as np
#使用 6 个随机数创建一个series
s = pd.series(np.random.randn(6))
print ("the last trhee rows of the data series:")
print(s.tail(3))
运行结果如下
the last trhee rows of the data series:
3 -1.264836
4 -0.841042
5 -0.335702
dtype: float64