pandas基本数据对象及操作(Series篇)

一.创建Series

import pandas as pd

countries = ['中国', '美国', '澳大利亚']
countries_s = pd.Series(countries)
print(type(countries_s))
print(countries_s)

<class 'pandas.core.series.Series'>
0      中国
1      美国
2    澳大利亚
dtype: object



countries_s.values

array(['中国', '美国', '澳大利亚'], dtype=object)



numbers = [4, 5, 6]
print(pd.Series(numbers))

0    4
1    5
2    6
dtype: int64



country_dicts = {'CH': '中国',
                'US': '美国',
                'AU': '澳大利亚'}
country_dict_s = pd.Series(country_dicts)
# 给索引命名
country_dict_s.index.name = 'Code'
# 给数据命名
country_dict_s.name = 'Country'
print(country_dict_s)
print(country_dict_s.values)
print(country_dict_s.index)

Code
AU    澳大利亚
CH      中国
US      美国
Name: Country, dtype: object
['澳大利亚' '中国' '美国']
Index(['AU', 'CH', 'US'], dtype='object', name='Code')

二.处理缺失数据

countries = ['中国', '美国', '澳大利亚', None]
print(pd.Series(countries))

0      中国
1      美国
2    澳大利亚
3    None
dtype: object




numbers = [4, 5, 6, None]
print(pd.Series(numbers))

0    4.0
1    5.0
2    6.0
3    NaN
dtype: float64

三.Series索引

country_dicts = {'CH': '中国',
                'US': '美国',
                'AU': '澳大利亚'}

country_dict_s = pd.Series(country_dicts)
print(country_dict_s)

AU    澳大利亚
CH      中国
US      美国
dtype: object



# 通过索引判断数据是存在
# Series也可看作定长、有序的字典
print('CH' in country_dict_s)
print('NZ' in country_dict_s)

True
False



print('iloc:', country_dict_s.iloc[1])
print('loc:', country_dict_s.loc['US'])
print('[]:', country_dict_s['US'])

iloc: 中国
loc: 美国
[]: 美国



print('iloc:\n', country_dict_s.iloc[[0, 2]])
print()
print('loc:\n', country_dict_s.loc[['US', 'AU']])

iloc:
 AU    澳大利亚
US      美国
dtype: object

loc:
 US      美国
AU    澳大利亚
dtype: object

四.向量化操作

import numpy as np
s = pd.Series(np.random.randint(0, 1000, 10000))
print(s.head())
print(len(s))

0    712
1    522
2    623
3    451
4    765
dtype: int32
10000

猜你喜欢

转载自blog.csdn.net/a1786742005/article/details/82777049