Pandas Series 属性和方法,前面介绍了Series基本用法,本章介绍 Series 经常使用的属性和方法。
Series 属性或方法
现在创建一个 Series 并演示如何使用上面所有列出的属性操作。
import pandas as pd
import numpy as np
#Create a series with 100 random numbers
s = pd.Series(np.random.randn(4))
print (s)
执行结果如下:
0 0.573942
1 1.596683
2 -1.211234
3 -0.589423
dtype: float64
axes 示例
返回 Series 索引列表
import pandas as pd
import numpy as np
#Create a series with 100 random numbers
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到5的值列表的紧凑格式,即:[0,1,2,3,4]
。
empty 示例
返回布尔值,表示对象是否为空。返回True
则表示对象为空。
import pandas as pd
import numpy as np
#Create a series with 100 random numbers
s = pd.Series(np.random.randn(4))
print ("Is the Object empty?")
print (s.empty)
执行结果如下:
Is the Object empty?
False
ndim 示例
返回基础数据的维数。根据定义,一个Series
是一个一维
数据结构
import pandas as pd
import numpy as np
#Create a series with 4 random numbers
s = pd.Series(np.random.randn(4))
print (s)
print ("The dimensions of the object:")
print (s.ndim)
执行结果如下:
0 0.533809
1 -1.248059
2 1.030966
3 0.594617
dtype: float64
The dimensions of the object:
1
size 示例
返回基础数据中的元素个数。
import pandas as pd
import numpy as np
#Create a series with 4 random numbers
s = pd.Series(np.random.randn(2))
print (s)
print ("The size of the object:")
print (s.size)
执行结果如下:
0 0.456946
1 -0.027225
dtype: float64
The size of the object:
2
values 示例
以ndarray
形式返回 Series 中的实际数据值。
import pandas as pd
import numpy as np
#Create a series with 4 random numbers
s = pd.Series(np.random.randn(4))
print (s)
print ("The actual data series is:")
print (s.values)
执行结果如下:
0 0.446583
1 1.045889
2 -2.095649
3 -0.874373
dtype: float64
The actual data series is:
[ 0.44658348 1.04588871 -2.09564915 -0.87437253]
head() 和 tail() 示例
要查看 Series 或 DataFrame 对象的小样本,请使用head()
和tail()
方法。
head()
返回前n
行(观察索引值)。默认数量为5
,可以传递自定义数值。
import pandas as pd
import numpy as np
#Create a series with 4 random numbers
s = pd.Series(np.random.randn(4))
print ("The original series is:")
print (s)
print ("The first two rows of the data series:")
print (s.head(2))
执行结果如下:
The original series is:
0 -1.540479
1 0.151597
2 -0.114554
3 2.037501
dtype: float64
The first two rows of the data series:
0 -1.540479
1 0.151597
dtype: float64
tail()
返回最后n
行(观察索引值)。 默认数量为5
,可以传递自定义数值。
import pandas as pd
import numpy as np
#Create a series with 4 random numbers
s = pd.Series(np.random.randn(4))
print ("The original series is:")
print (s)
print ("The last two rows of the data series:")
print (s.tail(2))
执行结果如下:
The original series is:
0 0.180139
1 -0.815171
2 -0.343180
3 -1.810884
dtype: float64
The last two rows of the data series:
2 -0.343180
3 -1.810884
dtype: float64