Python数据科学:Pandas Cheat Sheet

简介: Python数据科学:Pandas Cheat Sheet

Key and Imports

In this cheat sheet, we use the following shorthand:


df | Any pandas DataFrame object

s | Any pandas Series object


You’ll also need to perform the following imports to get started:


import pandas as pd

import numpy as np


Importing Data

pd.read_csv(filename) | From a CSV file

pd.read_table(filename) | From a delimited text file (like TSV)

pd.read_excel(filename) | From an Excel file

pd.read_sql(query, connection_object) | Read from a SQL table/database

pd.read_json(json_string) | Read from a JSON formatted string, URL or file.

pd.read_html(url) | Parses an html URL, string or file and extracts tables to a list of dataframes

pd.read_clipboard() | Takes the contents of your clipboard and passes it to read_table()

pd.DataFrame(dict) | From a dict, keys for columns names, values for data as lists


Exporting Data

df.to_csv(filename) | Write to a CSV file

df.to_excel(filename) | Write to an Excel file

df.to_sql(table_name, connection_object) | Write to a SQL table

df.to_json(filename) | Write to a file in JSON format


Create Test Objects

Useful for testing code segements


pd.DataFrame(np.random.rand(20,5)) | 5 columns and 20 rows of random floats

pd.Series(my_list) | Create a series from an iterable my_list

df.index = pd.date_range(‘1900/1/30’, periods=df.shape[0]) | Add a date index


Viewing/Inspecting Data

df.head(n) | First n rows of the DataFrame

df.tail(n) | Last n rows of the DataFrame

df.shape() | Number of rows and columns

df.info() | Index, Datatype and Memory information

df.describe() | Summary statistics for numerical columns

s.value_counts(dropna=False) | View unique values and counts

df.apply(pd.Series.value_counts) | Unique values and counts for all columns


Selection

df[col] | Returns column with label col as Series

df[[col1, col2]] | Returns columns as a new DataFrame

s.iloc[0] | Selection by position

s.loc[‘index_one’] | Selection by index

df.iloc[0,:] | First row

df.iloc[0,0] | First element of first column


Data Cleaning

df.columns = [‘a’,’b’,’c’] | Rename columns

pd.isnull() | Checks for null Values, Returns Boolean Arrray

pd.notnull() | Opposite of pd.isnull()

df.dropna() | Drop all rows that contain null values

df.dropna(axis=1) | Drop all columns that contain null values

df.dropna(axis=1,thresh=n) | Drop all rows have have less than n non null values

df.fillna(x) | Replace all null values with x

s.fillna(s.mean()) | Replace all null values with the mean (mean can be replaced with almost any function from the statistics section)

s.astype(float) | Convert the datatype of the series to float

s.replace(1,’one’) | Replace all values equal to 1 with ‘one’

s.replace([1,3],[‘one’,’three’]) | Replace all 1 with ‘one’ and 3 with ‘three’

df.rename(columns=lambda x: x + 1) | Mass renaming of columns

df.rename(columns={‘old_name’: ‘new_ name’}) | Selective renaming

df.set_index(‘column_one’) | Change the index

df.rename(index=lambda x: x + 1) | Mass renaming of index


Filter, Sort, and Groupby

df[df[col] > 0.5] | Rows where the column col is greater than 0.5

df[(df[col] > 0.5) & (df[col] < 0.7)] | Rows where 0.7 > col > 0.5

df.sort_values(col1) | Sort values by col1 in ascending order

df.sort_values(col2,ascending=False) | Sort values by col2 in descending order

df.sort_values([col1,col2],ascending=[True,False]) | Sort values by col1 in ascending order then col2 in descending order

df.groupby(col) | Returns a groupby object for values from one column

df.groupby([col1,col2]) | Returns groupby object for values from multiple columns

df.groupby(col1)[col2] | Returns the mean of the values in col2, grouped by the values in col1 (mean can be replaced with almost any function from the statistics section)

df.pivot_table(index=col1,values=[col2,col3],aggfunc=mean) | Create a pivot table that groups by col1 and calculates the mean of col2 and col3

df.groupby(col1).agg(np.mean) | Find the average across all columns for every unique col1 group

df.apply(np.mean) | Apply the function np.mean() across each column

nf.apply(np.max,axis=1) | Apply the function np.max() across each row


Join/Combine

df1.append(df2) | Add the rows in df1 to the end of df2 (columns should be identical)

pd.concat([df1, df2],axis=1) | Add the columns in df1 to the end of df2 (rows should be identical)

df1.join(df2,on=col1,how=’inner’) | SQL-style join the columns in df1 with the columns on df2 where the rows for col have identical values. how can be one of ‘left’, ‘right’, ‘outer’, ‘inner’


Statistics

These can all be applied to a series as well.


df.describe() | Summary statistics for numerical columns

df.mean() | Returns the mean of all columns

df.corr() | Returns the correlation between columns in a DataFrame

df.count() | Returns the number of non-null values in each DataFrame column

df.max() | Returns the highest value in each column

df.min() | Returns the lowest value in each column

df.median() | Returns the median of each column

df.std() | Returns the standard deviation of each column

相关文章
|
2月前
|
Java 数据处理 索引
(Pandas)Python做数据处理必选框架之一!(二):附带案例分析;刨析DataFrame结构和其属性;学会访问具体元素;判断元素是否存在;元素求和、求标准值、方差、去重、删除、排序...
DataFrame结构 每一列都属于Series类型,不同列之间数据类型可以不一样,但同一列的值类型必须一致。 DataFrame拥有一个总的 idx记录列,该列记录了每一行的索引 在DataFrame中,若列之间的元素个数不匹配,且使用Series填充时,在DataFrame里空值会显示为NaN;当列之间元素个数不匹配,并且不使用Series填充,会报错。在指定了index 属性显示情况下,会按照index的位置进行排序,默认是 [0,1,2,3,...] 从0索引开始正序排序行。
236 0
|
2月前
|
Java 数据挖掘 数据处理
(Pandas)Python做数据处理必选框架之一!(一):介绍Pandas中的两个数据结构;刨析Series:如何访问数据;数据去重、取众数、总和、标准差、方差、平均值等;判断缺失值、获取索引...
Pandas 是一个开源的数据分析和数据处理库,它是基于 Python 编程语言的。 Pandas 提供了易于使用的数据结构和数据分析工具,特别适用于处理结构化数据,如表格型数据(类似于Excel表格)。 Pandas 是数据科学和分析领域中常用的工具之一,它使得用户能够轻松地从各种数据源中导入数据,并对数据进行高效的操作和分析。 Pandas 主要引入了两种新的数据结构:Series 和 DataFrame。
387 0
|
4月前
|
存储 数据采集 数据处理
Pandas与NumPy:Python数据处理的双剑合璧
Pandas与NumPy是Python数据科学的核心工具。NumPy以高效的多维数组支持数值计算,适用于大规模矩阵运算;Pandas则提供灵活的DataFrame结构,擅长处理表格型数据与缺失值。二者在性能与功能上各具优势,协同构建现代数据分析的技术基石。
360 0
|
9月前
|
机器学习/深度学习 数据可视化 TensorFlow
Python 高级编程与实战:深入理解数据科学与机器学习
本文深入探讨了Python在数据科学与机器学习中的应用,介绍了pandas、numpy、matplotlib等数据科学工具,以及scikit-learn、tensorflow、keras等机器学习库。通过实战项目,如数据可视化和鸢尾花数据集分类,帮助读者掌握这些技术。最后提供了进一步学习资源,助力提升Python编程技能。
|
9月前
|
机器学习/深度学习 数据可视化 算法
Python 高级编程与实战:深入理解数据科学与机器学习
在前几篇文章中,我们探讨了 Python 的基础语法、面向对象编程、函数式编程、元编程、性能优化和调试技巧。本文将深入探讨 Python 在数据科学和机器学习中的应用,并通过实战项目帮助你掌握这些技术。
|
10月前
|
Python
python pandas学习(一)
该代码段展示了四个主要操作:1) 删除指定列名,如商品id;2) 使用正则表达式模糊匹配并删除列,例如匹配订单商品名称1的列;3) 将毫秒级时间戳转换为带有时区调整的日期时间格式,并增加8小时以适应本地时区;4) 将列表转换为DataFrame后保存为Excel文件,文件路径和名称根据变量拼接而成。
130 3
|
11月前
|
存储 数据挖掘 数据处理
Python Pandas入门:行与列快速上手与优化技巧
Pandas是Python中强大的数据分析库,广泛应用于数据科学和数据分析领域。本文为初学者介绍Pandas的基本操作,包括安装、创建DataFrame、行与列的操作及优化技巧。通过实例讲解如何选择、添加、删除行与列,并提供链式操作、向量化处理、索引优化等高效使用Pandas的建议,帮助用户在实际工作中更便捷地处理数据。
294 2
|
机器学习/深度学习 数据可视化 数据处理
掌握Python数据科学基础——从数据处理到机器学习
掌握Python数据科学基础——从数据处理到机器学习
209 0
|
机器学习/深度学习 数据采集 数据挖掘
Python在数据科学中的应用:从数据处理到模型训练
Python在数据科学中的应用:从数据处理到模型训练
|
机器学习/深度学习 数据处理 Python
从NumPy到Pandas:轻松转换Python数值库与数据处理利器
从NumPy到Pandas:轻松转换Python数值库与数据处理利器
328 1

推荐镜像

更多