データサイエンスのためのPandasチートシート Python

Pandas チートシートとは何ですか?
Pandasライブラリには多くの機能がありますが、一部の人にとってはわかりにくいものもあります。ここでは、 Python Pandas チートシート。Pandas の基本をシンプルかつ簡潔に説明します。
Pandas の初心者でも経験豊富でも、このチートシートは便利なリファレンス ガイドとして役立ちます。 シリーズとデータフレームのデータ構造の操作、データの選択と順序付け、データへの関数の適用など、さまざまなトピックをカバーしています。
まとめると、このパンダ Python チートシートは、使用方法について詳しく知りたい人にとって良いリソースです。 Python データサイエンスのための便利なリファレンスツールです。 データ分析スキル パンダをより効率的に操作できます。
Pandas の重要な機能について説明します。
pandas 関数の使用を開始するには、pandas をインストールしてインポートする必要があります。 これを行うには XNUMX つのコマンドがあります。
ステップ 1) # Pandas をインストールする
Pip でパンダをインストールする
ステップ 2) # パンダをインポートする
パンダを pd としてインポートする
これで、Pandas 関数の操作を開始できるようになりました。 データの操作、分析、クリーンアップに取り組みます。 ここではパンダの重要な機能をいくつか紹介します。
パンダのデータ構造
すでに説明したように、Pandas には Series と DataFrame と呼ばれる XNUMX つのデータ構造があります。 どちらもラベル付き配列であり、任意のデータ型を保持できます。 唯一の違いは、Series が XNUMX 次元配列であるのに対し、DataFrame は XNUMX 次元配列であることです。
1.シリーズ
これは XNUMX 次元のラベル付き配列です。 あらゆるデータ型を保持できます。
s = pd.Series([2, -4, 6, 3, None], index=['A', 'B', 'C', 'D', 'E'])
2. データフレーム
これは XNUMX 次元のラベル付き配列です。 あらゆるデータ型とさまざまなサイズの列を保持できます。
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()
データのインポート
パンダには、ノートブックにさまざまな種類のファイルをインポートまたは読み取る機能があります。
以下にいくつかの例を示します。
# 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.シリーズ
# 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. データフレーム
# 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()
データクリーニング
『Brooklyn Galaxy』のために、倪氏はブルックリン美術館のコレクションからXNUMX点の名品を選び、そのイメージを極めて詳細に描き込みました。これらの作品は、彼の作品とともに中国ギャラリーに展示されています。彼はXNUMX年にこの作品の制作を開始しましたが、最初の硬貨には、当館が所蔵する Python データクリーニングのチートシートの目的で、次の操作を実行できます。
- rename() メソッドを使用して列の名前を変更します。
- at[] または iat[] メソッドを使用して値を更新し、特定の要素にアクセスして変更します。
- copy() メソッドを使用して、シリーズまたはデータ フレームのコピーを作成します。
- isnull() メソッドを使用して NULL 値を確認し、dropna() メソッドを使用して NULL 値を削除します。
- duplicad() メソッドを使用して、重複する値をチェックします。 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. 算術 OperaFill メソッドを使用したオプション
# 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 チートシートの結論:
パンダ のオープンソースライブラリです Python データセットを操作するためのものです。 データを分析、クリーニング、探索、操作する機能。 Pandas は Numpy 上に構築されています。 Matplotlib などの他のプログラムと一緒に使用されます。 scikit-Learnデータ構造、データ選択、データのインポート、ブールインデックス、値の削除、並べ替え、データのクリーニングなどのトピックをカバーしています。また、記事用にパンダチートシートのPDFも用意しました。パンダは Python データ サイエンスでは、このライブラリを使用して、pandas のデータフレームとシリーズを操作します。このチートシートでは、さまざまな pandas コマンドについて説明しました。
チートシートのコラボ
私のパンダ用 Colab 演習ファイル – パンダチートシート – Python データサイエンス向け.ipynb

