Pandas库基础操作
pandas库是Python中非常受欢迎的数据分析库,提供了快速、灵活和富有表现力的数据结构,便于轻松地进行数据清洗和分析。因为它不是标准库,使用前确保环境已经安装了Pandas库。
pip install pandas
1. 数据结构简介
在pandas中有两类非常重要的数据结构,即序列Series和数据框DataFrame。Series类似于numpy中的一维数组,除了通吃一维数组可用的函数或方法,而且其可通过索引标签的方式获取数据,还具有索引的自动对齐功能
Series的创建
序列的创建主要有三种方式
1)通过一维数组创建序列
import numpy as np, pandas as pd
arr1 = np.arange(10)
print(arr1)
print(type(arr1))
s1 = pd.Series(arr1)
print(s1)
# 输出
[0 1 2 3 4 5 6 7 8 9]
<class 'numpy.ndarray'>
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
dtype: int64
<class 'pandas.core.series.Series'>
2)通过字典的方式创建序列
dic1 = {'a':10,'b':20,'c':30,'d':40,'e':50}
print(dic1)
print(type(dic1))
# 输出
{'a': 10, 'b': 20, 'c': 30, 'd': 40, 'e': 50}
<class 'dict'>
DataFrame的创建
数据框的创建主要有三种方式:
1)通过二维数组创建数据框
arr2 = np.array(np.arange(12)).reshape(4,3)
print(arr2)
print(type(arr2))
df1 = pd.DataFrame(arr2)
print(df1)
print(type(df1))
# 输出
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
<class 'numpy.ndarray'>
0 1 2
0 0 1 2
1 3 4 5
2 6 7 8
3 9 10 11
<class 'pandas.core.frame.DataFrame'>
2)通过字典的方式创建数据框
以下以两种字典来创建数据框,一个是字典列表,一个是嵌套字典。
# 例子1
dic2 = {'a':[1,2,3,4],'b':[5,6,7,8],'c':[9,10,11,12],'d':[13,14,15,16]}
print(dic2)
print(type(dic2))
df2 = pd.DataFrame(dic2)
print(df2)
print(type(df2))
# 输出
{'a': [1, 2, 3, 4], 'b': [5, 6, 7, 8], 'c': [9, 10, 11, 12], 'd': [13, 14, 15, 16]}
<class 'dict'>
a b c d
0 1 5 9 13
1 2 6 10 14
2 3 7 11 15
3 4 8 12 16
<class 'pandas.core.frame.DataFrame'>
# 例子2
dic3 = {'one':{'a':1,'b':2,'c':3,'d':4},'two':{'a':5,'b':6,'c':7,'d':8},'three':{'a':9,'b':10,'c':11,'d':12}}
print(dic3)
print(type(dic3))
df3 = pd.DataFrame(dic3)
print(df3)
print(type(df3))
# 输出
{'one': {'a': 1, 'b': 2, 'c': 3, 'd': 4}, 'two': {'a': 5, 'b': 6, 'c': 7, 'd': 8}, 'three': {'a': 9, 'b': 10, 'c': 11, 'd': 12}}
<class 'dict'>
one two three
a 1 5 9
b 2 6 10
c 3 7 11
d 4 8 12
<class 'pandas.core.frame.DataFrame'>
3)过DataFrame中的某一行或某一列创建序列
df4 = df3[['one','three']]
print(df4)
print(type(df4))
# 输出
one three
a 1 9
b 2 10
c 3 11
d 4 12
<class 'pandas.core.frame.DataFrame'>
一列数据就是序列
s3 = df3['one']
print(s3)
print(type(s3))
a 1
b 2
c 3
d 4
Name: one, dtype: int64
<class 'pandas.core.series.Series'>
更多内容请查看我的gittee仓库 : Python基础练习