目录
1、pandas 常用类
1.1 Series
Series 由一组数据以及一组与之对应的数据标签(即索引)组成。Series 对象可以视作一个NumPy 的 ndarray ,因此许多NumPy库函数可以作用于 series。
1.1.1创建 Series
Pandas Series 类似表格中的一个列(column),类似于一维数组,可以保存任何数据类型,本质上是一个 ndarray。Series 由索引(index)和列组成,函数如下:
pandas.Series( data=None, index=None, dtype=None, name=None, copy=False)
参数说明:
-
data:一组数据(ndarray 类型)。
-
index:数据索引标签,如果不指定,默认从 0 开始。
-
dtype:数据类型,默认会自己判断。
-
name:设置该 Series 名称。
-
copy:拷贝数据,默认为 False。仅影响 Series 和 ndarray 数组
通过 ndarray 创建 Series
import numpy as np
import pandas as pd
print('通过 ndarray 创建的 Series 为:\n', pd.Series(np.arange(5), index=['a', 'b', 'c', 'd', 'e'], name='ndarray'))
运行结果:
通过 ndarray 创建的 Series 为:
a 0
b 1
c 2
d 3
e 4
Name: ndarray, dtype: int32
若数据存放在 dict 中,则可以通过 dict 创建 Series,此时 dict 的键名(key)作为 Series 的索引,其值会作为 Series 的值,因此无需传入 index 参数。通过dict创建 Series 对象,代码如下:
通过 dict 创建 Series
import numpy as np
import pandas as pd
dit = {'a': 0, 'b': 1, 'c': 2, 'd': 3}
print('通过 dict 创建的 Series 为:\n', pd.Series(dit))
运行结果:
通过 dict 创建的 Series 为:
a 0
b 1
c 2
d 3
dtype: int64
通过 list 创建 Series
import numpy as np
import pandas as pd
list1 = [1, 2, 3, 4, 5]
list2 = [10, 2, 36, 4, 25]
print('通过 list 创建的 Series 为:\n', pd.Series(list1)) # 索引为默认
print('通过 list 创建的 Series 为:\n', pd.Series(list2, index=['a', 'b', 'c', 'd', 'e'], name='list'))
运行结果:
通过 list 创建的 Series 为:
0 1
1 2
2 3
3 4
4 5
dtype: int64
通过 list 创建的 Series 为:
a 10
b 2
c 36
d 4
e 25
Name: list, dtype: int64
属性 | 说明 |
values | 以 ndarray 的格式返回 Series 对象的所有元素 |
index | 返回 Series 对象的索引 |
dtype | 返回 Series 对象的数据类型 |
shape | 返回 Series 对象的形状 |
nbytes | 返回 Series 对象的字节数 |
ndim | 返回 Series 对象的维度 |
size | 返回 Series 对象的个数 |
T | 返回 Series 对象的转置 |
axes | 返回 Series 索引列表 |
import numpy as np
import pandas as pd
list1 = [1, 2, 3, 4, 5]
series = pd.Series(list1, index=['a', 'b', 'c', 'd', 'e'], name='list')
print('通过 dict 创建的 Series 为:\n', series)
print('数组形式返回 Series 为:', series.values)
print('Series 的 Index 为:', series.index)
print('Series 的 形状为:', series.shape)
print('Series 的 维度为:', series.ndim)
print('Series 对象的个数为:', series.size)
print('返回 Series 索引列表为:', series.axes)
运行结果:
通过 dict 创建的 Series 为:
a 1
b 2
c 3
d 4
e 5
Name: list, dtype: int64
数组形式返回 Series 为: [1 2 3 4 5]
Series 的 Index 为: Index(['a', 'b', 'c', 'd', 'e'], dtype='object')
Series 的 形状为: (5,)
Series 的 维度为: 1
Series 对象的个数为: 5
返回 Series 索引列表为: [Index(['a', 'b', 'c', 'd', 'e'], dtype='object')]
1.1.2 访问 Series 数据
索引和切片是 Series 最常用的操作之一,通过索引位置访问 Series 的数据与 ndarray 相同。Series 使用标签切片时,其末端时包含的,使用位置数值切片,其末端是不包含的。
import numpy as np
import pandas as pd
# 创建 Series
s1 = pd.Series(np.arange(1, 6))
print('通过 ndarray 创建的 Series 为:\n', s1) # 索引为默认
print(f"s1.index为:\n{s1.index}")
print(f"s1.index强制转换为列表输出为:\n{list(s1.index)}")
# 通过标签取得对应的值,或进行修改
s1[2] = 100
# print(s1[-1]) # 无法通过反向索引
s1[-1] = 99 # 新增一行数据
print(f"现在的Series为:\n{s1}")
print(f"s1[-1]: {s1[-1]}") # 标签中存在-1
运行结果:
通过 ndarray 创建的 Series 为:
0 1
1 2
2 3
3 4
4 5
dtype: int32
s1.index为:
RangeIndex(start=0, stop=5, step=1)
s1.index强制转换为列表输出为:
[0, 1, 2, 3, 4]
现在的Series为:
0 1
1 2
2 100
3 4
4 5
-1 99
dtype: int64
s1[-1]: 99
import numpy as np
import pandas as pd
dit = {'a': 0, 'b': 1, 'c': 2, 'd': 3}
print('通过 dict 创建的 Series 为:\n', pd.Series(dit))
# 通过标签取得相应的值,或进行修改
dit['s'] = 9
print(f"dit['b'] = {dit['b']}")
运行结果:
通过 dict 创建的 Series 为:
a 0
b 1
c 2
d 3
dtype: int64
dit['b'] = 1
import numpy as np
import pandas as pd
list1 = [1, 2, 3, 4, 5]
series = pd.Series(list1, index=['a', 'b', 'c', 'd', 'e'], name='list')
print('通过 dict 创建的 Series 为:\n', series)
print(f"Series 位于第 1 位置的数据为:{series[0]}")
# 通过索引名称(标签)也可以访问Series 数据
print(f"Series中 Index 为 ‘b’的数据为:{series['b']}")
print(f"bool 类型的 Series 为:\n{series < 4}")
print(f"通过bool 数组访问Series 为:\n{series[series < 4]}")
运行结果:
通过 dict 创建的 Series 为:
a 1
b 2
c 3
d 4
e 5
Name: list, dtype: int64
Series 位于第 1 位置的数据为:1
Series中 Index 为 ‘b’的数据为:2
bool 类型的 Series 为:
a True
b True
c True
d False
e False
Name: list, dtype: bool
通过bool 数组访问Series 为:
a 1
b 2
c 3
Name: list, dtype: int64
1.1.3 更新、插入和删除
import numpy as np
import pandas as pd
list1 = [1, 2, 3, 4, 5]
series = pd.Series(list1, index=['a', 'b', 'c', 'd', 'e'], name='list')
print('通过 dict 创建的 Series 为:\n', series)
# 更新元素
series['b'] = 9
print(f"更新后的 Series 为:\n{series}")
# 在原 Series 上插入(追加)新的Series
series1 = pd.Series([4, 5], index=['f', 'g'])
# 追加
print(f"在 series 后插入 series1,结果为:\n{series.append(series1)}")
# 添加单个元素
series1['h'] = 7
print(f"插入单个数据后 series1:\n{series1}")
# 删除 Series 元素
series.drop('e', inplace=True)
print('删除索引 e 对应的数据后的 series 为:\n', series)
运行结果:
通过 dict 创建的 Series 为:
a 1
b 2
c 3
d 4
e 5
Name: list, dtype: int64
更新后的 Series 为:
a 1
b 9
c 3
d 4
e 5
Name: list, dtype: int64
在 series 后插入 series1,结果为:
a 1
b 9
c 3
d 4
e 5
f 4
g 5
dtype: int64
插入单个数据后 series1:
f 4
g 5
h 7
dtype: int64
删除索引 e 对应的数据后的 series 为:
a 1
b 9
c 3
d 4
Name: list, dtype: int64
1.2 DataFrame
DataFrame 是 pandas 基本数据结构,类似于数据库中的表。 DataFrame 既有行索引,也有列索引,它可以看作 Series 组成的 dict ,每个 Series 看作 DataFrame 的一个列。
1.2.1 创建 DataFrame
DataFrame 函数用于创建 DataFrame 对象,其基本语法格式如下:
class pandas.DataFrame(data, index, columns, dtype, copy)
参数名称 | 说明 |
data | 接收 ndarray、dict、list或DataFrame,表示输入数据。默认为None |
index | 接收Index、ndarray,表示索引。默认为 None。 |
columns | 接收Index、ndarray,表示列标签(列名)。默认为None |
创建 DataFrame 的方法由很多,常见的一种是传入一个由等长 list 或 ndarray 组成的 dict。
若没有传入 columns 参数,则传入的 dict 的键会被当做列名。
使用字典创建 DataFrame 对象
import numpy as np
import pandas as pd
# 通过 dict 创建 DataFrame
dict1 = {'col1': [0, 1, 2, 3, 4], 'col2': [5, 6, 7, 8, 9]}
print(f"痛过 dict 创建的 DataFrame 为:\n{pd.DataFrame(dict1,index=['a', 'b', 'c', 'd', 'e'])}")
# 通过 list 创建 DataFrame
list2 = [[0, 5, 1], [1, 6, 5], [2, 6, 3], [8, 9, 5], [8, 3, 4]]
print(f"痛过 list 创建的 DataFrame 为:\n{pd.DataFrame(list2,index=['a', 'b', 'c', 'd', 'e'], columns=['col1', 'col2', 'col3'])}")
运行结果:
痛过 dict 创建的 DataFrame 为:
col1 col2
a 0 5
b 1 6
c 2 7
d 3 8
e 4 9
痛过 list 创建的 DataFrame 为:
col1 col2 col3
a 0 5 1
b 1 6 5
c 2 6 3
d 8 9 5
e 8 3 4
使用嵌套列表创建:
import numpy as np
import pandas as pd
data = [['xiaoming', 20], ['lina', 35], ['jam', 24]]
# 未分配列标签
df = pd.DataFrame(data)
print('使用嵌套列表创建的 DataFrame(未分配列标签) 为:\n', df)
# 分配列标签
df1 = pd.DataFrame(data, columns=['name', 'Age'])
print('使用嵌套列表创建的 DataFrame(分配列标签) 为:\n', df1)
运行结果:
使用嵌套列表创建的 DataFrame(未分配列标签) 为:
0 1
0 xiaoming 20
1 lina 35
2 jam 24
使用嵌套列表创建的 DataFrame(分配列标签) 为:
name Age
0 xiaoming 20
1 lina 35
2 jam 24
使用列表嵌套字典创建 DataFrame 对象
import numpy as np
import pandas as pd
data = [{'a': 1, 'b': 2}, {'a': 5, 'b': 10, 'c': 20}]
df = pd.DataFrame(data, index=['first', 'second'])
# 如果其中某个元素值缺失,也就是字典的key无法找到对应的 value ,将使用 NaN 代替
print(f"列表嵌套字典创建 DataFrame 对象:\n{df}")
运行结果:
列表嵌套字典创建 DataFrame 对象:
a b c
first 1 2 NaN
second 5 10 20.0
使用 Series 创建 DataFrame 对象
import numpy as np
import pandas as pd
data = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(data)
# 对于 one 列而言,此处虽然显示了行索引'd',但由于没有与其对应的值,所以它的值为 NaN
print(f"通过 Series 创建 DataFrame 对象:\n{df}")
运行结果:
通过 Series 创建 DataFrame 对象:
one two
a 1.0 1
b 2.0 2
c 3.0 3
d NaN 4
属性 | 说明 |
T | 行列转置 |
columns | 返回 DataFrame 的列标签 |
dtypes | 返回 DataFrame 各列的数据类型 |
index | 返回行索引名 |
shape | 返回 DataFrame 对象的形状 |
size | 返回 DataFrame 对象包含的元素个数 |
values | 以 ndarray 的格式返回 DataFrame 对象的所有元素 |
loc | 通过行索引获取行数据 |
iloc | 通过行号获取数据 |
axes | 返回一个仅以行轴标签和列轴标签为成员的列表 |
empty | DataFrame 中没有数据或者任意坐标轴的长度为0,则返回True |
head() | 返回前 n 行数据 |
tail() | 返回后 n 行数据 |
rename() | rename(columns=字典),修改列名 |
info() | 可以显示信息,例如行/列数,总内存使用量,每列的数据类型以及 |
import numpy as np
import pandas as pd
# 设置打印宽度,使打印数据对齐
pd.set_option('display.unicode.ambiguous_as_wide', True)
pd.set_option('display.unicode.east_asian_width', True)
df = pd.DataFrame({'city': ['上海市', '北京市', '广州市', '深圳市'], 'GDP': [13908.57, 12406.8, 9891.48, 9709.02]},
columns=['city', 'GDP'])
print(f"通过 dict 创建的 DataFrame 为:\n{df}")
print(f" DataFrame 的转置为:\n{df.T}")
print(f"查看行索引名为:\n{df.index}")
print(f"查看行列索引名为:\n{df.columns}")
print(f"查看 DataFrame 的形状为:\n{df.shape}")
print(f"查看 DataFrame 对象的数据为:\n{df.values}")
print(f"查看 DataFrame 指定列df['GDP']的内容为:\n{df['GDP']}")
print(f"查看 DataFrame 指定列df.GDP的内容为:\n{df.GDP}")
print(f"查看 DataFrame 行号为 2 这一行内容为:\n{df.loc[2]}")
print(f"查看 DataFrame 元素个数:\n{df.size}")
运行结果:
通过 dict 创建的 DataFrame 为:
city GDP
0 上海市 13908.57
1 北京市 12406.80
2 广州市 9891.48
3 深圳市 9709.02
DataFrame 的转置为:
0 1 2 3
city 上海市 北京市 广州市 深圳市
GDP 13908.57 12406.8 9891.48 9709.02
查看行索引名为:
RangeIndex(start=0, stop=4, step=1)
查看行列索引名为:
Index(['city', 'GDP'], dtype='object')
查看 DataFrame 的形状为:
(4, 2)
查看 DataFrame 对象的数据为:
[['上海市' 13908.57]
['北京市' 12406.8]
['广州市' 9891.48]
['深圳市' 9709.02]]
查看 DataFrame 指定列df['GDP']的内容为:
0 13908.57
1 12406.80
2 9891.48
3 9709.02
Name: GDP, dtype: float64
查看 Da