Pandas 教程-Pandas DataFrame 的索引和选择
整理:python架构师
Pandas 是 Python 中用于数据分析应用的最重要的库之一。首先,Pandas 中的 DataFrame 就像一个表格或一个具有行和列的二维数组。它是一个可变的和异构的数据结构。我们把行和列称为轴。
pandas.DataFrame(data, row_labels, column_labels)
import pandas as pdpd.DataFrame()
import pandas as pddf = pd.read_excel("painters.xlsx", index_col = 0)print(df)
DataFrame[] 和 DataFrame.column
DataFrame.loc[]
DataFrame.iloc[]
head() 和 tail()
👉点击领取:最全Python资料合集
1. [] 和 .
[] 被称为索引运算符,. 被称为属性运算符 在 Pandas 中使用。这些运算符用于对 DataFrame 进行基本的索引和查看不同子集。
使用属性运算符(.):
选择列:
我们只能使用此运算符从 DataFrame 中选择单个列。它仅限于具有直接引用的列。这意味着如果列名包含空格,Python 将无法正确解析:
import pandas as pddf = pd.read_excel("painters.xlsx", index_col = 0)print(df.Birth)print(df.Greatest Artpiece)
输出:
Import pandas as pddf = pd.read_excel("painters.xlsx", index_col = 0)print(getattr(df, "Greatest Artpiece"))
输出:
使用索引运算符:
选择列:
import pandas as pddf = pd.read_excel("painters.xlsx", index_col = 0)print(df["Greatest Artpiece"])
请注意,列名必须用引号括起来。
此运算符的另一个功能是我们甚至可以通过将所需的列列表传递给函数来选择多列:
import pandas as pddf = pd.read_excel("painters.xlsx", index_col = 0)print(df[["Name", "Nationality"]])
选择行:
# 对象[开始:结束:步骤]# 开始: 起始索引/行位置(包含)# 结束: 停止切片的位置(不包括)# 步骤: 选择行之间的间隔import pandas as pdcols = [0, 1, 2, 3, 4]df = pd.read_excel("painters.xlsx", index_col=0)print(df[1:4])
import pandas as pddictionary = {"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 pdcols = [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 pdcols = [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 columnsDataFrame.iloc[[r1, r2...], column_position] #Multiple rows and single column
import pandas as pdcols = [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 pdcols = [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 pdcols = [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 pdcols = [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 columnsDataFrame.iloc[[r1, r2...], column_label] #Multiple rows and single column
import pandas as pdcols = [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 pdcols = [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[] 和索引运算符:
以下是一些要点:
& for and operation| for or operation~ for not operation
import pandas as pdcols = [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"))])
df["Birth"] > 1800这是条件。我们在检查条件后,如果打印它,我们将得到该列的 True 和 False。现在,如果我们想打印行,我们需要将条件传递给 df[]:
df[df["Birth"] > 1800]
4.使用 loc[],我们可以将条件直接传递给运算符,就像我们传递给 df[] 一样。使用 loc[] 的附加优势是,我们可以使用切片选择列。
import pandas as pdcols = [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"])
热门推荐