groupby()将行/列分组
将行/列分组到指定的组中
groupby()
是 pandas 中用于将数据分组的强大方法。它允许你根据某个条件(例如某一列的值)将数据分成若干组,然后对这些组分别进行操作,比如计算汇总统计量、应用函数等。
语法
DataFrame.groupby(by=None, axis=0, level=None, as_index=True,
sort=True, group_keys=True, squeeze=NoDefault.no_default,
observed=False, dropna=True)
参数
by
: 用于分组的键或键的列表。可以是列名、Series、索引级别等。axis
: 要分组的轴,默认为 0(行)。level
: 如果轴是 MultiIndex,则指定级别。as_index
: 如果为 True,则分组键将成为结果的索引。默认值为 True。sort
: 如果为 True,则分组后的结果会按分组键排序。默认值为 True。group_keys
: 如果为 True,则在分组键处保留分组对象。默认值为 True。squeeze
: 如果为 True 并且分组结果仅包含一个值,则返回 Series 而不是 DataFrame。observed
: 如果为 True 并且分组键是分类变量,则只包含观测到的分类组合。默认值为 False。dropna
: 如果为 True,则在分组时忽略包含 NaN 的键。默认值为 True。
返回值
返回一个 DataFrameGroupBy
或 SeriesGroupBy
对象,它可以被进一步处理以计算汇总统计量或应用其他函数。
实际案例
案例 1: 按单个列分组并计算均值
import pandas as pd
# 创建一个 DataFrame
df = pd.DataFrame({
'Category': ['A', 'B', 'A', 'B', 'A', 'B'],
'Value': [10, 20, 15, 25, 10, 30]
})
print("Original DataFrame:")
print(df)
# 使用 groupby 方法按 'Category' 列分组并计算均值
grouped = df.groupby('Category').mean()
print("\nGrouped by 'Category' and calculated mean:")
print(grouped)
结果
Original DataFrame:
Category Value
0 A 10
1 B 20
2 A 15
3 B 25
4 A 10
5 B 30
Grouped by 'Category' and calculated mean:
Value
Category
A 11.666667
B 25.000000
案例 2: 按多个列分组并计算总和
import pandas as pd
# 创建一个 DataFrame
df = pd.DataFrame({
'Category': ['A', 'B', 'A', 'B', 'A', 'B'],
'Subcategory': ['X', 'Y', 'X', 'Y', 'Z', 'Y'],
'Value': [10, 20, 15, 25, 10, 30]
})
print("Original DataFrame:")
print(df)
# 使用 groupby 方法按 'Category' 和 'Subcategory' 列分组并计算总和
grouped = df.groupby(['Category', 'Subcategory']).sum()
print("\nGrouped by 'Category' and 'Subcategory' and calculated sum:")
print(grouped)
结果
Original DataFrame:
Category Subcategory Value
0 A X 10
1 B Y 20
2 A X 15
3 B Y 25
4 A Z 10
5 B Y 30
Grouped by 'Category' and 'Subcategory' and calculated sum:
Value
Category Subcategory
A X 25
Z 10
B Y 75
案例 3: 对分组应用自定义函数
import pandas as pd
# 创建一个 DataFrame
df = pd.DataFrame({
'Category': ['A', 'B', 'A', 'B', 'A', 'B'],
'Value': [10, 20, 15, 25, 10, 30]
})
print("Original DataFrame:")
print(df)
# 自定义函数:计算范围
def range_func(x):
return x.max() - x.min()
# 使用 groupby 方法按 'Category' 列分组并应用自定义函数
grouped = df.groupby('Category')['Value'].apply(range_func)
print("\nGrouped by 'Category' and applied custom function (range):")
print(grouped)
结果
Original DataFrame:
Category Value
0 A 10
1 B 20
2 A 15
3 B 25
4 A 10
5 B 30
Grouped by 'Category' and applied custom function (range):
Category
A 5
B 10
Name: Value, dtype: int64
案例 4: 按列分组并计算多个聚合函数
import pandas as pd
# 创建一个 DataFrame
df = pd.DataFrame({
'Category': ['A', 'B', 'A', 'B', 'A', 'B'],
'Value': [10, 20, 15, 25, 10, 30]
})
print("Original DataFrame:")
print(df)
# 使用 groupby 方法按 'Category' 列分组并计算多个聚合函数
grouped = df.groupby('Category').agg({
'Value': ['mean', 'sum', 'max', 'min']
})
print("\nGrouped by 'Category' and calculated multiple aggregation functions:")
print(grouped)
结果
Original DataFrame:
Category Value
0 A 10
1 B 20
2 A 15
3 B 25
4 A 10
5 B 30
Grouped by 'Category' and calculated multiple aggregation functions:
Value
mean sum max min
Category
A 11.666667 35 15 10
B 25.000000 75 30 20
案例 5: 按 MultiIndex 分组
import pandas as pd
import numpy as np
# 创建一个 MultiIndex DataFrame
arrays = [
['A', 'A', 'A', 'B', 'B', 'B'],
['X', 'X', 'Y', 'Y', 'Z', 'Z']
]
index = pd.MultiIndex.from_arrays(arrays, names=('Category', 'Subcategory'))
df = pd.DataFrame({'Value': [10, 20, 15, 25, 10, 30]}, index=index)
print("Original DataFrame:")
print(df)
# 使用 groupby 方法按第一级别分组并计算均值
grouped = df.groupby(level='Category').mean()
print("\nGrouped by 'Category' and calculated mean:")
print(grouped)
结果
Original DataFrame:
Value
Category Subcategory
A X 10
X 20
Y 15
B Y 25
Z 10
Z 30
Grouped by 'Category' and calculated mean:
Value
Category
A 15.0
B 21.666667
通过这些示例,你可以看到 groupby()
方法如何用于在 pandas 中进行数据分组和聚合操作。这在数据分析和处理过程中非常有用,可以简化对大数据集的操作。
gt()对于大于指定值的值,返回 True,否则返回 False
对于大于指定值的值,返回 True,否则返回 False。
gt()
是 pandas 中用于逐元素比较 DataFrame 或 Series 是否大于(>)另一个对象的方法。它返回一个布尔类型的 DataFrame 或 Series,其中每个元素表示比较结果。
语法
对于 DataFrame:
DataFrame.gt(other, axis='columns', level=None)
对于 Series:
Series.gt(other, level=None)
参数
other
: 要比较的标量值、Series、DataFrame 或其他对象。axis
: {0 or 'index', 1 or 'columns'}, 默认为 'columns'。指定比较的轴。level
: 如果 DataFrame 是多层索引(MultiIndex),则指定要比较的索引级别。
返回值
返回一个布尔类型的 DataFrame 或 Series,表示每个元素是否大于对应元素。
实际案例
案例 1: DataFrame 与标量值比较
import pandas as pd
# 创建一个 DataFrame
df = pd.DataFrame({
'A': [1, 4, 3],
'B': [2, 2, 5]
})
print("Original DataFrame:")
print(df)
# 使用 gt 方法将 DataFrame 与标量值比较
df_gt = df.gt(2)
print("\nDataFrame after gt with 2:")
print(df_gt)
结果
Original DataFrame:
A B
0 1 2
1 4 2
2 3 5
DataFrame after gt with 2:
A B
0 False False
1 True False
2 True True
案例 2: DataFrame 与另一个 DataFrame 比较
import pandas as pd
# 创建两个 DataFrame
df1 = pd.DataFrame({
'A': [1, 4, 3],
'B': [2, 2, 5]
})
df2 = pd.DataFrame({
'A': [3, 3, 3],
'B': [2, 1, 6]
})
print("Original DataFrame df1:")
print(df1)
print("\nOriginal DataFrame df2:")
print(df2)
# 使用 gt 方法将两个 DataFrame 比较
df_gt = df1.gt(df2)
print("\nDataFrame after gt with df2:")
print(df_gt)
结果
Original DataFrame df1:
A B
0 1 2
1 4 2
2 3 5
Original DataFrame df2:
A B
0 3 2
1 3 1
2 3 6
DataFrame after gt with df2:
A B
0 False False
1 True True
2 False False
案例 3: Series 与标量值比较
import pandas as pd
# 创建一个 Series
s = pd.Series([1, 4, 3])
print("Original Series:")
print(s)
# 使用 gt 方法将 Series 与标量值比较
s_gt = s.gt(2)
print("\nSeries after gt with 2:")
print(s_gt)
结果
Original Series:
0 1
1 4
2 3
dtype: int64
Series after gt with 2:
0 False
1 True
2 True
dtype: bool
案例 4: DataFrame 与 Series 比较
import pandas as pd
# 创建一个 DataFrame
df = pd.DataFrame({
'A': [1, 4, 3],
'B': [2, 2, 5]
})
# 创建一个 Series
s = pd.Series([2, 3, 3])
print("Original DataFrame:")
print(df)
print("\nOriginal Series:")
print(s)
# 使用 gt 方法将 DataFrame 与 Series 比较
df_gt = df.gt(s, axis=0)
print("\nDataFrame after gt with Series:")
print(df_gt)
结果
Original DataFrame:
A B
0 1 2
1 4 2
2 3 5
Original Series:
0 2
1 3
2 3
dtype: int64
DataFrame after gt with Series:
A B
0 False False
1 True False
2 True True
通过这些示例,你可以看到 gt()
方法如何用于比较 pandas 的 DataFrame 和 Series 对象。这个方法在数据分析和处理过程中非常有用,可以帮助你快速筛选出符合条件的数据。
head()返回标题行和前 10 行,或指定的行数
返回标题行和前 10 行,或指定的行数。
head()
是 pandas 中用于返回 DataFrame 或 Series 前 n 行数据的方法。它通常用于快速查看数据集的开头部分。
语法
对于 DataFrame 和 Series:
DataFrame.head(n=5)
Series.head(n=5)
参数
n
: 整数,表示要返回的行数。默认值为 5。
返回值
返回一个 DataFrame 或 Series,包含原始数据的前 n 行。
实际案例
案例 1: 查看 DataFrame 的前 5 行(默认)
import pandas as pd
# 创建一个 DataFrame
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5, 6, 7],
'B': [7, 6, 5, 4, 3, 2, 1]
})
print("Original DataFrame:")
print(df)
# 使用 head 方法查看 DataFrame 的前 5 行
df_head = df.head()
print("\nDataFrame head (first 5 rows):")
print(df_head)
结果
Original DataFrame:
A B
0 1 7
1 2 6
2 3 5
3 4 4
4 5 3
5 6 2
6 7 1
DataFrame head (first 5 rows):
A B
0 1 7
1 2 6
2 3 5
3 4 4
4 5 3
案例 2: 查看 DataFrame 的前 3 行
import pandas as pd
# 创建一个 DataFrame
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5, 6, 7],
'B': [7, 6, 5, 4, 3, 2, 1]
})
print("Original DataFrame:")
print(df)
# 使用 head 方法查看 DataFrame 的前 3 行
df_head = df.head(3)
print("\nDataFrame head (first 3 rows):")
print(df_head)
结果
Original DataFrame:
A B
0 1 7
1 2 6
2 3 5
3 4 4
4 5 3
5 6 2
6 7 1
DataFrame head (first 3 rows):
A B
0 1 7
1 2 6
2 3 5
案例 3: 查看 Series 的前 5 行(默认)
import pandas as pd
# 创建一个 Series
s = pd.Series([10, 20, 30, 40, 50, 60, 70])
print("Original Series:")
print(s)
# 使用 head 方法查看 Series 的前 5 行
s_head = s.head()
print("\nSeries head (first 5 rows):")
print(s_head)
结果
Original Series:
0 10
1 20
2 30
3 40
4 50
5 60
6 70
dtype: int64
Series head (first 5 rows):
0 10
1 20
2 30
3 40
4 50
dtype: int64
案例 4: 查看 Series 的前 2 行
import pandas as pd
# 创建一个 Series
s = pd.Series([10, 20, 30, 40, 50, 60, 70])
print("Original Series:")
print(s)
# 使用 head 方法查看 Series 的前 2 行
s_head = s.head(2)
print("\nSeries head (first 2 rows):")
print(s_head)
结果
Original Series:
0 10
1 20
2 30
3 40
4 50
5 60
6 70
dtype: int64
Series head (first 2 rows):
0 10
1 20
dtype: int64
其他示例
案例 5: 查看 DataFrame 的前 10 行
import pandas as pd
# 创建一个 DataFrame
df = pd.DataFrame({
'A': range(1, 21),
'B': range(21, 41)
})
print("Original DataFrame:")
print(df)
# 使用 head 方法查看 DataFrame 的前 10 行
df_head = df.head(10)
print("\nDataFrame head (first 10 rows):")
print(df_head)
结果
Original DataFrame:
A B
0 1 21
1 2 22
2 3 23
3 4 24
4 5 25
5 6 26
6 7 27
7 8 28
8 9 29
9 10 30
10 11 31
11 12 32
12 13 33
13 14 34
14 15 35
15 16 36
16 17 37
17 18 38
18 19 39
19 20 40
DataFrame head (first 10 rows):
A B
0 1 21
1 2 22
2 3 23
3 4 24
4 5 25
5 6 26
6 7 27
7 8 28
8 9 29
9 10 30
通过这些示例,你可以看到 head()
方法如何用于快速查看 DataFrame 和 Series 的前几行数据。这在数据分析和处理过程中非常有用,可以帮助你快速了解数据的结构和内容。
iat在指定位置获取或设置项的值
在指定位置获取或设置项的值
iat
是 Pandas 库中的一个方法,用于通过整数位置访问单个数据元素。与 iloc
不同,iat
仅用于单个标量值的快速访问。我们来详细介绍 iat
的语法,并通过实际案例展示其使用方法和输出结果。
语法
DataFrame.iat[row_position, column_position]
- row_index: 用于选择行的整数位置。
- column_index: 用于选择列的整数位置。
用法和案例
创建一个示例 DataFrame
import pandas as pd
# 创建一个 DataFrame
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5],
'B': [10, 20, 30, 40, 50],
'C': [100, 200, 300, 400, 500]
})
print("原始 DataFrame:")
print(df)
输出结果:
原始 DataFrame:
A B C
0 1 10 100
1 2 20 200
2 3 30 300
3 4 40 400
4 5 50 500
选择单个元素
# 选择第2行第1列的元素
element = df.iat[1, 0]
print("第2行第1列的元素:", element)
# 选择第4行第3列的元素
element = df.iat[3, 2]
print("第4行第3列的元素:", element)
输出结果:
第2行第1列的元素: 2
第4行第3列的元素: 400
通过 iat
进行修改
iat
也可以用于快速修改单个元素的值。
# 修改第2行第1列的元素
df.iat[1, 0] = 22
print("修改后的 DataFrame:")
print(df)
# 修改第4行第3列的元素
df.iat[3, 2] = 440
print("\n再次修改后的 DataFrame:")
print(df)
输出结果:
修改后的 DataFrame:
A B C
0 1 10 100
1 22 20 200
2 3 30 300
3 4 40 400
4 5 50 500
再次修改后的 DataFrame:
A B C
0 1 10 100
1 22 20 200
2 3 30 300
3 4 40 440
4 5 50 500
总结
iat
是 Pandas 提供的一个方法,用于通过整数位置快速访问和修改单个数据元素。- 适用于 DataFrame 和 Series,对单个标量值进行高效的读取和写入操作。
- 与
iloc
不同,iat
仅限于单个元素的操作,适合在需要快速访问或修改单个值的场景中使用。
通过上述案例,我们可以看到 iat
的使用方法及其在实际数据操作中的应用。
idxmax()返回指定轴上最大值的标签
返回指定轴上最大值的标签
idxmax()
是 Pandas 库中的一个方法,用于返回具有最大值的元素的索引。它通常用于 Series 和 DataFrame 对象。我们来详细介绍 idxmax()
的语法,并通过实际案例展示其使用方法和输出结果。
语法
对于 Series 对象:
Series.idxmax(axis=0, skipna=True, *args, **kwargs)
对于 DataFrame 对象:
DataFrame.idxmax(axis=0, skipna=True, *args, **kwargs)
参数
- axis: {0 or ‘index’, 1 or ‘columns’}, 默认值 0
- 0 或 'index': 返回每列的最大值索引。
- 1 或 'columns': 返回每行的最大值索引。
- skipna: bool, 默认值 True
- 如果为 True,则跳过 NaN 值。
- 如果为 False,任何 NaN 值都会导致返回 NaN。
- args, kwargs: 其他未使用的参数。
返回值
返回索引的 Series,如果在 DataFrame 上使用 axis=1
,则返回的是索引列表。
实际案例
对于 Series
import pandas as pd
# 创建一个 Series
s = pd.Series([1, 3, 2, 5, 4])
# 使用 idxmax 方法
max_index = s.idxmax()
print("最大值的索引:", max_index)
输出结果:
最大值的索引: 3
对于 DataFrame
import pandas as pd
# 创建一个 DataFrame
df = pd.DataFrame({
'A': [1, 2, 3, 4],
'B': [4, 3, 2, 1],
'C': [2, 3, 1, 5]
})
# 按列查找最大值的索引
max_index_per_column = df.idxmax(axis=0)
print("每列最大值的索引:")
print(max_index_per_column)
# 按行查找最大值的索引
max_index_per_row = df.idxmax(axis=1)
print("\n每行最大值的索引:")
print(max_index_per_row)
输出结果:
每列最大值的索引:
A 3
B 0
C 3
dtype: int64
每行最大值的索引:
0 B
1 C
2 A
3 C
dtype: object
总结
Series.idxmax()
返回 Series 中最大值元素的索引。DataFrame.idxmax(axis=0)
返回每列最大值元素的索引。DataFrame.idxmax(axis=1)
返回每行最大值元素的索引。skipna
参数允许在处理数据时选择是否忽略 NaN 值。
idxmin()的详细语法与实际案例及案例输出结果
返回指定轴上最小值的标签
idxmin()
是 Pandas 库中的一个方法,用于返回具有最小值的元素的索引。它通常用于 Series 和 DataFrame 对象。我们来详细介绍 idxmin()
的语法,并通过实际案例展示其使用方法和输出结果。
语法
对于 Series 对象:
Series.idxmin(axis=0, skipna=True, *args, **kwargs)
对于 DataFrame 对象:
DataFrame.idxmin(axis=0, skipna=True, *args, **kwargs)
参数
- axis: {0 or ‘index’, 1 or ‘columns’}, 默认值 0
- 0 或 'index': 返回每列的最小值索引。
- 1 或 'columns': 返回每行的最小值索引。
- skipna: bool, 默认值 True
- 如果为 True,则跳过 NaN 值。
- 如果为 False,任何 NaN 值都会导致返回 NaN。
- args, kwargs: 其他未使用的参数。
返回值
返回索引的 Series,如果在 DataFrame 上使用 axis=1
,则返回的是索引列表。
实际案例
对于 Series
import pandas as pd
# 创建一个 Series
s = pd.Series([1, 3, 2, 5, 4])
# 使用 idxmin 方法
min_index = s.idxmin()
print("最小值的索引:", min_index)
输出结果:
最小值的索引: 0
对于 DataFrame:
import pandas as pd
# 创建一个 DataFrame
df = pd.DataFrame({
'A': [1, 2, 3, 4],
'B': [4, 3, 2, 1],
'C': [2, 3, 1, 5]
})
# 按列查找最小值的索引
min_index_per_column = df.idxmin(axis=0)
print("每列最小值的索引:")
print(min_index_per_column)
# 按行查找最小值的索引
min_index_per_row = df.idxmin(axis=1)
print("\n每行最小值的索引:")
print(min_index_per_row)
输出结果:
每列最小值的索引:
A 0
B 3
C 2
dtype: int64
每行最小值的索引:
0 A
1 A
2 C
3 B
dtype: object
总结
Series.idxmin()
返回 Series 中最小值元素的索引。DataFrame.idxmin(axis=0)
返回每列最小值元素的索引。DataFrame.idxmin(axis=1)
返回每行最小值元素的索引。skipna
参数允许在处理数据时选择是否忽略 NaN 值。
iloc在指定位置获取或设置一组元素的值
在指定位置获取或设置一组元素的值。
iloc
是 Pandas 库中的一个方法,用于通过整数位置(即基于索引位置)来选择数据。它是一个非常强大的工具,可以帮助我们根据行号和列号来索引数据。我们来详细介绍 iloc
的语法,并通过实际案例展示其使用方法和输出结果。
语法
DataFrame.iloc[row_selection, column_selection]
- row_selection: 用于选择行的整数位置、切片、列表或布尔数组。
- column_selection: 用于选择列的整数位置、切片、列表或布尔数组。
用法和案例
创建一个示例 DataFrame:
import pandas as pd
# 创建一个 DataFrame
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5],
'B': [10, 20, 30, 40, 50],
'C': [100, 200, 300, 400, 500]
})
print("原始 DataFrame:")
print(df)
输出结果:
原始 DataFrame:
A B C
0 1 10 100
1 2 20 200
2 3 30 300
3 4 40 400
4 5 50 500
选择单个元素
# 选择第2行第1列的元素
element = df.iloc[1, 0]
print("第2行第1列的元素:", element)
输出结果:
第2行第1列的元素: 2
选择整行或整列
# 选择第3行
row = df.iloc[2]
print("第3行:")
print(row)
# 选择第2列
column = df.iloc[:, 1]
print("\n第2列:")
print(column)
输出结果:
第3行:
A 3
B 30
C 300
Name: 2, dtype: int64
第2列:
0 10
1 20
2 30
3 40
4 50
Name: B, dtype: int64
选择多个行或列
# 选择第1行和第4行
rows = df.iloc[[0, 3]]
print("第1行和第4行:")
print(rows)
# 选择第1列和第3列
columns = df.iloc[:, [0, 2]]
print("\n第1列和第3列:")
print(columns)
输出结果:
第1行和第4行:
A B C
0 1 10 100
3 4 40 400
第1列和第3列:
A C
0 1 100
1 2 200
2 3 300
3 4 400
4 5 500
使用切片选择范围
# 选择第2行到第4行(不包括第4行)
rows_slice = df.iloc[1:3]
print("第2行到第4行(不包括第4行):")
print(rows_slice)
# 选择第2列到第3列(不包括第3列)
columns_slice = df.iloc[:, 1:2]
print("\n第2列到第3列(不包括第3列):")
print(columns_slice)
输出结果:
第2行到第4行(不包括第4行):
A B C
1 2 20 200
2 3 30 300
第2列到第3列(不包括第3列):
B
0 10
1 20
2 30
3 40
4 50
使用布尔索引选择
# 选择行满足特定条件的行
bool_rows = df.iloc[[True, False, True, False, True]]
print("布尔索引选择的行:")
print(bool_rows)
输出结果:
布尔索引选择的行:
A B C
0 1 10 100
2 3 30 300
4 5 50 500
总结
iloc
是基于整数位置的索引,用于选择 DataFrame 和 Series 中的数据。- 通过
iloc
可以选择单个元素、整行、整列、多个行或列、范围切片以及布尔索引。 iloc
的灵活性使得它在数据选择和过滤方面非常强大。
index返回 DataFrame 的行标签
返回 DataFrame 的行标签。
index
是 Pandas 中的一个属性,用于获取 DataFrame 或 Series 的行标签(索引)。它是一个 Index
对象,包含了所有行的标签,可以用来进行各种索引操作。
语法
对于 DataFrame 对象:
DataFrame.index
对于 Series 对象:
Series.index
用法和案例
创建一个示例 DataFrame:
import pandas as pd
# 创建一个 DataFrame
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5],
'B': [10, 20, 30, 40, 50],
'C': [100, 200, 300, 400, 500]
}, index=['a', 'b', 'c', 'd', 'e'])
print("原始 DataFrame:")
print(df)
输出结果:
原始 DataFrame:
A B C
a 1 10 100
b 2 20 200
c 3 30 300
d 4 40 400
e 5 50 500
获取 DataFrame 的索引
# 获取 DataFrame 的索引
index = df.index
print("DataFrame 的索引:", index)
输出结果:
DataFrame 的索引: Index(['a', 'b', 'c', 'd', 'e'], dtype='object')
设置 DataFrame 的索引
# 设置新的索引
df.index = ['A', 'B', 'C', 'D', 'E']
print("设置新索引后的 DataFrame:")
print(df)
输出结果:
设置新索引后的 DataFrame:
A B C
A 1 10 100
B 2 20 200
C 3 30 300
D 4 40 400
E 5 50 500
访问特定行数据
# 使用索引访问特定行的数据
row = df.loc['C']
print("索引为 'C' 的行数据:")
print(row)
输出结果:
索引为 'C' 的行数据:
A 3
B 30
C 300
Name: C, dtype: int64
重新设置索引
# 重新设置索引
df_reset = df.reset_index()
print("重新设置索引后的 DataFrame:")
print(df_reset)
输出结果:
重新设置索引后的 DataFrame:
index A B C
0 A 1 10 100
1 B 2 20 200
2 C 3 30 300
3 D 4 40 400
4 E 5 50 500
获取 Series 的索引
# 创建一个 Series
s = pd.Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e'])
print("原始 Series:")
print(s)
# 获取 Series 的索引
index = s.index
print("\nSeries 的索引:", index)
输出结果:
原始 Series:
a 1
b 2
c 3
d 4
e 5
dtype: int64
Series 的索引: Index(['a', 'b', 'c', 'd', 'e'], dtype='object')
设置 Series 的索引
# 设置新的索引
s.index = ['A', 'B', 'C', 'D', 'E']
print("设置新索引后的 Series:")
print(s)
输出结果:
设置新索引后的 Series:
A 1
B 2
C 3
D 4
E 5
dtype: int64
总结
index
属性用于获取 DataFrame 或 Series 的索引。- 索引是一个
Index
对象,可以进行各种索引操作。 - 通过设置
index
属性可以更改 DataFrame 或 Series 的索引。 loc
方法可以使用索引标签来访问特定行的数据。- 通过
reset_index
方法可以重置索引。
infer_objects()更改 DataFrame 中列的数据类型
更改 DataFrame 中列的数据类型。
infer_objects()
是 Pandas 库中的一个方法,用于将 DataFrame 中的数据类型为 object
的列转换为更具体的类型(如整数、浮点数等)。这是在处理数据时优化数据类型的一种方法,可以提高数据处理的效率和准确性。
语法
DataFrame.infer_objects()
功能
- 将
object
类型的列转换为更具体的类型,如整数 (int64
)、浮点数 (float64
) 或分类变量 (category
)。 - 不会改变已经是具体类型的列。
实际案例
示例数据集
import pandas as pd
# 创建一个示例 DataFrame
data = {
'A': [1, 2, 3, 4],
'B': ['1.1', '2.2', '3.3', '4.4'],
'C': ['x', 'y', 'z', 'w']
}
df = pd.DataFrame(data)
# 将某些列强制转换为对象类型
df['A'] = df['A'].astype(object)
df['B'] = df['B'].astype(object)
print("Before infer_objects:")
print(df.dtypes)
输出:
Before infer_objects:
A object
B object
C object
dtype: object
在这个例子中,我们创建了一个包含整数、字符串表示浮点数和纯字符串的 DataFrame,并将 A
和 B
列强制转换为 object
类型。
使用 infer_objects()
# 使用 infer_objects 方法
df = df.infer_objects()
print("After infer_objects:")
print(df.dtypes)
输出:
After infer_objects:
A int64
B float64
C object
dtype: object
具体步骤及结果分析
- 创建 DataFrame:我们创建了一个包含整数、字符串表示浮点数和纯字符串的 DataFrame。
- 强制转换为对象类型:将
A
和B
列强制转换为object
类型,结果显示所有列的数据类型均为object
类型。 - 使用
infer_objects()
:调用infer_objects()
方法后,Pandas 自动推断并将A
列转换为整数类型,将B
列转换为浮点数类型,而C
列保持为object
类型,因为C
列包含的字符串不能转换为其他具体类型。
总结
infer_objects()
方法用于将object
类型的列转换为更具体的数据类型,以提高效率和数据处理准确性。- 它不会影响已经是具体类型的列。
- 使用该方法后,DataFrame 的数据类型会变得更加明确和具体,便于后续的分析和处理。
这是一个简洁高效的方法,可以优化 DataFrame 中的数据类型,特别是在处理大型数据集时尤为有用。
info()打印有关 DataFrame 的信息
打印有关 DataFrame 的信息。
在 Python 中,info()
方法主要是 Pandas DataFrame 和 Series 对象的一部分。它用于提供数据框或序列的简要摘要信息,包括索引类型、列名称、非空值数量和数据类型等信息。
语法
对于 DataFrame 对象:
DataFrame.info(verbose=None, buf=None, max_cols=None,
memory_usage=None, null_counts=None)
对于 Series 对象(与 DataFrame 类似,只是不常用):
Series.info(verbose=None, buf=None, max_cols=None,
memory_usage=None, null_counts=None)
参数
- verbose: bool, optional
- 如果为 True,显示完整的摘要信息。
- 如果为 False,显示简要信息。
- 默认值为 None,自动决定显示简要信息还是完整信息。
- buf: writable buffer, optional
- 将输出写到指定的缓冲区(例如文件)而不是默认的 sys.stdout。
- max_cols: int, optional
- 限制显示的列数。如果列数超过这个值,则显示一条简要信息。
- memory_usage: bool, str, optional
- 如果为 True,显示内存使用情况。
- 如果为 'deep',显示深度内存使用情况,包括对象数据的内存。
- null_counts: bool, optional
- 如果为 True,显示每列的空值计数。
- 如果为 False,不显示空值计数。
- 默认值为 None,在数据集包含超过 100,000 行时,空值计数将不会显示以提升性能。
实际案例
创建一个示例 DataFrame:
import pandas as pd
import numpy as np
# 创建一个 DataFrame
df = pd.DataFrame({
'A': [1, 2, np.nan, 4, 5],
'B': [10, 20, 30, np.nan, 50],
'C': ['foo', 'bar', 'baz', 'qux', 'quux'],
'D': pd.to_datetime(['2023-01-01', '2023-01-02', np.nan, '2023-01-04', '2023-01-05'])
})
print("原始 DataFrame:")
print(df)
输出结果:
原始 DataFrame:
A B C D
0 1.0 10.0 foo 2023-01-01
1 2.0 20.0 bar 2023-01-02
2 NaN 30.0 baz NaN
3 4.0 NaN qux 2023-01-04
4 5.0 50.0 quux 2023-01-05
使用 info()
方法
# 使用 info() 方法
df.info()
输出结果:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 A 4 non-null float64
1 B 4 non-null float64
2 C 5 non-null object
3 D 4 non-null datetime64[ns]
dtypes: datetime64 , float64(2), object(1)
memory usage: 288.0+ bytes
使用参数来定制输出
1. 显示完整信息
df.info(verbose=True)
输出结果:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 A 4 non-null float64
1 B 4 non-null float64
2 C 5 non-null object
3 D 4 non-null datetime64[ns]
dtypes: datetime64 , float64(2), object(1)
memory usage: 288.0+ bytes
2. 限制显示的列数
df.info(max_cols=2)
输出结果:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 A 4 non-null float64
1 B 4 non-null float64
dtypes: float64(2)
memory usage: 208.0 bytes
3. 显示内存使用情况
df.info(memory_usage='deep')
输出结果:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 A 4 non-null float64
1 B 4 non-null float64
2 C 5 non-null object
3 D 4 non-null datetime64[ns]
dtypes: datetime64 , float64(2), object(1)
memory usage: 753.0 bytes
将输出写入文件
with open('dataframe_info.txt', 'w') as f:
df.info(buf=f)
输出结果:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 A 4 non-null float64
1 B 4 non-null float64
2 C 5 non-null object
3 D 4 non-null datetime64[ns]
dtypes: datetime64 , float64(2), object(1)
memory usage: 288.0+ bytes
(输出内容写入 dataframe_info.txt
文件中)
总结
info()
方法用于快速查看 DataFrame 或 Series 的简要摘要信息,包括索引类型、列名称、非空值数量和数据类型。- 通过使用不同的参数,可以定制输出内容,例如显示完整信息、限制显示的列数、显示内存使用情况等。
- 该方法非常有助于了解数据集的整体结构和数据质量。
insert()在 DataFrame 中插入一列
在 DataFrame 中插入一列。
在 Pandas 中,insert()
方法用于在 DataFrame 的指定位置插入一列数据。这个方法非常有用,当你需要在特定位置添加新列时。
语法
DataFrame.insert(loc, column, value, allow_duplicates=False)
参数
-
loc: int
- 列的位置,整数值,从 0 开始计数。
-
column: str
- 新列的列名。
-
value: scalar, Series, or array-like
- 新列的值,可以是标量值、Series 或者数组。
-
allow_duplicates: bool, default False
- 如果为 True,允许插入具有重复名称的列。
- 如果为 False(默认值),插入重复列名会引发错误。
实际案例
创建一个示例 DataFrame:
import pandas as pd
# 创建一个 DataFrame
df = pd.DataFrame({
'A': [1, 2, 3, 4],
'B': [10, 20, 30, 40]
})
print("原始 DataFrame:")
print(df)
输出结果:
原始 DataFrame:
A B
0 1 10
1 2 20
2 3 30
3 4 40
在指定位置插入新列
1. 在第1列位置插入新列 'C'
# 在第1列位置插入新列 'C'
df.insert(1, 'C', [100, 200, 300, 400])
print("插入新列 'C' 后的 DataFrame:")
print(df)
输出结果:
插入新列 'C' 后的 DataFrame:
A C B
0 1 100 10
1 2 200 20
2 3 300 30
3 4 400 40
2. 在第0列位置插入新列 'D'
# 在第0列位置插入新列 'D'
df.insert(0, 'D', ['x', 'y', 'z', 'w'])
print("插入新列 'D' 后的 DataFrame:")
print(df)
输出结果:
插入新列 'D' 后的 DataFrame:
D A C B
0 x 1 100 10
1 y 2 200 20
2 z 3 300 30
3 w 4 400 40
3. 尝试插入重复列名
try:
# 尝试插入重复列名
df.insert(1, 'A', [5, 6, 7, 8])
except ValueError as e:
print("插入重复列名时引发的错误:", e)
输出结果:
插入重复列名时引发的错误: cannot insert A, already exists
4. 允许插入重复列名
# 允许插入重复列名
df.insert(1, 'A', [5, 6, 7, 8], allow_duplicates=True)
print("允许插入重复列名 'A' 后的 DataFrame:")
print(df)
输出结果:
允许插入重复列名 'A' 后的 DataFrame:
D A A C B
0 x 5 1 100 10
1 y 6 2 200 20
2 z 7 3 300 30
3 w 8 4 400 40
总结
insert()
方法用于在指定位置插入新列。- 需要指定插入位置、列名和列值。
- 默认情况下,不允许插入重复列名,可以通过设置
allow_duplicates=True
允许重复。 - 该方法非常有用,当你需要在特定位置添加新列时,可以灵活地控制列的顺序和结构。
interpolate()使用插值方法替换非数字值
使用插值方法替换非数字值。
interpolate()
是 Pandas 中用于填充或插值缺失数据的方法。它支持多种插值方法,可以根据需要填充缺失值。
语法
DataFrame.interpolate(method='linear', axis=0, limit=None,
inplace=False, limit_direction='forward',
limit_area=None, downcast=None, **kwargs)
参数
-
method: str, default 'linear'
- 插值的方法。常见方法包括
'linear'
,'time'
,'index'
,'values'
,'nearest'
,'zero'
,'slinear'
,'quadratic'
,'cubic'
,'barycentric'
,'polynomial'
等。
- 插值的方法。常见方法包括
-
axis: {0 or ‘index’, 1 or ‘columns’}, default 0
- 插值的方向,0 表示按列插值,1 表示按行插值。
-
limit: int, optional
- 填充的最大连续缺失值数目。
-
inplace: bool, default False
- 是否在原 DataFrame 上进行操作。
-
limit_direction: {‘forward’, ‘backward’, ‘both’}, default ‘forward’
- 插值的方向,前向、后向或双向。
-
limit_area: {None, ‘inside’, ‘outside’}, default None
- 限制插值的区域,内部、外部或全部。
-
downcast: optional, ‘infer’ or None, default None
- 数据类型向下转换的选项。
-
kwargs: 可选参数,用于特定插值方法的附加参数。
示例数据集
import pandas as pd
import numpy as np
# 创建一个示例 DataFrame
data = {
'A': [1, 2, np.nan, 4, 5],
'B': [np.nan, 2, 3, np.nan, 5],
'C': [1, np.nan, np.nan, 4, 5]
}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
输出:
Original DataFrame:
A B C
0 1.0 NaN 1.0
1 2.0 2.0 NaN
2 NaN 3.0 NaN
3 4.0 NaN 4.0
4 5.0 5.0 5.0
各插值方法示例
1. linear
(线性插值)
linear_interpolation = df.interpolate(method='linear')
print("Linear Interpolation:")
print(linear_interpolation)
输出:
Linear Interpolation:
A B C
0 1.0 NaN 1.0
1 2.0 2.0 2.0
2 3.0 3.0 3.0
3 4.0 4.0 4.0
4 5.0 5.0 5.0
2. time
(时间插值)
适用于索引为时间序列的情况。
import pandas as pd
import numpy as np
# 创建一个带有时间索引的 DataFrame
dates = pd.date_range('20230101', periods=6)
df = pd.DataFrame({
'A': [1, 2, np.nan, 4, np.nan, 6],
'B': [np.nan, 2, 3, np.nan, 5, 6]
}, index=dates)
print("原始 DataFrame:")
print(df)
输出结果:
原始 DataFrame:
A B
2023-01-01 1.0 NaN
2023-01-02 2.0 2.0
2023-01-03 NaN 3.0
2023-01-04 4.0 NaN
2023-01-05 NaN 5.0
2023-01-06 6.0 6.0
使用时间插值填充缺失值
# 使用时间插值填充缺失值
df_interpolated = df.interpolate(method='time')
print("使用时间插值填充缺失值后的 DataFrame:")
print(df_interpolated)
输出结果:
使用时间插值填充缺失值后的 DataFrame:
A B
2023-01-01 1.0 NaN
2023-01-02 2.0 2.0
2023-01-03 3.0 3.0
2023-01-04 4.0 4.0
2023-01-05 5.0 5.0
2023-01-06 6.0 6.0
在上面的例子中,'A' 列和 'B' 列的缺失值被时间插值填充。在 'A' 列中,1.0 和 2.0 之间的缺失值被插值为 3.0,4.0 和 6.0 之间的缺失值被插值为 5.0。在 'B' 列中,2.0 和 3.0 之间的缺失值被插值为 4.0。
3. index
(索引插值)
values_interpolation = df.interpolate(method='values')
print("Values Interpolation:")
print(values_interpolation)
输出:
Values Interpolation:
A B C
0 1.0 NaN 1.0
1 2.0 2.0 2.0
2 3.0 3.0 3.0
3 4.0 4.0 4.0
4 5.0 5.0 5.0
5. nearest
(最近邻插值)
nearest_interpolation = df.interpolate(method='nearest')
print("Nearest Interpolation:")
print(nearest_interpolation)
输出:
Nearest Interpolation:
A B C
0 1.0 NaN 1.0
1 2.0 2.0 1.0
2 2.0 3.0 4.0
3 4.0 3.0 4.0
4 5.0 5.0 5.0
6. zero
(零阶保持插值)
零阶保持插值(Zero-Order Hold Interpolation),也称为阶梯插值,是一种简单的插值方法。在这种方法中,插值点的值直接取相邻数据点的值,保持不变。即在一个区间内的所有点都保持为区间左端点的值。
原理
零阶保持插值的原理非常简单:对于任何一个插值点,它的值等于最近左侧已知点的值。这样插值结果看起来像阶梯一样,因此得名阶梯插值。
公式
zero_interpolation = df.interpolate(method='zero')
print("Zero Interpolation:")
print(zero_interpolation)
输出:
Zero Interpolation:
A B C
0 1.0 NaN 1.0
1 2.0 2.0 1.0
2 2.0 3.0 4.0
3 4.0 3.0 4.0
4 5.0 5.0 5.0
7. slinear
(样条线性插值)
样条线性插值(Slinear Interpolation)是样条插值的一种特殊形式,它使用线性函数进行分段插值。样条线性插值的目的是在已知数据点之间找到一组线性函数,使得这些线性函数能够平滑地连接每个数据点,从而在已知数据点之间插值出一个新的点。它比简单的线性插值更平滑,但计算复杂度较低。
原理
这保证了插值函数在每个已知数据点处都是连续的。样条线性插值的结果就是这些线性函数的集合。
实际案例
创建一个示例 DataFrame
import pandas as pd
import numpy as np
# 创建一个带有缺失值的 DataFrame
df = pd.DataFrame({
'A': [1, 2, np.nan, 4, np.nan, 6],
'B': [np.nan, 2, 3, np.nan, 5, 6]
}, index=[0, 1, 2, 3, 4, 5])
print("原始 DataFrame:")
print(df)
输出结果:
原始 DataFrame:
A B
0 1.0 NaN
1 2.0 2.0
2 NaN 3.0
3 4.0 NaN
4 NaN 5.0
5 6.0 6.0
使用样条线性插值填充缺失值
# 使用样条线性插值填充缺失值
df_interpolated = df.interpolate(method='slinear')
print("使用样条线性插值填充缺失值后的 DataFrame:")
print(df_interpolated)
输出结果:
使用样条线性插值填充缺失值后的 DataFrame:
A B
0 1.0 NaN
1 2.0 2.0
2 3.0 3.0
3 4.0 4.0
4 5.0 5.0
5 6.0 6.0
在这个例子中,A
列和 B
列的缺失值被样条线性插值填充:
A
列中,索引为2的缺失值被插值为3.0,索引为4的缺失值被插值为5.0。B
列中,索引为3的缺失值被插值为4.0。
8、quadratic
(二次样条插值)
二次样条插值(Quadratic Spline Interpolation)是一种通过二次多项式在已知数据点之间进行插值的方法。与线性插值不同,二次样条插值可以生成更平滑的曲线,因为它在每个区间使用二次多项式进行插值。
原理
import pandas as pd
import numpy as np
# 创建一个带有缺失值的 DataFrame
df = pd.DataFrame({
'A': [1, 2, np.nan, 4, np.nan, 6],
'B': [np.nan, 2, 3, np.nan, 5, 6]
}, index=[0, 1, 2, 3, 4, 5])
print("原始 DataFrame:")
print(df)
输出结果:
原始 DataFrame:
A B
0 1.0 NaN
1 2.0 2.0
2 NaN 3.0
3 4.0 NaN
4 NaN 5.0
5 6.0 6.0
使用二次样条插值填充缺失值
quadratic_interpolation = df.interpolate(method='quadratic')
print("Quadratic Interpolation:")
print(quadratic_interpolation)
输出结果:
使用二次样条插值填充缺失值后的 DataFrame:
A B
0 1.0 NaN
1 2.0 2.0
2 3.0 3.0
3 4.0 4.0
4 4.0 5.0
5 6.0 6.0
在这个例子中,A
列和 B
列的缺失值被二次样条插值填充:
A
列中,索引为2的缺失值被插值为3.0,索引为4的缺失值被插值为4.0。B
列中,索引为3的缺失值被插值为4.0。
总结
- 二次样条插值是一种分段插值方法,使用二次多项式进行插值,适用于需要平滑插值结果的场景。
- 它比线性插值和线性样条插值更平滑,因为它考虑了每个区间内的数据点的二阶导数的连续性。
- 在 Pandas 中,可以使用
interpolate(method='quadratic')
方法进行二次样条插值。 - 这种插值方法在处理数据变化较为平缓且对插值结果平滑度要求较高的情况下非常有效。
9. cubic
(三次样条插值)
三次样条插值(Cubic Spline Interpolation)是一种更复杂和更精确的插值方法,它使用三次多项式进行分段插值。与线性和二次样条插值相比,三次样条插值在每个数据点的两侧使用三次多项式来连接数据点,从而获得更加平滑的插值结果。
原理
实际案例
cubic_interpolation = df.interpolate(method='cubic')
print("Cubic Interpolation:")
print(cubic_interpolation)
输出:
Cubic Interpolation:
A B C
0 1.0 NaN 1.0
1 2.0 2.0 2.0
2 3.0 3.0 3.0
3 4.0 4.0 4.0
4 5.0 5.0 5.0
10. barycentric
(重心插值)
重心插值(Barycentric Interpolation)是一种基于重心坐标的插值方法。它是一种数值稳定且高效的插值方法,尤其适用于插值多项式,因为它避免了拉格朗日插值中常见的数值不稳定性。
原理
重心插值的原理是使用重心坐标来计算插值多项式的值。对于已知数据点
这种方法通过使用重心权重来避免直接计算拉格朗日插值多项式,从而提高数值稳定性。
实际案例
import pandas as pd
import numpy as np
# 创建一个带有缺失值的 DataFrame
df = pd.DataFrame({
'A': [1, 2, np.nan, 4, np.nan, 6],
'B': [np.nan, 2, 3, np.nan, 5, 6]
}, index=[0, 1, 2, 3, 4, 5])
print("原始 DataFrame:")
print(df)
输出结果:
原始 DataFrame:
A B
0 1.0 NaN
1 2.0 2.0
2 NaN 3.0
3 4.0 NaN
4 NaN 5.0
5 6.0 6.0
使用重心插值填充缺失值
# 使用重心插值填充缺失值
df_interpolated = df.interpolate(method='barycentric')
print("使用重心插值填充缺失值后的 DataFrame:")
print(df_interpolated)
输出结果:
使用重心插值填充缺失值后的 DataFrame:
A B
0 1.0 NaN
1 2.0 2.0
2 3.0 3.0
3 4.0 4.0
4 5.0 5.0
5 6.0 6.0
在这个例子中,A
列和 B
列的缺失值被重心插值填充:
A
列中,索引为2的缺失值被插值为3.0,索引为4的缺失值被插值为5.0。B
列中,索引为3的缺失值被插值为4.0。
总结
- 重心插值是一种数值稳定且高效的插值方法,特别适用于插值多项式。
- 它通过计算重心权重来避免拉格朗日插值中的数值不稳定性。
- 在 Pandas 中,可以使用
interpolate(method='barycentric')
方法进行重心插值。 - 这种插值方法适用于需要高精度插值结果的场景,并且在处理数据变化较为平缓的情况下非常有效。
11. polynomial
(多项式插值)
多项式插值(Polynomial Interpolation)是一种使用多项式函数来进行插值的方法。它的目标是在已知数据点之间找到一个多项式,使其经过所有已知点,从而在这些点之间进行插值。多项式插值能够产生光滑的插值曲线,但在某些情况下可能会出现龙格现象(Runge's phenomenon),即在插值区间边界附近出现大的振荡。
原理
import pandas as pd
import numpy as np
# 创建一个带有缺失值的 DataFrame
df = pd.DataFrame({
'A': [1, 2, np.nan, 4, np.nan, 6],
'B': [np.nan, 2, 3, np.nan, 5, 6]
}, index=[0, 1, 2, 3, 4, 5])
print("原始 DataFrame:")
print(df)
输出结果:
原始 DataFrame:
A B
0 1.0 NaN
1 2.0 2.0
2 NaN 3.0
3 4.0 NaN
4 NaN 5.0
5 6.0 6.0
输出结果:
使用二次多项式插值填充缺失值后的 DataFrame:
A B
0 1.0 NaN
1 2.0 2.0
2 3.0 3.0
3 4.0 4.0
4 5.0 5.0
5 6.0 6.0
在这个例子中,A
列和 B
列的缺失值被二次多项式插值填充:
A
列中,索引为2的缺失值被插值为3.0,索引为4的缺失值被插值为5.0。B
列中,索引为3的缺失值被插值为4.0。
总结
- 多项式插值是一种使用多项式函数进行插值的方法,适用于需要平滑插值结果的场景。
- 可以选择不同的多项式阶数来进行插值,阶数越高,插值结果越精细,但也更容易出现数值不稳定性。
- 在 Pandas 中,可以使用
interpolate(method='polynomial', order=n)
方法进行多项式插值,其中order
参数指定多项式的阶数。 - 多项式插值适用于数据变化较为平缓且对插值结果平滑度要求较高的情况,但需要注意避免过高阶数可能带来的数值不稳定性。
isin()判断 DataFrame 或 Series 中的元素是否包含在给定的列表、Series 或字典中
如果 DataFrame 中的每个元素都在指定值中,则返回 True。
isin()
是 Pandas 中的一个方法,用于判断 DataFrame 或 Series 中的元素是否包含在给定的列表、Series 或字典中。它返回一个布尔 DataFrame 或 Series,表示每个元素是否在给定的序列中。
语法
对于 Series 对象:
Series.isin(values)
对于 DataFrame 对象:
DataFrame.isin(values)
参数
- values: list-like, Series, or dict
- 要检查的值,可以是列表、Series 或字典。
- 如果是字典,键应该是列名称,值是要检查的值列表。
实际案例
创建一个示例 DataFrame
import pandas as pd
# 创建一个 DataFrame
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5],
'B': ['a', 'b', 'c', 'd', 'e'],
'C': [1.1, 2.2, 3.3, 4.4, 5.5]
})
print("原始 DataFrame:")
print(df)
输出结果:
原始 DataFrame:
A B C
0 1 a 1.1
1 2 b 2.2
2 3 c 3.3
3 4 d 4.4
4 5 e 5.5
使用 isin()
方法
1. 检查列 'A' 中的值是否在给定列表中
# 检查列 'A' 中的值是否在给定列表中
isin_A = df['A'].isin([1, 3, 5])
print("列 'A' 中的值是否在 [1, 3, 5] 中:")
print(isin_A)
输出结果:
列 'A' 中的值是否在 [1, 3, 5] 中:
0 True
1 False
2 True
3 False
4 True
Name: A, dtype: bool
2. 检查整个 DataFrame 中的值是否在给定列表中
# 检查整个 DataFrame 中的值是否在给定列表中
isin_df = df.isin([1, 'a', 3.3])
print("整个 DataFrame 中的值是否在 [1, 'a', 3.3] 中:")
print(isin_df)
输出结果:
整个 DataFrame 中的值是否在 [1, 'a', 3.3] 中:
A B C
0 True True False
1 False False False
2 False False True
3 False False False
4 False False False
3. 使用字典检查指定列中的值是否在给定列表中
# 使用字典检查指定列中的值是否在给定列表中
isin_dict = df.isin({'A': [1, 2], 'B': ['a', 'c']})
print("使用字典检查指定列中的值:")
print(isin_dict)
输出结果:
使用字典检查指定列中的值:
A B C
0 True True False
1 True False False
2 False True False
3 False False False
4 False False False
使用 isin()
方法过滤 DataFrame
1. 过滤 DataFrame 中列 'A' 的值在给定列表中的行
# 过滤 DataFrame 中列 'A' 的值在给定列表中的行
filtered_df_A = df[df['A'].isin([1, 3, 5])]
print("过滤列 'A' 的值在 [1, 3, 5] 中的行:")
print(filtered_df_A)
输出结果:
过滤列 'A' 的值在 [1, 3, 5] 中的行:
A B C
0 1 a 1.1
2 3 c 3.3
4 5 e 5.5
2. 过滤整个 DataFrame 中的值在给定列表中的行
# 过滤整个 DataFrame 中的值在给定列表中的行
filtered_df = df[df.isin([1, 'a', 3.3]).any(axis=1)]
print("过滤整个 DataFrame 中的值在 [1, 'a', 3.3] 中的行:")
print(filtered_df)
输出结果:
过滤整个 DataFrame 中的值在 [1, 'a', 3.3] 中的行:
A B C
0 1 a 1.1
2 3 c 3.3
总结
isin()
方法用于判断 DataFrame 或 Series 中的元素是否包含在给定的列表、Series 或字典中,返回布尔 DataFrame 或 Series。- 可以用于过滤 DataFrame 或 Series 中的值,以实现数据筛选和清洗操作。
- 支持多种类型的输入,包括列表、Series 和字典,灵活性高。
isna()用于检测缺失值
isna()
是 Pandas 中用于检测缺失值的方法。它返回一个布尔 DataFrame 或 Series,其中 True
表示相应位置的值是缺失的(NaN 或 None),False
表示相应位置的值不是缺失的。
语法
对于 DataFrame 对象:
DataFrame.isna()
对于 Series 对象:
Series.isna()
实际案例
创建一个示例 DataFrame
import pandas as pd
import numpy as np
# 创建一个 DataFrame
df = pd.DataFrame({
'A': [1, 2, np.nan, 4, 5],
'B': [np.nan, 2, 3, np.nan, 5],
'C': [1, 2, 3, 4, np.nan],
'D': [np.nan, np.nan, np.nan, np.nan, np.nan]
})
print("原始 DataFrame:")
print(df)
输出结果:
原始 DataFrame:
A B C D
0 1.0 NaN 1.0 NaN
1 2.0 2.0 2.0 NaN
2 NaN 3.0 3.0 NaN
3 4.0 NaN 4.0 NaN
4 5.0 5.0 NaN NaN
使用 isna()
方法
1. 检查 DataFrame 中的缺失值
# 检查 DataFrame 中的缺失值
na_df = df.isna()
print("DataFrame 中的缺失值:")
print(na_df)
输出结果:
DataFrame 中的缺失值:
A B C D
0 False True False True
1 False False False True
2 True False False True
3 False True False True
4 False False True True
2. 检查 Series 中的缺失值
# 检查列 'A' 中的缺失值
na_series = df['A'].isna()
print("列 'A' 中的缺失值:")
print(na_series)
输出结果:
列 'A' 中的缺失值:
0 False
1 False
2 True
3 False
4 False
Name: A, dtype: bool
使用 isna()
方法过滤缺失值
1. 过滤 DataFrame 中不包含缺失值的行
# 过滤 DataFrame 中不包含缺失值的行
filtered_df = df.dropna()
print("过滤不包含缺失值的行:")
print(filtered_df)
输出结果:
过滤不包含缺失值的行:
Empty DataFrame
Columns: [A, B, C, D]
Index: []
由于我们示例 DataFrame 中的每一行都包含至少一个缺失值,所以过滤后得到的 DataFrame 为空。
2. 过滤 DataFrame 中包含缺失值的行
# 过滤 DataFrame 中包含缺失值的行
filtered_na_df = df[df.isna().any(axis=1)]
print("过滤包含缺失值的行:")
print(filtered_na_df)
输出结果:
过滤包含缺失值的行:
A B C D
0 1.0 NaN 1.0 NaN
1 2.0 2.0 2.0 NaN
2 NaN 3.0 3.0 NaN
3 4.0 NaN 4.0 NaN
4 5.0 5.0 NaN NaN
总结
isna()
方法用于检测 DataFrame 或 Series 中的缺失值,返回布尔类型的 DataFrame 或 Series。- 可以与其他 Pandas 方法结合使用,以实现数据过滤、清洗和分析。
- 该方法对数据处理和预处理非常有用,能够帮助我们轻松识别和处理缺失数据。
isnull()查找空值
查找空值
isnull()
是 Pandas 中用于检测缺失值的方法。它返回一个布尔类型的 DataFrame 或 Series,其中 True
表示相应位置的值是缺失的(NaN 或 None),False
表示相应位置的值不是缺失的。
语法
对于 DataFrame 对象:
DataFrame.isnull()
对于 Series 对象:
Series.isnull()
实际案例
import pandas as pd
import numpy as np
# 创建一个带有缺失值的 DataFrame
df = pd.DataFrame({
'A': [1, 2, np.nan, 4, 5],
'B': [np.nan, 2, 3, np.nan, 5],
'C': [1, 2, 3, 4, np.nan],
'D': [np.nan, np.nan, np.nan, np.nan, np.nan]
})
print("原始 DataFrame:")
print(df)
输出结果:
原始 DataFrame:
A B C D
0 1.0 NaN 1.0 NaN
1 2.0 2.0 2.0 NaN
2 NaN 3.0 3.0 NaN
3 4.0 NaN 4.0 NaN
4 5.0 5.0 NaN NaN
使用 isnull()
方法
1. 检查 DataFrame 中的缺失值
# 检查 DataFrame 中的缺失值
null_df = df.isnull()
print("DataFrame 中的缺失值:")
print(null_df)
输出结果:
DataFrame 中的缺失值:
A B C D
0 False True False True
1 False False False True
2 True False False True
3 False True False True
4 False False True True
2. 检查 Series 中的缺失值
# 检查列 'A' 中的缺失值
null_series = df['A'].isnull()
print("列 'A' 中的缺失值:")
print(null_series)
输出结果:
列 'A' 中的缺失值:
0 False
1 False
2 True
3 False
4 False
Name: A, dtype: bool
使用 isnull()
方法过滤缺失值
1. 过滤 DataFrame 中不包含缺失值的行
# 过滤 DataFrame 中不包含缺失值的行
filtered_df = df.dropna()
print("过滤不包含缺失值的行:")
print(filtered_df)
输出结果:
过滤不包含缺失值的行:
Empty DataFrame
Columns: [A, B, C, D]
Index: []
由于我们示例 DataFrame 中的每一行都包含至少一个缺失值,所以过滤后得到的 DataFrame 为空。
2. 过滤 DataFrame 中包含缺失值的行
# 过滤 DataFrame 中包含缺失值的行
filtered_na_df = df[df.isnull().any(axis=1)]
print("过滤包含缺失值的行:")
print(filtered_na_df)
输出结果:
过滤包含缺失值的行:
A B C D
0 1.0 NaN 1.0 NaN
1 2.0 2.0 2.0 NaN
2 NaN 3.0 3.0 NaN
3 4.0 NaN 4.0 NaN
4 5.0 5.0 NaN NaN
替换缺失值
# 替换缺失值为0
filled_df = df.fillna(0)
print("替换缺失值为0后的 DataFrame:")
print(filled_df)
输出结果:
替换缺失值为0后的 DataFrame:
A B C D
0 1.0 0.0 1.0 0.0
1 2.0 2.0 2.0 0.0
2 0.0 3.0 3.0 0.0
3 4.0 0.0 4.0 0.0
4 5.0 5.0 0.0 0.0
总结
isnull()
方法用于检测 DataFrame 或 Series 中的缺失值,返回布尔类型的 DataFrame 或 Series。isnull()
和isna()
是等价的,功能完全相同。- 可以与其他 Pandas 方法结合使用,以实现数据过滤、清洗和分析。
- 该方法对数据处理和预处理非常有用,能够帮助我们轻松识别和处理缺失数据。