用于 Python 数据科学的 Pandas 速查表

Pandas Cheat Sheet

什么是 Pandas 备忘录?

Pandas 库有很多函数,但其中一些可能让一些人感到困惑。我们在这里提供了一个有用的资源,称为 Python Pandas 备忘录。它以简单明了的方式解释了 Pandas 的基础知识。

无论您是 Pandas 的新手还是经验丰富的用户,此备忘录都可以作为有用的参考指南。它涵盖了各种主题,包括使用 Series 和 DataFrame 数据结构,选择和排序数据,以及将函数应用于您的数据。

总之,这份 Pandas Python 备忘录是任何希望更多地了解如何使用 Python 进行数据科学的人的绝佳资源。它是一个便捷的参考工具。它可以帮助您提高数据分析技能并更有效地使用 Pandas。

👉 在此处下载备忘录的 PDF

解释 Pandas 中的重要函数

要开始使用 pandas 函数,您需要安装并导入 pandas。可以使用以下两个命令执行此操作:

步骤 1)# 安装 Pandas

Pip install pandas

步骤 2)# 导入 Pandas

Import pandas as pd

现在,您可以开始使用 Pandas 函数了。我们将进行数据操作、分析和清理。以下是一些重要的 pandas 函数。

Pandas 数据结构

正如我们已经讨论过的,Pandas 有两个数据结构,称为 Series 和 DataFrames。它们都是带标签的数组,可以容纳任何数据类型。唯一的区别是 Series 是一维数组,而 DataFrame 是二维数组。

1. Series

它是一维带标签的数组。它可以容纳任何数据类型。

s = pd.Series([2, -4, 6, 3, None], index=['A', 'B', 'C', 'D', 'E'])

2. DataFrame

它是一个二维带标签的数组。它可以容纳任何数据类型和不同大小的列。

data = {'RollNo' : [101, 102, 75, 99],
        'Name' : ['Mithlesh', 'Ram', 'Rudra', 'Mithlesh'],
        'Course' : ['Nodejs', None, 'Nodejs', 'JavaScript']
}
df = pd.DataFrame(data, columns=['RollNo', 'Name', 'Course'])
df.head()

Pandas Cheat Sheet

导入数据

Pandas 能够将各种类型的文件导入或读取到您的 Notebook 中。

以下是一些示例。

# Import a CSV file pd
pd.read_csv(filename)

# Import a TSV file
pd.read_table(filename)

# Import a Excel file pd
pd.read_excel(filename)

# Import a SQL table/database
pd.read_sql(query, connection_object)

# Import a JSON file
pd.read_json(json_string)

# Import a HTML file
pd.read_html(url)

# From clipboard to read_table()
pd.read_clipboard()

# From dict
pd.DataFrame(dict)

选择

您可以通过其位置或索引选择元素。您可以使用这些技术来选择行、列和不同的值。

1. Series

# Accessing one element from Series
s['D']

# Accessing all elements between two given indices
s['A':'C']

# Accessing all elements from starting till given index
s[:'C']

# Accessing all elements from given index till end
s['B':]

2. DataFrame

# Accessing one column df
df['Name']

# Accessing rows from after given row
df[1:]

# Accessing till before given row
df[:1]

# Accessing rows between two given rows
df[1:2]

通过布尔索引和设置进行选择

1. 按位置

df.iloc[0, 1]

df.iat[0, 1]

2. 按标签

df.loc[[0],  ['Name']]

3. 按标签/位置

df.loc[2] # Both are same
df.iloc[2]

4. 布尔索引

# Series s where value is > 1
s[(s > 0)]

# Series s where value is <-2 or >1
s[(s < -2) | ~(s > 1)]

# Use filter to adjust DataFrame
df[df['RollNo']>100]

# Set index a of Series s to 6
s['D'] = 10
s.head()

数据清理

为了方便 Python 数据清理备忘录,您可以执行以下操作:

  • 使用 rename() 方法重命名列。
  • 使用 at[] 或 iat[] 方法更新值以访问和修改特定元素。
  • 使用 copy() 方法创建 Series 或 DataFrame 的副本。
  • 使用 isnull() 方法检查 NULL 值,并使用 dropna() 方法删除它们。
  • 使用 duplicated() 方法检查重复值。使用 drop_duplicates() 方法删除它们。
  • 使用 fill() 方法将 NULL 值替换为指定值。
  • 使用 replace() 方法替换值。
  • 使用 sort_values() 方法对值进行排序。
  • 使用 rank() 方法对值进行排名。
# Renaming columns
df.columns = ['a','b','c']
df.head()

# Mass renaming of columns
df = df.rename(columns={'RollNo': 'ID', 'Name': 'Student_Name'})

# Or use this edit in same DataFrame instead of in copy
df.rename(columns={'RollNo': 'ID', 'Name': 'Student_Name'}, inplace=True)
df.head()

# Counting duplicates in a column
df.duplicated(subset='Name')

# Removing entire row that has duplicate in given column
df.drop_duplicates(subset=['Name'])

# You can choose which one keep - by default is first
df.drop_duplicates(subset=['Name'], keep='last')

# Checks for Null Values
s.isnull()

# Checks for non-Null Values - reverse of isnull()
s.notnull()

# Checks for Null Values df
df.isnull()

# Checks for non-Null Values - reverse of isnull()
df.notnull()

# Drops all rows that contain null values
df.dropna()

# Drops all columns that contain null values
df.dropna(axis=1)

# Replaces all null values with 'Guru99'
df.fillna('Guru99')

# Replaces all null values with the mean
s.fillna(s.mean())

# Converts the datatype of the Series to float
s.astype(float)

# Replaces all values equal to 6 with 'Six'
s.replace(6,'Six')

# Replaces all 2 with 'Two' and 6 with 'Six'
s.replace([2,6],['Two','Six'])

# Drop from rows (axis=0)
s.drop(['B',  'D'])

# Drop from columns(axis=1)
df.drop('Name', axis=1)

# Sort by labels with axis
df.sort_index()

# Sort by values with axis
df.sort_values(by='RollNo')

# Ranking entries
df.rank()

# s1 is pointing to same Series as s
s1 = s

# s_copy of s, but not pointing same Series
s_copy = s.copy()

# df1 is pointing to same DataFrame as df
df1 = s

# df_copy of df, but not pointing same DataFrame
df_copy = df.copy()

检索信息

您可以执行这些操作来检索信息:

  • 使用 shape 属性获取行数和列数。
  • 使用 head() 或 tail() 方法获取前几行或后几行作为样本。
  • 使用 info()、describe() 或 dtypes 方法获取有关数据类型、计数、平均值、标准差、最小值和最大值的信息。
  • 使用 count()、min()、max()、sum()、mean() 和 median() 方法获取值的特定统计信息。
  • 使用 loc[] 方法获取一行。
  • 使用 groupby() 方法将 GROUP BY 函数应用于 DataFrame 列中相似值的分组。

1. 基本信息

# Counting all elements in Series
len(s)

# Counting all elements in DataFrame
len(df)

# Prints number of rows and columns in dataframe
df.shape

# Prints first 10 rows by default, if no value set
df.head(10)

# Prints last 10 rows by default, if no value set
df.tail(10)

# For counting non-Null values column-wise
df.count()

# For range of index df
df.index

# For name of attributes/columns
df.columns

# Index, Data Type and Memory information
df.info()

# Datatypes of each column
df.dtypes

# Summary statistics for numerical columns
df.describe()

2. 摘要

# For adding all values column-wise
df.sum()

# For min column-wise
df.min()

# For max column-wise
df.max()

# For mean value in number column
df.mean()

# For median value in number column
df.median()

# Count non-Null values
s.count()

# Count non-Null values
df.count()

# Return Series of given column
df['Name'].tolist()

# Name of columns
df.columns.tolist()

# Creating subset
df[['Name', 'Course']]

# Return number of values in each group
df.groupby('Name').count()

应用函数

# Define function
f = lambda x: x*5

# Apply this function on given Series - For each value
s.apply(f)

# Apply this function on given DataFrame - For each value
df.apply(f)

1. 内部数据对齐

# NA values for indices that don't overlap
s2 = pd.Series([8, -1, 4],  index=['A',  'C',  'D'])
s + s2

2. 带有填充方法的算术运算

# Fill values that don't overlap
s.add(s2, fill_value=0)

3. 过滤、排序和分组

以下函数可用于过滤、排序和分组 Series 和 DataFrame。

# Filter rows where column is greater than 100
df[df['RollNo']>100]

# Filter rows where 70 < column < 101
df[(df['RollNo'] > 70) & (df['RollNo'] < 101)]

# Sorts values in ascending order
s.sort_values()

# Sorts values in descending order
s.sort_values(ascending=False)

# Sorts values by RollNo in ascending order
df.sort_values('RollNo')

# Sorts values by RollNo in descending order
df.sort_values('RollNo', ascending=False)

导出数据

Pandas 能够以各种格式导出或写入数据。以下是一些示例。

# Export as a CSV file df
df.to_csv(filename)

# Export as a Excel file df
df.to_excel(filename)

# Export as a SQL table df
df.to_sql(table_name, connection_object)

# Export as a JSON file
df.to_json(filename)

# Export as a HTML table
df.to_html(filename)

# Write to the clipboard
df.to_clipboard()

Pandas 备忘录总结

Pandas 是一个开源库,用于在 Python 中处理数据集。它能够分析、清理、探索和操作数据。Pandas 构建在 Numpy 之上。它与其他程序一起使用,例如 Matplotlib 和 Scikit-Learn。它涵盖了数据结构、数据选择、数据导入、布尔索引、删除值、排序和数据清理等主题。我们还为本文准备了 pandas 备忘录 PDF。Pandas 是 Python 中的一个库,数据科学使用这个库来处理 pandas 数据帧和系列。我们在本备忘录中讨论了各种 pandas 命令。

备忘录 Colab

我的 Pandas Colab 练习文件 – Pandas 备忘录 – Python 数据科学.ipynb