1. Series 创建
Series 是一种类似一维数组的对象,由两部分组成:
- values:一组数据(ndarray类型)
- index:相关数据索引标签
两种创建方式:
(1) 由列表或 Numpy 数组创建
(2) 由字典创建
import numpy as np
import pandas as pd
# 1. 由list创建
list1 = [41, 12, 40, 55]
s = pd.Series(list1)
print(s)
n = np.array(list1)
s = pd.Series(n)
print(s)
print(s.values) # [41 12 40 55]
print(s.index) # RangeIndex(start=0, stop=4, step=1)
# 修改索引值
s.index = ['A', 'B', 'C', 'D']
# 通过索引获取值
print(s.A) # 41
print(s['C']) # 40
# 2. 由dict创建
d = {
'a': 11,
'b': 22,
'c': 33,
'd': 44
}
s = pd.Series(d)
print(s)
s.index = list('ABCD')
print(s)
d = {
'a': np.random.randint(0, 10, size=(2, 3)),
'b': np.random.randint(0, 10, size=(2, 3)),
'c': np.random.randint(0, 10, size=(2, 3)),
'd': np.random.randint(0, 10, size=(2, 3))
}
s = pd.Series(d)
print(s)
s = pd.Series([1, 2, 3], index=['鲁班', '刘备', '诸葛亮'], name='历史人物')
print(s)
2. Series 的显式索引和隐式索引
可以使用中括号取单个索引(此时返回的是元素类型),或者中括号里一个列表取多个索引(此时返回的仍然是一个Series类型)。
(1)显示索引:
- 使用
index
中的元素作为索引值 - 使用
.loc[]
(2)隐式索引
- 使用整数作为索引值
- 使用
.iloc[]
import pandas as pd
s = pd.Series({
'python': 90,
'pandas': 95,
'numpy': 100
})
# 显示索引:使用索引名
print(s['python']) # 90
print(s[['python', 'pandas']])
print(s.loc['python']) # 90
print(s.loc[['numpy', 'pandas']])
# 隐式索引:使用下标
print(s[0])
print(s[[0, 1]])
print(s.iloc[0]) # 90
3. Series 切片
import pandas as pd
s = pd.Series({
'python': 90,
'pandas': 95,
'numpy': 100,
'matplotlib': 85
})
# 隐式切片:左闭右开
print(s[1:3])
print(s.iloc[1:3])
# 显示切片:左闭右闭
print(s['pandas':'numpy'])
print(s.loc['python':'numpy'])
4. Series 基本属性和方法
import pandas as pd
import numpy as np
s = pd.Series({
'python': 90,
'pandas': 95,
'numpy': 100,
'matplotlib': 85
})
# 查看前几条数据 默认是 5
print(s.head(2)) # 查看前2条数据
# 查看后几条数据 默认是 5
print(s.tail(2)) # 查看后2条数据
s = pd.Series(['张三', np.nan])
# 检查缺失数据
print(s.isnull()) # 判断数据是否为空
print(pd.isnull(s))
print(s.notnull()) # 判断数据是否不为空
print(pd.notnull(s))
# 使用bool值过滤数据
print(s[s.notnull()]) # 过滤掉空数据
print(s[~ s.isnull()]) # 过滤掉空数据
5. Series 运算
import pandas as pd
s1 = pd.Series([1, 2])
s2 = pd.Series([4, 5])
print(s1 + s2) # 两个Series相加
print(s1 - s2) # 两个Series相减
print(s1 * s2) # 两个Series相乘
print(s1 / s2) # 两个Series相除
print(s1 % s2) # 两个Series取模
print(s1 ** s2) # 两个Series相乘方
print(s1 // s2) # 两个Series取整除
print(s1 == s2) # 两个Series相等
6. DataFrame 创建
DataFrame 是一个表格型的数据结构,可以看做是由Series组成的字典(共用同一个索引)。DataFrame 由按一定顺序排列的多列数据组成。
import pandas as pd
import numpy as np
# 1. 通过字典创建
d = {
'name': ['张三', '李四', '王五'],
'age': [18, 19, 20]
}
df = pd.DataFrame(d)
print(df)
print(df.values) # 二维数组的数据
print(df.index) # 行索引
print(df.columns) # 列索引
# 2. 创建
df = pd.DataFrame(
data=np.random.randint(60, 100, (3, 6)),
index=['张三', '李四', '王五'],
columns=['语文', '数学', '英语', '物理', '化学', '生物']
)
print(df)
7.DataFrame 索引
import pandas as pd
import numpy as np
df = pd.DataFrame(
data=np.random.randint(60, 100, (3, 6)),
index=['张三', '李四', '王五'],
columns=['语文', '数学', '英语', '物理', '化学', '生物']
)
# 列索引
print(df.语文) # Series类型
print(df[['语文', '化学']]) # DataFrame类型
# 行索引
print(df.loc['张三']) # Series类型
print(df.loc[['张三', '李四']]) # DataFrame类型
print(df.iloc[0]) # Series类型
print(df.iloc[[0, 1]]) # DataFrame类型
# 先行索引后列索引
print(df.loc['张三', '语文'])
print(df.iloc[0]['语文'])
# 先列索引后行索引
print(df['语文']['张三'])
print(df.语文.张三)
8. DataFrame 切片
import pandas as pd
import numpy as np
df = pd.DataFrame(
data=np.random.randint(60, 100, (3, 4)),
index=['张三', '李四', '王五'],
columns=['语文', '数学', '英语', '化学']
)
# 行切片
print(df['张三':'李四']) # 左闭右闭
print(df.loc['张三':'李四']) # 左闭右闭
print(df[1:2]) # 左闭右开
print(df.iloc[1:2]) # 左闭右开
# 列切片
print(df.iloc[:, 1:3]) # 左闭右开
print(df.loc[:, '数学':'英语']) # 左闭右闭
# 同时做切片(先行后列)
print(df.loc['张三':'李四', '数学':'英语']) # 左闭右闭
print(df.iloc[1:2, 1:3]) # 左闭右开
print(df.iloc[[1], :])
9. DataFrame 运算
import pandas as pd
import numpy as np
df1 = pd.DataFrame(
data=np.random.randint(60, 100, (2, 2)),
index=['张三', '李四'],
columns=['语文', '数学']
)
df2 = pd.DataFrame(
data=np.random.randint(60, 100, (2, 3)),
index=['张三', '李四'],
columns=['语文', '数学', '英语']
)
print(df1.add(df2, fill_value=0))
s = pd.Series([1, 1], index=df1.index)
print(df1)
print(df1.add(s, axis=0)) # axis=0表示按行相加
s = pd.Series([1, 1], index=df1.columns)
print(df1)
print(df1.add(s, axis=1)) # axis=1表示按列相加
10. Pandas 层次化索引
import pandas as pd
import numpy as np
data = np.random.randint(0, 100, (6, 6))
index = [
['1班', '1班', '1班', '2班', '2班', '2班'],
['张三', '李四', '王五', '张三', '李四', '王五']
]
columns = [
['期中', '期中', '期中', '期末', '期末', '期末'],
['语文', '数学', '英语', '语文', '数学', '英语']
]
df = pd.DataFrame(data, index=index, columns=columns)
print(df)
data = np.random.randint(0, 100, 6)
index = [
['1班', '1班', '1班', '2班', '2班', '2班'],
['张三', '李四', '王五', '张三', '李四', '王五']
]
s = pd.Series(data=data, index=index)
print(s)
11. 多层索引中Series的索引和切片
import pandas as pd
import numpy as np
data = np.random.randint(0, 100, 6)
index = [
['1班', '1班', '1班', '2班', '2班', '2班'],
['张三', '李四', '王五', '张三', '李四', '王五']
]
s = pd.Series(data=data, index=index)
print(s)
# 显示索引
print(s['1班'])
print(s.loc['1班'])
print(s[['1班']])
print(s[['1班', '2班']])
print(s['1班', '张三'])
print(s.loc['1班', '张三'])
# 隐式索引
print(s.iloc[0])
print(s.iloc[[1, 3]])
# 切片
print(s['1班':'2班'])
print(s.loc['1班':'2班'])
print(s[1:4])
print(s.iloc[1:4])
12. 多层索引中DataFrame的索引和切片
import pandas as pd
import numpy as np
data = np.random.randint(0, 100, (6, 6))
index = [
['1班', '1班', '1班', '2班', '2班', '2班'],
['张三', '李四', '王五', '张三', '李四', '王五']
]
columns = [
['期中', '期中', '期中', '期末', '期末', '期末'],
['语文', '数学', '英语', '语文', '数学', '英语']
]
df = pd.DataFrame(data, index=index, columns=columns)
print(df)
# 获取元素
print(df['期中']['数学']['1班']['张三'])
print(df.iloc[0, 1])
print(df.loc[('1班', '张三'), ('期中', '数学')])
# 列索引
print(df['期中']['数学'])
print(df.期中.数学)
print(df.iloc[:, 2]) # 取英语成绩
# 行索引
print(df.loc['2班', '张三'])
print(df.iloc[2]) # 取一行
print(df.iloc[[1, 2]]) # 取多行
# 行切片
print(df.iloc[1:5])
print(df.loc[('1班', '张三'):('2班', '李四')])
# 列切片
print(df.iloc[:, 1:5])
print(df.loc[:, '期中':'期末'])
13. 索引的堆叠
import pandas as pd
import numpy as np
data = np.random.randint(0, 100, (6, 6))
index = [
['1班', '1班', '1班', '2班', '2班', '2班'],
['张三', '李四', '王五', '张三', '李四', '王五']
]
columns = [
['期中', '期中', '期中', '期末', '期末', '期末'],
['语文', '数学', '英语', '语文', '数学', '英语']
]
df = pd.DataFrame(data, index=index, columns=columns)
# 索引的堆叠
print(df.stack()) # 默认把列的最后一层转为行
print(df.stack().unstack()) # 默认把行的最后一层索引转为列
14. Pandas 聚合操作
import pandas as pd
import numpy as np
data = np.random.randint(0, 100, (6, 6))
index = [
['1班', '1班', '1班', '2班', '2班', '2班'],
['张三', '李四', '王五', '张三', '李四', '王五']
]
columns = [
['期中', '期中', '期中', '期末', '期末', '期末'],
['语文', '数学', '英语', '语文', '数学', '英语']
]
df = pd.DataFrame(data, index=index, columns=columns)
df2 = df.loc['1班', '期中']
print(df2)
print(df2.values.sum()) # 求所有值的和
print(df2.sum()) # 默认求每一列的和
print(df2.sum(axis=1)) # 求每一行的和
print(df2.sum(axis=0)) # 求每一列的和
print(df2.mean()) # 求每一列的平均值 跟上面的一样
15. Pandas 数据合并
concat():沿着一个轴(通常是0轴)将多个Series或DataFrame对象组合成一个新的对象。
import pandas as pd
# 创建示例数据
df1 = pd.DataFrame({
'id': [1, 2, 3],
'name': ['Alice', 'Bob', 'Charlie']
})
df2 = pd.DataFrame({
'id': [4, 5, 6],
'name': ['David', 'Eva', 'Frank']
})
# 沿行方向连接
concatenated_df = pd.concat([df1, df2], axis=0)
print(concatenated_df)
# 沿列方向连接
df3 = pd.DataFrame({
'score': [85, 90, 95]
})
concatenated_df_col = pd.concat([df1, df3], axis=1)
print(concatenated_df_col)
merge() 函数类似于 SQL 的 JOIN 操作,可以基于一个或多个键合并两个 DataFrame。
import pandas as pd
# 创建示例数据
df1 = pd.DataFrame({
'id': [1, 2, 3, 4],
'name': ['Alice', 'Bob', 'Charlie', 'David']
})
df2 = pd.DataFrame({
'id': [1, 2, 3, 5],
'score': [85, 90, 95, 80]
})
# 合并数据
merged_df = pd.merge(df1, df2, on='id', how='inner')
print(merged_df)
join() 函数用于基于索引合并 DataFrame。
import pandas as pd
# 创建示例数据
df1 = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie'],
'score': [85, 90, 95]
}, index=[1, 2, 3])
df2 = pd.DataFrame({
'city': ['New York', 'Los Angeles', 'Chicago']
}, index=[1, 2, 3])
# 基于索引合并数据
joined_df = df1.join(df2)
print(joined_df)