この記事では、Pythonで空のDataFrameを作成するためのさまざまな方法について説明する予定です。
また、空のDataFrameとNaN値を持つDataFrameの違いについても説明します。
それでは、始めましょう。
Pythonで空のDataFrameとは何ですか?
Pythonでは、DataFrameはPythonのpandasモジュールが提供する2次元のデータ構造で、表形式(行と列)でデータを格納します。
空のDataFrameは、完全に空の(データがない)pandas DataFrameオブジェクトで、すべての軸の長さはゼロです。
また、行数か列数が0でなければなりません。
pandas DataFrameオブジェクトが空かどうかは、pandas DataFrameオブジェクトの DataFrame.empty プロパティを使用して確認することができます。
このプロパティをpandas DataFrameオブジェクトに適用すると、そのDataFrameオブジェクトが空かどうかの条件に応じて、TrueまたはFalseというブール値を返します。
空のデータフレームを作成する方法
Pythonでは、以下の方法で空のpandas DataFrameを作成することができます。
これらを一つずつ理解していきましょう。
1. 行も列もない空のDataFrameを作成する
これは pd.DataFrame() 関数を用いて空の pandas DataFrame オブジェクトを作成する最もシンプルで簡単な方法です。
このメソッドでは、パラメータなしでpandas DataFrameクラスのコンストラクタを呼び出し、空のpandas DataFrameオブジェクトを返します。
このメソッドを実装するためのPythonのコードを見てみましょう。
| # Method-1# Import pandas moduleimportpandas as pd # Create an empty DataFrame without # Any any row or column# Using pd.DataFrame() functiondf1 =pd.DataFrame()print('This is our DataFrame with no row or column:)print(df1)# Check if the above created DataFrame# Is empty or not using the empty propertyprint(')print(df1.empty) | 
結果は以下の通りです。
| This is our DataFrame with no row or column:Empty DataFrameColumns: []Index: []Is this an empty DataFrame?True | 
2. 行だけを含む空のDataFrameを作成する
これは、pd.DataFrame()関数を使用して行だけを含む空のpandas DataFrameオブジェクトを作成するもう一つの簡単な方法です。
このメソッドでは、pandas DataFrameクラスのコンストラクタをindexという1つのパラメータで呼び出し、渡された行またはインデックスリストを持つ空のPandas DataFrameオブジェクトを返します。
このメソッドを実装するための Python コードを書いてみましょう。
| # Method-2# Import pandas moduleimportpandas as pd # Create an empty DataFrame with# Five rows but no columns# Using pd.DataFrame() function with rows parameterdf2 =pd.DataFrame(index =['R1', 'R2', 'R3', 'R4', 'R5'])print('This is our DataFrame with rows only no columns:)print(df2)# Check if the above created DataFrame# Is empty or not using the empty propertyprint(')print(df2.empty) | 
結果は以下の通りです。
| This is our DataFrame with rows only no columns:Empty DataFrameColumns: []Index: [R1, R2, R3, R4, R5]Is this an empty DataFrame?True | 
この記事もチェック:PythonのPandasでブールインデックス参照を実装する方法
3. カラムだけの空の DataFrame を作成する
pd.DataFrame()` 関数を使ってカラムだけを含む空の Pandas DataFrame オブジェクトを作成するには、Pandas DataFrame クラスのコンストラクタに columns という 1 つのパラメータを渡して呼び出し、その結果、渡されたカラムリストを含む空の Pandas DataFrame オブジェクトが返されます。
このメソッドをPythonのコードで実装してみましょう。
| # Method-3# Import pandas moduleimportpandas as pd # Create an empty DataFrame with# Five columns but no rows# Using pd.DataFrame() function with columns parameterdf3 =pd.DataFrame(columns =['C1', 'C2', 'C3', 'C4', 'C5'])print('This is our DataFrame with columns only no rows:)print(df3)# Check if the above created DataFrame# Is empty or not using the empty propertyprint(')print(df3.empty) | 
結果は以下の通りです。
| This is our DataFrame with columns only no rows:Empty DataFrameColumns: [C1, C2, C3, C4, C5]Index: []Is this an empty DataFrame?True | 
この記事もチェック:Pandas DataFrameの単一カラムの名前を変更する
4. 行と列の両方を持つ空のDataFrameを作成する
このメソッドでは、行と列の両方を含む空の Pandas DataFrame オブジェクトを作成します。
列とインデックスという2つのパラメータを指定してpandas DataFrameクラスのコンストラクタを呼び出すと、渡されたインデックスと列のリストを持つ空のpandas DataFrameオブジェクトを返します。
このメソッドをPythonのコードで実装する方法を見てみましょう。
| # Method-4# Import pandas moduleimportpandas as pd # Create an empty DataFrame with# Five rows and five columns# Using pd.DataFrame() function # With columns & index parametersdf4 =pd.DataFrame(columns =['C1', 'C2', 'C3', 'C4', 'C5'],                   index =['R1', 'R2', 'R3', 'R4', 'R5'])print('This is our DataFrame with both rows and columns:)print(df4)# Check if the above created DataFrame# Is empty or not using the empty propertyprint(')print(df4.empty) | 
結果は以下の通りです。
| This is our DataFrame with both rows and columns:     C1   C2   C3   C4   C5R1  NaN  NaN  NaN  NaN  NaNR2  NaN  NaN  NaN  NaN  NaNR3  NaN  NaN  NaN  NaN  NaNR4  NaN  NaN  NaN  NaN  NaNR5  NaN  NaN  NaN  NaN  NaNIs this an empty DataFrame?False | 
注意:このメソッドには一つ問題があり、その出力では empty 属性が False を返しています。
これは、このメソッドで作成したDataFrameが、pandasモジュールによって空のDataFrameとして認識されていないことを意味します。
空のデータフレーム vs NaN値を持つデータフレーム
上記のPythonコードの出力に問題があることがわかりました。
空のDataFrameと全てのNaN値を持つDataFrameは、Pandasモジュールによって異なる扱いを受けます。
これは、このメソッドを使って空のpandas DataFrameを作成しようとすると、DataFrameオブジェクトに何もデータを提供または入力しないのに、デフォルトでNaN値で埋め尽くされるために起こります。
そのため、このような種類のpandas DataFrameに empty 属性を適用すると、Falseが返されます。
そこで、この問題を解決する一つの簡単な方法は、DataFrameにデフォルトで配置されているNaN値をすべて削除することです。
pandas DataFrameクラスの dropna() 関数を使用して、DataFrame内のすべてのNaN値を削除することができます。
そして、DataFrameオブジェクトのemptyプロパティを適用して結果を確認すると、Trueが返されます。
Pythonコードで実装してみましょう。
| # Compare an empty DataFrame# With a DataFrame with all NaN values# Import pandas moduleimportpandas as pd # Create an empty DataFrame with# Three rows and four columns# Using pd.DataFrame() function # With columns & index parametersdf =pd.DataFrame(columns =['Col-1', 'Col-2', 'Col-3', 'Col-4'],                   index =['Row-1', 'Row-2', 'Row-3'])print('This is our DataFrame with NaN values:)print(df)# Check if the above created DataFrame# Is empty or not using the empty propertyprint(')print(df.empty)# Remove all the NaN values using dropna() function# Then apply the empty attribute/property on the DataFrameprint(')print('Is this an empty DataFrame?)print(df.dropna().empty) | 
結果は以下の通りです。
| This is our DataFrame with NaN values:      Col-1 Col-2 Col-3 Col-4Row-1   NaN   NaN   NaN   NaNRow-2   NaN   NaN   NaN   NaNRow-3   NaN   NaN   NaN   NaNIs this an empty DataFrame?FalseAfter removing all the NaN values:Is this an empty DataFrame?True | 
この記事もチェック:Pandasのデータフレームに行を追加する5つの簡単な方法
まとめ
この記事では、空のPandas DataFrameオブジェクトを作成する4つの方法と、空のDataFrameとNaN値を持つDataFrameの違いについて学びました。
この記事では、空のデータフレームを作成する4つの方法と、空のデータフレームとNaN値を持つデータフレームの違いについて説明しました。
このようなエキサイティングなPythonチュートリアルをもっと見るために私たちと一緒にいてください。
この記事もチェック:PythonでPandasデータフレームの列の順序を変更する4つの方法
