索引的力量:利用 Pandas 提高数据整理效率

@高效码农  August 16, 2023

介绍

Pandas 是使用最广泛的 Python 数据操作库,它使我们能够有效地访问和操作数据。

通过在 Pandas 中有效地理解和利用索引技术,我们可以显着提高数据整理任务的速度和效率。

在本文中,我们将探索 Pandas 中的各种索引技术,并将了解如何利用它们来更快地进行数据整理。

在 Pandas 中引入索引

Pandas 库提供了两个主要对象:Series 和 DataFrame。

Pandas Series 是一个一维标记数组,能够保存任何类型的数据类型。

Pandas DataFrame 是一个表格,类似于电子表格,能够存储任何类型的数据,并由行和列构建。

更准确地说,Pandas DataFrame 也可以看作是 Pandas Series 的有序集合。

因此,Series 和 DataFrame 都有一个索引,它提供了一种唯一标识和访问每个元素的方法。

在本文中,我们将演示 Pandas 中的一些索引技术,以增强您的日常数据操作任务。

Pandas 中的编码索引技术

现在,让我们使用实际的 Python 代码探索一些索引技术。

基于整数的索引

我们将从基于整数的方法开始,该方法使我们能够选择数据框中的行和列。

广告

但首先,让我们了解如何在 Pandas 中创建数据框:

import pandas as pd

# Create tabular data
data = {
    'A': [1, 2, 3, 4, 5],
    'B': [6, 7, 8, 9, 10],
    'C': [11, 12, 13, 14, 15]
}

# Create data frame
df = pd.DataFrame(data)

# Show data frame
print(df)

这将产生:

   A   B   C
0  1   6  11
1  2   7  12
2  3   8  13
3  4   9  14
4  5  10  15

正如我们所看到的,Pandas 数据框的数据创建方式与我们在 Python 中创建字典的方式相同。事实上,列的名称是键,列表中的数字是值。列名和值由冒号分隔,就像字典中的键和值一样。最后,它们位于大括号内。

基于整数的方法使用iloc[]索引数据帧的方法。例如,如果我们想要索引两行,我们可以输入以下内容:

# Select rows from index 1 to 3 using .iloc[]
sliced_rows = df.iloc[1:3]

# Print sliced rows
print(sliced_rows)

我们得到:

    A  B   C
1   2  7  12
2   3  8  13

注意:请记住,在 Python 中我们从 0 开始计数,iloc[1:3]选择​​第二行和第三行。

现在,iloc[]还可以像这样选择列:

# Select columns 0 to 2 using .iloc[]
sliced_cols = df.iloc[:, 0:2]

# Print sliced columns
print(sliced_cols)

我们得到:

   A   B
0  1   6
1  2   7
2  3   8
3  4   9
4  5  10

广告

So, in this case, the colon inside the square brackets means that we want to take all the values in the rows. Then, after the comma, we specify which columns we want to get (remembering that we start counting from 0).

用整数对索引进行切片的另一种方法是使用loc[]方法。例如,像这样:

# Select rows with index labels using .loc[]
sliced_rows = df.loc[1:3]

# Show sliced rows
print(sliced_rows)

我们得到:

   A  B   C
1  2  7  12
2  3  8  13
3  4  9  14

另外,我们想补充一点,该loc[]方法使我们能够使用重命名的索引对 Pandas DataFrame 进行切片。让我们通过一个例子来看看我们的意思:

import pandas as pd

# Create tabular data
data = {
    'A': [1, 2, 3, 4, 5],
    'B': [6, 7, 8, 9, 10],
    'C': [11, 12, 13, 14, 15]
}

# Rename indexes
df = pd.DataFrame(data, index=['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'])

# Select rows with index labels from 'Row_2' to 'Row_4'
sliced_rows = df.loc['Row_2':'Row_4']

# Print sliced rows
print(sliced_rows)

我们得到:

       A  B   C
Row_2  2  7  12
Row_3  3  8  13
Row_4  4  9  14

因此,正如我们所看到的,现在索引不再是整数:它们是字符串,并且该loc[]方法可用于像我们一样对数据帧进行切片。

布尔索引

布尔索引涉及根据表示为布尔值的条件选择行或列。数据框(或系列)将被过滤以仅包含满足给定条件的行或列。

例如,假设我们有一个包含所有数值的数据框。我们希望通过对列进行索引来过滤数据框,以便它仅向我们显示大于 2 的值。我们可以这样做:

import pandas as pd

data = {
    'A': [1, 2, 3, 4, 5],
    'B': [6, 7, 8, 9, 10],
    'C': [11, 12, 13, 14, 15]
}

# Create data frame
df = pd.DataFrame(data)

# Select rows where column 'A' is greater than 2
condition = df['A'] > 2

# Create filtered data frame
filtered_rows = df[condition]

# Print new data frame
print(filtered_rows)

我们得到:

Free eBook: Git Essentials

查看我们的 Git 学习实践指南,其中包含最佳实践、行业认可的标准以及随附的备忘单。停止谷歌搜索 Git 命令并真正学习它!

下载电子书  

   A   B   C
2  3   8  13
3  4   9  14
4  5  10  15

因此,通过condition = df['A'] > 2,我们创建了一个 Pandas 系列,它在 列 中获取大于二的值A。然后,filtered_rows = df[condition]我们创建了过滤后的数据框,该数据框仅显示与我们对列施加的条件相匹配的行A

当然,我们可以对数据帧建立索引,使其匹配不同的条件,甚至对于不同的列。例如,假设我们要在 columnA和 column 上添加条件B。我们可以这样做:

# Imposing the condition on two columns
condition = (df['A'] > 2) & (df['B'] < 10)

# Create filtered dataframe
filtered_rows = df[condition]

# Print filtered dataframe
print(filtered_rows)

我们得到:

   A  B   C
2  3  8  13
3  4  9  14

因此,要添加多个条件,我们使用运算符&

此外,我们甚至可以对整个数据帧进行切片。例如,假设我们只想查看值大于 8 的列。我们可以这样做:

# Imposing the condition on the entire data frame
condition = (df > 8).all()

# Index for the imposed condition
filtered_cols = df.loc[:, condition]

# Print result
print(filtered_cols)

我们得到:

    C
0  11
1  12
2  13
3  14
4  15

因此,只有列C符合强加的条件。
因此,通过 方法all(),我们对整个数据框施加了一个条件。

设置新索引并重置为旧索引

在某些情况下,我们可能会获取 Pandas 数据框的一列并将其用作整个数据框的索引。例如,在这种操作可能会导致更快的索引切片的情况下。

例如,假设我们有一个数据框架,用于存储与国家、城市及其各自人口相关的数据。我们可能希望将城市列设置为数据框的索引。我们可以这样做:

import pandas as pd

data = {
    'City': ['New York', 'Los Angeles', 'Chicago', 'Houston'],
    'Country': ['USA', 'USA', 'USA', 'USA'],
    'Population': [8623000, 4000000, 2716000, 2302000]
}

df = pd.DataFrame(data)

# Set 'City' as the new index
df.set_index(['City'], inplace=True)

# Print indexed data frame
print(df)

ADVERTISEMENT

我们有:

            Country  Population
City                           
New York        USA     8623000
Los Angeles     USA     4000000
Chicago         USA     2716000
Houston         USA     2302000

请注意,我们之前使用过类似的方法,特别是在“基于整数的索引”段落的末尾。该方法用于重命名索引:我们在开头有数字,然后将它们重命名为字符串。

在最后一种情况下,列已成为数据框的索引。这意味着我们可以loc[]像之前一样过滤它:

# Slice for indexed column
sliced_rows = df.loc['New York':'Chicago']

# Print indexed data frame                   
print(sliced_rows)

结果是:

            Country  Population
City                           
New York        USA     8623000
Los Angeles     USA     4000000
Chicago         USA     2716000

注意:当我们像以前那样对列进行索引时,列名“下降”,这意味着它不再与其他列的名称处于同一级别,正如我们所看到的。在这些情况下,索引列(在本例中为“City”)无法像我们对 Pandas 中的列那样进行访问,直到我们将其恢复为列。

因此,如果我们想恢复经典的索引方法,将索引列恢复为列,我们可以输入以下内容:

# Create a new data frame with restored indexes
df_reset = df.reset_index()

# Print new, restored data frame
print(df_reset)

我们得到:

          City Country  Population
0     New York     USA     8623000
1  Los Angeles     USA     4000000
2      Chicago     USA     2716000
3      Houston     USA     2302000

因此,在本例中,我们创建了一个使用df_reset方法调用的新 DataFrame reset_index(),它已恢复索引,如我们所见。

排序索引

sort_index()Pandas 还使我们能够使用如下方法按降序对索引进行排序(升序是标准顺序) :

import pandas as pd

data = {
    'B': [6, 7, 8, 9, 10],
    'A': [1, 2, 3, 4, 5],
    'C': [11, 12, 13, 14, 15]
}

df = pd.DataFrame(data)

# Sort the DataFrame based on the index in ascending order
df_sorted = df.sort_index(ascending=False)

# Print sorted df
print(df_sorted)

ADVERTISEMENT

这导致:

    B  A   C
4  10  5  15
3   9  4  14
2   8  3  13
1   7  2  12
0   6  1  11

当我们重命名索引或对列建立索引时,甚至可以使用这种方法。例如,假设我们要重命名索引并按降序对它们进行排序:

import pandas as pd

data = {
    'B': [6, 7, 8, 9, 10],
    'A': [1, 2, 3, 4, 5],
    'C': [11, 12, 13, 14, 15]
}

df = pd.DataFrame(data, index=["row 1", "row 2", "row 3", "row 4", "row 5"])

# Sort the data frame based on the index in ascending order
df_sorted = df.sort_index(ascending=False)

# Print sorted df
print(df_sorted)

我们有:

        B  A   C
row 5  10  5  15
row 4   9  4  14
row 3   8  3  13
row 2   7  2  12
row 1   6  1  11

因此,为了达到这个结果,我们使用sort_index()并将参数传递ascending=False给它。

结论

在本文中,我们展示了索引 Pandas 数据帧的不同方法。

有些方法产生的结果与其他方法类似,因此在做出选择时必须牢记我们在操作数据时想要实现的确切结果。



评论已关闭