Pandas教程-Pandas DataFrame 的索引和选择
Pandas 是 Python 中用于数据分析应用的最重要的库之一。首先,Pandas 中的 DataFrame 就像一个表格或一个具有行和列的二维数组。它是一个可变的和异构的数据结构。我们把行和列称为轴。
Pandas 提供了许多函数来操作数据分析中的 DataFrame。我们可以通过多种方式创建 DataFrame,但使用的函数是:
pandas.DataFrame(data, row_labels, column_labels)
要使用此函数或库中的任何函数,首先我们必须导入库,如下所示:
import pandas as pd
pd.DataFrame()
在本教程中,我们在 Excel 表格 "painters.xlsx" 中创建了一个包含世界上最伟大的 20 位画家信息的表格。
现在,以下是一个将此表格创建为 Pandas DataFrame 的 Python 代码:
import pandas as pd
df = pd.read_excel("painters.xlsx", index_col = 0)
print(df)
输出:
本教程的标题是 "DataFrame 的索引和选择"。就像我们使用索引从 0 到长度 - 1 切割字符串一样,我们也可以访问、复制并从现有 DataFrame 创建新 DataFrame。 本教程解释了所有这些方法。
- DataFrame[] 和 DataFrame.column
- DataFrame.loc[]
- DataFrame.iloc[]
- head() 和 tail()
1. [] 和 .
[] 被称为索引运算符,. 被称为属性运算符 在 Pandas 中使用。这些运算符用于对 DataFrame 进行基本的索引和查看不同子集。
使用属性运算符(.):
选择列:
- 我们只能使用此运算符从 DataFrame 中选择单个列。它仅限于具有直接引用的列。这意味着如果列名包含空格,Python 将无法正确解析:
在我们的 Painters 表格中:
import pandas as pd
df = pd.read_excel("painters.xlsx", index_col = 0)
print(df.Birth)
print(df.Greatest Artpiece)
输出:
请注意,尝试访问列 "Greatest Artpiece" 时引发语法错误,因为有空格。如果我们想要访问属性,可以使用 getattr(DataFrame, column_name)
函数。
Import pandas as pd
df = pd.read_excel("painters.xlsx", index_col = 0)
print(getattr(df, "Greatest Artpiece"))
输出:
使用索引运算符:
选择列:
我们需要将列的名称传递给运算符,但这里对列名中的任何空格都没有限制:
import pandas as pd
df = pd.read_excel("painters.xlsx", index_col = 0)
print(df["Greatest Artpiece"])
请注意,列名必须用引号括起来。
输出:
- 此运算符的另一个功能是我们甚至可以通过将所需的列列表传递给函数来选择多列:
import pandas as pd
df = pd.read_excel("painters.xlsx", index_col = 0)
print(df[["Name", "Nationality"]])
输出:
选择行:
使用切片运算符,我们可以使用相同的索引运算符选择 DataFrame 的行。切片的语法与任何其他可迭代对象的语法相同:
# 对象[开始:结束:步骤]
# 开始: 起始索引/行位置(包含)
# 结束: 停止切片的位置(不包括)
# 步骤: 选择行之间的间隔
import pandas as pd
cols = [0, 1, 2, 3, 4]
df = pd.read_excel("painters.xlsx", index_col=0)
print(df[1:4])
输出:
如果我们在创建时使用了行标签,我们还可以使用它们。这里是一个例子:
import pandas as pd
dictionary = {"Name": ["Harry", "Zayn", "Niall"], "Age": [28, 28, 29]}
df1 = pd.DataFrame(dictionary, index = ["Member 1", "Member 2", "Member 3"])
print(df1)
print()
print(df1[0: 2])
print()
print(df1["Member 1": "Member 3"])
输出:
- 请注意,使用位置切片时,结束位置是排他的,但是当我们使用行标签时,最后一行是包含的。
总结索引运算符的几点:
- 我们可以使用 [] 从 DataFrame 中选择行和列。
- 在选择列时,可以选择单个列或多个列。
- 当使用切片运算符时,它将选择行。
- 我们可以使用位置或行标签切片行。当使用位置时,最后一行不被选择,但是当使用行标签时,最后一行被选择。
到目前为止,我们无法同时选择 DataFrame 的行和列。有两个 Pandas 中专门用于选择和子集化 DataFrame 的函数。这些函数具有明确的功能。我们现在将学习它们。
2. DataFrame.iloc
语法:
DataFrame.iloc[rows, columns]
行和列必须是位置,而不是标签,这些位置可以按以下方式给出:
- 单个位置
- 多个位置的列表
- 位置的切片
下面是我们将要修改的表格:
请注意,第 0 行和第 0 列被称为第 1 行和第 1 列。
- 单个位置:
语法:
DataFrame.iloc[row_position, column_position]
代码:
import pandas as pd
cols = [0, 1, 2, 3, 4]
df = pd.read_excel("D:\Internships\JavaTpoint\October-new pos\painters.xlsx", index_col = 0)
print("The value in 2nd row and 2nd column:")
print(df.iloc[1, 1]) #0th-1st, 1st - 2nd
输出:
- 位置列表:
语法:
DataFrame.iloc[[r1, r2..], [c1, c2..]]
代码:
import pandas as pd
cols = [0, 1, 2, 3, 4]
df = pd.read_excel("D:\Internships\JavaTpoint\October-new pos\painters.xlsx", index_col = 0)
print("First three rows and columns:")
print(df.iloc[[0, 1, 2], [0, 1, 2]])
输出:
- 单个位置和位置列表的组合:
语法:
DataFrame.iloc[row_position, [c1, c2...]] #Single row, multiple columns
DataFrame.iloc[[r1, r2...], column_position] #Multiple rows and single column
代码:
import pandas as pd
cols = [0, 1, 2, 3, 4]
df = pd.read_excel("D:\Internships\JavaTpoint\October-new pos\painters.xlsx", index_col = 0)
print("Values in first two columns in 2nd row:")
print(df.iloc[1, [0, 1]])
print()
print("Values in first two rows in 2nd column:")
print(df.iloc[[0, 1], 1])
输出:
- 切片
语法:
DataFrame.iloc[start: stop: step, start: stop: step]
代码:
import pandas as pd
cols = [0, 1, 2, 3, 4]
df = pd.read_excel("D:\Internships\JavaTpoint\October-new pos\painters.xlsx", index_col = 0)
print("Values in first row:")
print(df.iloc[0, ::])
print()
print("Values in first column:")
print(df.iloc[::, 0])
print()
print("Values in 2, 3, 4 rows and 3, 4, 5 columns:")
print(df.iloc[1: 3, 2: 4])
print()
print("Values in even rows and even columns:")
print(df.iloc[1::2, 1::2])
输出:
3. DataFrame.loc[行, 列]
如上所述,iloc[] 使用位置,而 loc[] 使用标签,而其他功能是相同的。
行和列都必须是标签,这些标签可以如下给出:
- 单个行或列标签
- 多个标签的列表
- 标签的切片
注意: 在对行或列标签使用切片运算符时,结束标签将包括在内,与我们使用索引运算符-[] 切片时相同。
以下是我们将要修改的表格:
- 单个标签:
语法:
DataFrame.loc[row_label, column_label]
代码:
import pandas as pd
cols = [0, 1, 2, 3, 4]
df = pd.read_excel("D:\Internships\JavaTpoint\October-new pos\painters.xlsx", index_col = 0)
print("The value in 2nd row and 2nd column:")
print(df.loc[1, "Birth"])
输出:
- 标签列表:
语法:
DataFrame.loc[[r1, r2..], [c1, c2..]]
代码:
import pandas as pd
cols = [0, 1, 2, 3, 4]
df = pd.read_excel("D:\Internships\JavaTpoint\October-new pos\painters.xlsx", index_col = 0)
print("First three rows and columns:")
print(df.loc[[0, 1, 2], ["Name", "Birth", "Death"]])
输出:
- 单个位置和位置列表的组合:
语法:
DataFrame.iloc[row_label, [c1, c2...]] #Single row, multiple columns
DataFrame.iloc[[r1, r2...], column_label] #Multiple rows and single column
代码:
import pandas as pd
cols = [0, 1, 2, 3, 4]
df = pd.read_excel("D:\Internships\JavaTpoint\October-new pos\painters.xlsx", index_col = 0)
print("Values in first two columns in 2nd row:")
print(df.loc[1, ["Name", "Birth"]])
print()
print("Values in first two rows in 2nd column:")
print(df.loc[[0, 1], "Birth"])
输出:
- 切片
语法:
DataFrame.iloc[start: stop: step, start: stop: step]
代码:
import pandas as pd
cols = [0, 1, 2, 3, 4]
df = pd.read_excel("D:\Internships\JavaTpoint\October-new pos\painters.xlsx", index_col = 0)
print("Values in first row:")
print(df.loc[0, ::])
print()
print("Values in first column:")
print(df.loc[::, "Name"])
print()
print("Values in 2, 3, 4 rows and 3, 4, 5 columns:")
print(df.loc[1: 3, "Death": "Nationality"])
print()
print("Values in even rows and even columns:")
print(df.loc[1::2, "Birth"::2])
输出:
观察当我们给出:
print(df.loc[1: 3, "Death": "Nationality"])
行: 第 1、2 和 3 行
列: 被打印出 "Death", "Greatest Artpiece," 和 "Nationality",这意味着最后一行和列也被包括在内。
带条件:
到目前为止,我们使用位置号码或标签从 DataFrame 中选择数据。我们还可以根据我们需要的条件选择数据,使用两种方法 loc[] 和索引运算符:
以下是一些要点:
1.我们可以使用任何布尔运算符,但在这里,我们必须使用:
& for and operation
| for or operation
~ for not operation
2.我们可以使用任意数量的条件,但是每个条件都必须使用括号括起来。
import pandas as pd
cols = [0, 1, 2, 3, 4]
df = pd.read_excel("D:\Internships\JavaTpoint\October-new pos\painters.xlsx", index_col = 0)
print("American or French painter born after 1800:")
print(df[(df["Birth"]>1800) & ((df["Nationality"]=="American") | (df["Nationality"]=="French"))])
输出:
3.比如说我们想打印所有在 1800 年之后出生的画家。我们需要检查 Birth 列:
df["Birth"] > 1800
这是条件。我们在检查条件后,如果打印它,我们将得到该列的 True 和 False。现在,如果我们想打印行,我们需要将条件传递给 df[]:
df[df["Birth"] > 1800]
4.使用 loc[],我们可以将条件直接传递给运算符,就像我们传递给 df[] 一样。使用 loc[] 的附加优势是,我们可以使用切片选择列。
这是一个例子:
import pandas as pd
cols = [0, 1, 2, 3, 4]
df = pd.read_excel("D:\Internships\JavaTpoint\October-new pos\painters.xlsx", index_col = 0)
print("Using loc():")
print("Painters born after 1800:")
print(df.loc[(df["Birth"]>1800)])
print("Selecting a few columns:")
print(df.loc[(df["Birth"]>1800), "Name": "Birth"])
输出: