pip install pandas -i https://pypi.tuna.tsinghua.edu.cn/simple/
Pandas 在 ndarray 数组(NumPy 中的数组)的基础上构建出了两种不同的数据结构,分别是 Series(一维数据结构)、DataFrame(二维数据结构):
Series:是带标签的一维数组,这里的标签可以理解为索引,但这个索引并不局限于整数,它也可以是字符类型
DataFrame:是一种表格型数据结构,它既有行标签,又有列标签
数据结构 | 维度 | 说明 |
---|---|---|
Series | 1 | 该结构能够存储各种数据类型,比如字符数、整数、浮点数、Python 对象等,Series 用 name 和 index 属性来描述数据值。Series 是一维数据结构,因此其维数不可以改变 |
DataFrame | 2 | DataFrame 是一种二维表格型数据的结构,既有行索引,也有列索引。行索引是 index,列索引是 columns。 在创建该结构时,可以指定相应的索引值 |
语法:pandas.Series(data,index,dtype)
属性:
data:一组数据(ndarray 类型)
index:数据索引标签,如果不指定,默认从 0 开始
dtype:数据类型,默认会自己判断
copy:表示对 data 进行拷贝,默认为 False
创建方式:
1.空对象
2.ndarray 创建 Series 对象
3.字典创建 Series 对象
示例:
import numpy as np
import pandas as pd
# 创建Series空对象
s = pd.Series()
print(s)
# 列表创建Series对象
s = pd.Series([1, 2, 3, 4, 5])
print(s)
# ndarray创建Series对象
s = pd.Series(np.array([1, 2, 3, 4, 5]))
# 字典创建Series对象
dic = {"id": 1, "age": 20, "name": "xiaohei"}
s = pd.Series(dic)
print(s)
'''
输出结果:
Series([], dtype: object)
0 1
1 2
2 3
3 4
4 5
dtype: int64
id 1
age 20
name xiaohei
dtype: object
'''
1.使用 items()
2.使用 index 属性
3.使用 values 属性
示例:
import pandas as pd
# 访问Series的元素
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s[3])
# 注意:使用下标做切片时,终止值不包含
print(s[0:2])
s = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
print(s)
print(s['d'])
# 注意:使用标签做切片时,终止值包含
print(s['a':'c'])
# 遍历
# 1.index遍历
s = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
for idx in s.index:
print(idx, s[idx])
# 2.使用values遍历
for v in s.values:
print(v)
# 3.使用items()遍历,返回index和value
for idx, val in s.items():
print(idx, val)
'''
输出结果:
4
0 1
1 2
dtype: int64
a 1
b 2
c 3
d 4
dtype: int64
4
a 1
b 2
c 3
dtype: int64
a 1
b 2
c 3
d 4
1
2
3
4
a 1
b 2
c 3
d 4
'''
Dataframe和Series的关系:
在 Pandas 中,DataFrame
的每一行或每一列都是一个 Series
。DataFrame
是一个二维表格,可以看作是由多个 Series
组成的。
如何区分行和列的 Series
:
列的 Series
:标签是行索引;值是该列的所有行数据。
行的Series:标签是列名;值是该行的所有列数据。
语法:pd.DataFrame( data, index, columns, dtype, copy)
属性:
data:一组数据(ndarray、series, map, lists, dict 等类型)
index:索引值,或者可以称为行标签
columns:列标签,默认为 RangeIndex (0, 1, 2, …, n)
dtype:数据类型
copy:默认为 False,表示复制数据 data
创建方法:
创建 DataFrame 空对象
列表嵌套字典创建 DataFrame 对象
字典嵌套列表创建 DataFrame 对象
Series 创建 DataFrame 对象
示例:
import pandas as pd
# 1.创建 DataFrame 空对象
df = pd.DataFrame()
print(df)
# 2.列表嵌套字典创建 DataFrame 对象
# 如果字典中有不同键值对,取并集,并填充空值
l = [{"name": "xiaohei", "age": 20}, {"name": "xiaobai", "age": 22, "sex": 0}]
df = pd.DataFrame(l)
print(df)
# 3.字典嵌套列表创建 DataFrame 对象
# 字典中value长度要一致,否则报错
dic = {"name": ["xiaohei", "zhagnsan"], "age": [11, 22]}
df = pd.DataFrame(dic)
print(df)
# 4.Series 创建 DataFrame 对象
# 字典中value使用Series时,如果字典的行有缺失,填充NaN
dic = {"name": pd.Series(["xiaohei", "zhangsan"], index=['a', 'b']),
"age": pd.Series([11, 22, 33], index=['a', 'b', 'c'])}
df = pd.DataFrame(dic)
print(df)
'''
输出结果:
Empty DataFrame
Columns: []
Index: []
name age sex
0 xiaohei 20 NaN
1 xiaobai 22 0.0
name age
0 xiaohei 11
1 zhagnsan 22
name age
a xiaohei 11
b zhangsan 22
c NaN 33
'''
import numpy as np
import pandas as pd
# 获取列值
dic = {"one": [1, 2, 3, 4, 5], "two": [6, 7, 8, 9, 10], "three": [11, 12, 13, 14, 15]}
df = pd.DataFrame(dic)
print(df)
# 取一列返回Series,多列返回DataFrame
print(df['one'])
print(df[['one', 'two']])
# 通过布尔索引获取
print(df[df['one'] > 3])
# 不能直接切片
# print(df['one':'two'])
# 添加
# 添加一个空列
df['three'] = None
print(df)
# 通过列表添加列
df['four'] = [10, 20, 30, 40, 50]
print(df)
# assign方法添加列
# assign():参数是赋值语句,左边是列名,右边是添加的值
# assign():是链式调用(返回值是数据类型本身)
df1 = df.assign(five=[10, 20, 30, 40, 50]).assign(six=[1, 2, 3, 4, 5])
print(df1)
# insert():在指定位置插入数据
# 参数:loc-要插入的索引下标(不是标签),column要插入的列名,value要插入的数据
dic = {"one": [1, 2, 3, 4, 5], "two": [6, 7, 8, 9, 10], "three": [11, 12, 13, 14, 15]}
df = pd.DataFrame(dic)
df.insert(1, "four", [1, 1, 1, 1, 1])
print(df)
# 修改数据
dic = {"one": [1, 2, 3, 4, 5], "two": [6, 7, 8, 9, 10], "three": [11, 12, 13, 14, 15]}
df = pd.DataFrame(dic)
df['two'] = [16, 17, 18, 19, 20]
print(df)
df['two'] = df['one'] + 10
print(df)
# 修改列名
# 1.columns属性修改列名:在原数据直接修改
df.columns = ['a', 'b', 'c']
print(df)
# 2.rename()修改列名,返回新数据,原数据不受影响
# columns属性数据类型是字典,key是原标签,value是修改列名
df1 = df.rename(columns={'a': 'A', 'b': 'B', 'c': 'C'})
print(df1)
# 修改数据类型
print(df1.dtypes)
df1['A'] = df1['A'].astype(np.float32)
print(df1)
# drop()
# 参数:
# labels:删除标签(行/列)
# axis:轴方向,和label组合使用,axis = 0,labels是行标签,axis = 1 labels是列标签
# index:要删除的是行标签或者标签列表
# columns:要删除的是列标签或列表
# inplace:如果为true,表示原地修改数据,为false返回一个新数组,默认为false
data = {
'A': [1, 2, 3, 4, 5],
'B': [6, 7, 8, 9, 10]
}
df = pd.DataFrame(data)
# 使用labels和axis删除
df1 = df.drop('A', axis=1)
print(df1)
# 使用columns删除
df2 = df.drop(columns=['A'])
print(df2)
# 使用labels和axis删除 注意:包含边界
df3 = df.drop([0, 1], axis=0)
print(df3)
# 使用index删除
df4 = df.drop(index=[0, 1])
print(df4)
# 原地修改
df.drop(index=[0], inplace=True)
print(df)
'''
输出结果:
one two three
0 1 6 11
1 2 7 12
2 3 8 13
3 4 9 14
4 5 10 15
0 1
1 2
2 3
3 4
4 5
Name: one, dtype: int64
one two
0 1 6
1 2 7
2 3 8
3 4 9
4 5 10
one two three
3 4 9 14
4 5 10 15
one two three
0 1 6 None
1 2 7 None
2 3 8 None
3 4 9 None
4 5 10 None
one two three four
0 1 6 None 10
1 2 7 None 20
2 3 8 None 30
3 4 9 None 40
4 5 10 None 50
one two three four five six
0 1 6 None 10 10 1
1 2 7 None 20 20 2
2 3 8 None 30 30 3
3 4 9 None 40 40 4
4 5 10 None 50 50 5
one four two three
0 1 1 6 11
1 2 1 7 12
2 3 1 8 13
3 4 1 9 14
4 5 1 10 15
one two three
0 1 16 11
1 2 17 12
2 3 18 13
3 4 19 14
4 5 20 15
one two three
0 1 11 11
1 2 12 12
2 3 13 13
3 4 14 14
4 5 15 15
a b c
0 1 11 11
1 2 12 12
2 3 13 13
3 4 14 14
4 5 15 15
A B C
0 1 11 11
1 2 12 12
2 3 13 13
3 4 14 14
4 5 15 15
A int64
B int64
C int64
dtype: object
A B C
0 1.0 11 11
1 2.0 12 12
2 3.0 13 13
3 4.0 14 14
4 5.0 15 15
B
0 6
1 7
2 8
3 9
4 10
B
0 6
1 7
2 8
3 9
4 10
A B
2 3 8
3 4 9
4 5 10
A B
2 3 8
3 4 9
4 5 10
A B
1 2 7
2 3 8
3 4 9
4 5 10
'''
1.loc 选取数据
df.loc[] 只能使用标签索引,不能使用整数索引。当通过标签索引的切片方式来筛选数据时,它的取值前闭后闭,也就是只包括边界值标签(开始和结束)
loc方法返回的数据类型:
1.如果选择单行或单列,返回的数据类型为Series
2.选择多行或多列,返回的数据类型为DataFrame
3.选择单个元素(某行某列对应的值),返回的数据类型为该元素的原始数据类型(如整数、浮点数等)。
语法:DataFrame.loc[row_indexer, column_indexer]
参数:
row_indexer:行标签或布尔数组。
column_indexer:列标签或布尔数组。
2. iloc 选取数据
iloc 方法用于基于位置(integer-location based)的索引,即通过行和列的整数位置来选择数据。
语法:DataFrame.iloc[row_indexer, column_indexer]
参数:
row_indexer:行位置或布尔数组。
column_indexer:列位置或布尔数组。
3. 切片多行选取
通过切片的方式进行多行数据的选取
1.loc方法添加新行
2.concat拼接
语法:pd.concat(objs, axis=0, join='outer', ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, sort=False, copy=True)
参数:
objs: 要连接的 DataFrame 或 Series 对象的列表或字典。
axis: 指定连接的轴,0 或 'index' 表示按行连接,1 或 'columns' 表示按列连接。
join: 指定连接方式,'outer' 表示并集(默认),'inner' 表示交集。
ignore_index: 如果为 True,则忽略原始索引并生成新的索引。
keys: 用于在连接结果中创建层次化索引。
levels: 指定层次化索引的级别。
names: 指定层次化索引的名称。
verify_integrity: 如果为 True,则在连接时检查是否有重复索引。
sort: 如果为 True,则在连接时对列进行排序。
copy: 如果为 True,则复制数据。
您可以使用行索引标签,从 DataFrame 中删除某一行数据。如果索引标签存在重复,那么它们将被一起删除。使用的是 drop 函数
示例:
import pandas as pd
# 获取行
# loc[]
data = {
'A': [1, 2, 3, 4],
'B': [5, 6, 7, 8],
'C': [9, 10, 11, 12]
}
df = pd.DataFrame(data, index=['a', 'b', 'c', 'd'])
# 获取a行数据
print(df.loc['a'])
# 对行切片,如:a-c行
print(df.loc['a':'c'])
# 对行和列切片
print(df.loc['a':'c', 'A':'B'])
# 对列切片
print(df.loc[..., 'A':'B'])
# 获取一个元素
print(df.loc['a', 'B'])
# 获取多行多列
print(df.loc[['a', 'c'], ['A', 'C']])
# iloc
# 获取单行,0行
print(df.iloc[0])
# 行切片不包含终止值
print(df.iloc[0:2])
# 行和列切片
print(df.iloc[0:2, 0:2])
# 列切片
print(df.iloc[:, 0:2])
# 获取单个元素
print(df.iloc[0, 0])
# 获取多行多列
print(df.iloc[[0, 1], [0, 1]])
# DataFrame切片操作 默认切片同iloc结果一样
df1 = df[0:2]
print(df1)
# 添加行
# loc添加
data = {
'A': [1, 2, 3, 4],
'B': [5, 6, 7, 8]
}
df = pd.DataFrame(data, index=['a', 'b', 'c', 'd'])
# 通过loc添加一个新的行标签,赋值即可,赋值的列表中的元素和列数一致
df.loc['e'] = [9, 10]
print(df)
# 2.concat拼接DataFrame
df1 = pd.DataFrame({
'A': [1, 2, 3],
'B': [4, 5, 6],
})
df2 = pd.DataFrame({
'A': [7, 8, 9],
'B': [10, 11, 12],
'C': [10, 11, 12]
})
# 按行拼接
df3 = pd.concat([df1, df2], axis=0, ignore_index=True)
print(df3)
# 按列拼接
df4 = pd.concat([df1, df2], axis=1)
print(df4)
# join:拼接方式 outer-并集(默认),inner-交集
df5 = pd.concat([df1, df2], axis=0, join='inner')
print(df5)
# DataFrame 和 Series拼接
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [4, 5, 6]
})
a = pd.Series([7, 8, 9], name='C')
df6 = pd.concat([df, a], axis=0)
print(df6)
'''
输出结果:
A 1
B 5
C 9
Name: a, dtype: int64
A B C
a 1 5 9
b 2 6 10
c 3 7 11
A B
a 1 5
b 2 6
c 3 7
A B
a 1 5
b 2 6
c 3 7
d 4 8
5
A C
a 1 9
c 3 11
A 1
B 5
C 9
Name: a, dtype: int64
A B C
a 1 5 9
b 2 6 10
A B
a 1 5
b 2 6
A B
a 1 5
b 2 6
c 3 7
d 4 8
1
A B
a 1 5
b 2 6
A B C
a 1 5 9
b 2 6 10
A B
a 1 5
b 2 6
c 3 7
d 4 8
e 9 10
A B C
0 1 4 NaN
1 2 5 NaN
2 3 6 NaN
3 7 10 10.0
4 8 11 11.0
5 9 12 12.0
A B A B C
0 1 4 7 10 10
1 2 5 8 11 11
2 3 6 9 12 12
A B
0 1 4
1 2 5
2 3 6
0 7 10
1 8 11
2 9 12
A B C
0 1.0 4.0 NaN
1 2.0 5.0 NaN
2 3.0 6.0 NaN
0 NaN NaN 7.0
1 NaN NaN 8.0
2 NaN NaN 9.0
'''
函数名称 | 描述说明 |
---|---|
count() | 统计某个非空值的数量 |
sum() | 求和 |
mean() | 求均值 |
median() | 求中位数 |
std() | 求标准差 |
min() | 求最小值 |
max() | 求最大值 |
abs() | 求绝对值 |
prod() | 求所有数值的乘积 |
重置索引(reindex)可以更改原 DataFrame 的行标签或列标签,并使更改后的行、列标签与 DataFrame 中的数据逐一匹配。通过重置索引操作,您可以完成对现有数据的重新排序。如果重置的索引标签在原 DataFrame 中不存在,那么该标签对应的元素值将全部填充为 NaN。
reindex
reindex() 方法用于重新索引 DataFrame 或 Series 对象。重新索引意味着根据新的索引标签重新排列数据,并填充缺失值。如果重置的索引标签在原 DataFrame 中不存在,那么该标签对应的元素值将全部填充为 NaN。
语法:
DataFrame.reindex(labels=None, index=None, columns=None, axis=None, method=None, copy=True, level=None, fill_value=np.nan, limit=None, tolerance=None)
参数:
labels:
类型:数组或列表,默认为 None。
描述:新的索引标签。
index:
类型:数组或列表,默认为 None。
描述:新的行索引标签。
columns:
类型:数组或列表,默认为 None。
描述:新的列索引标签。
axis:
类型:整数或字符串,默认为 None。
描述:指定重新索引的轴。0 或 'index' 表示行,1 或 'columns' 表示列。
method:
类型:字符串,默认为 None。
描述:用于填充缺失值的方法。可选值包括 'ffill'(前向填充)、'bfill'(后向填充)等。
copy:
类型:布尔值,默认为 True。
描述:是否返回新的 DataFrame 或 Series。
level:
类型:整数或级别名称,默认为 None。
描述:用于多级索引(MultiIndex),指定要重新索引的级别。
fill_value:
类型:标量,默认为 np.nan。
描述:用于填充缺失值的值。
limit:
类型:整数,默认为 None。
描述:指定连续填充的最大数量。
tolerance:
类型:标量或字典,默认为 None。
描述:指定重新索引时的容差。
import pandas as pd
# 统计函数
# 方差
data = {
'A': [1, 2, 3, 4, 5],
'B': [10, 20, 30, 40, 50],
'C': [100, 200, 300, 400, 500]
}
df = pd.DataFrame(data)
print(df.var())
# 平均值
print(df.mean())
# 求和
print(df.sum())
# 重置索引
# reindex
data = {
'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, 8, 9]
}
# 重置行索引
df = pd.DataFrame(data, index=['a', 'b', 'c'])
new_index = ['b', 'c', 'a']
df1 = df.reindex(index=new_index)
print(df1)
# 重置列索引
new_col = ['A', 'B', 'C', 'D']
df2 = df.reindex(columns=new_col)
print(df2)
# method:填充方法 ffill-前线填充 ,bfill-后向填充
df3 = df.reindex(columns=new_col, method='ffill')
print(df3)
'''
输出结果:
A 2.5
B 250.0
C 25000.0
dtype: float64
A 3.0
B 30.0
C 300.0
dtype: float64
A 15
B 150
C 1500
dtype: int64
A B C
b 2 5 8
c 3 6 9
a 1 4 7
A B C D
a 1 4 7 NaN
b 2 5 8 NaN
c 3 6 9 NaN
A B C D
a 1 4 7 7
b 2 5 8 8
c 3 6 9 9
'''