Pandas study notes (1): Series data structure

Construct

Series can be created using the following constructor

# data : 数据源,ndarray、list、dic、常量等
# index : 索引,唯一和散列等,与数据的长度相同
# dtype : 指定数据类型,默认系统推断数据类型
# copy : 复制数据,默认为 Flase
pd.Series( data, index, dtype, copy)
  • Create empty series
s = pd.Series()
print(s)
'''Series([], dtype: float64)'''
  • via ndarray
s = pd.Series(np.array(['a','b','c']))
print(s)
'''
0    a
1    b
2    c
dtype: object'''
  • via list
s = pd.Series(['1','a','3',2])
print(s)
'''
0    1
1    a
2    3
3    2
dtype: object'''
  • via dic dictionary
# 字典的 key 即为标签
dic = {'name':'luo', 'age':25, 'sex':'F'}
s = pd.Series(dic)
print(s)
'''
age      25
name    luo
sex       F
dtype: object'''
  • by scalar
s = pd.Series(2, index=[0, 1, 2])
print(s)
'''
0    2
1    2
2    2
dtype: int64'''

Designated subscript

s = pd.Series(np.arange(3), index=list('ABC'))
print(s)
'''
A    0
B    1
C    2
dtype: int64'''

retrieve data

The data takes s in the above example as an example

  • by index
data = s[1]
print('通过索引取值:{}'.format(data))
'''通过索引取值:1'''

If the series has a label index, we can also get the value by the label

  • by label

a. Array

data = s[['B','A']]     
print('通过标签取值:\n{}'.format(data))
'''
通过标签取值:
B    1
A    0
dtype: int64'''

b. Sliced

data = s['A':'C']       
print('通过标签取值:\n{}'.format(data))
'''
A    0
B    1
C    2
dtype: int64'''

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325639651&siteId=291194637