後で使用できるように pandas dataframe を保存する方法 (例あり)


多くの場合、CSV ファイルからデータを再インポートせずに、後で使用できるようにパンダ データフレームを保存したい場合があります。

これを行う最も簡単な方法は、 to_pickle()を使用して DataFrame を pickle ファイルとして保存することです。

 df. to_pickle (" my_data.pkl ")

これにより、現在の作業環境に DataFrame が保存されます。

次に、 read_pickle()を使用して、pickle ファイルから DataFrame をすばやく読み取ることができます。

 df = pd. read_pickle (" my_data.pkl ")

次の例は、これらの関数を実際に使用する方法を示しています。

例: Pandas DataFrame を保存してロードする

さまざまなバスケットボール チームに関する情報を含む次のパンダ データフレームを作成するとします。

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' team ': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                   ' points ': [18, 22, 19, 14, 14, 11, 20, 28],
                   ' assists ': [5, 7, 7, 9, 12, 9, 9, 4],
                   ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
print (df)

  team points assists rebounds
0 A 18 5 11
1 B 22 7 8
2 C 19 7 10
3 D 14 9 6
4 E 14 12 6
5 F 11 9 5
6 G 20 9 9
7:28 4 12

df.info()を使用して、DataFrame 内の各変数のデータ型を表示できます。

 #view DataFrame info
print ( df.info ())

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 8 entries, 0 to 7
Data columns (total 4 columns):
 # Column Non-Null Count Dtype 
--- ------ -------------- ----- 
 0 team 8 non-null object
 1 point 8 non-null int64 
 2 assists 8 non-null int64 
 3 rebounds 8 non-null int64 
dtypes: int64(3), object(1)
memory usage: 292.0+ bytes
None

to_pickle()関数を使用して、この DataFrame を.pkl拡張子の付いた pickle ファイルに保存できます。

 #save DataFrame to pickle file
df. to_pickle (" my_data.pkl ")

DataFrame は、現在の作業環境で pickle ファイルとして保存されます。

次に、 read_pickle()関数を使用して DataFrame をすばやく読み取ることができます。

 #read DataFrame from pickle file
df=pd. read_pickle (" my_data.pkl ")

#view DataFrame
print (df)

team points assists rebounds
0 A 18 5 11
1 B 22 7 8
2 C 19 7 10
3 D 14 9 6
4 E 14 12 6
5 F 11 9 5
6 G 20 9 9
7:28 4 12

再度df.info()を使用して、各列のデータ型が前と同じであることを確認できます。

 #view DataFrame info
print ( df.info ())

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 8 entries, 0 to 7
Data columns (total 4 columns):
 # Column Non-Null Count Dtype 
--- ------ -------------- ----- 
 0 team 8 non-null object
 1 point 8 non-null int64 
 2 assists 8 non-null int64 
 3 rebounds 8 non-null int64 
dtypes: int64(3), object(1)
memory usage: 292.0+ bytes
None

pickle ファイルを使用する利点は、DataFrame を保存およびロードするときに各列のデータ型が保持されることです。

これには、pickle ファイルが DataFrame の元の状態を保持するため、DataFrame で変換を実行する必要がないため、CSV ファイルの保存およびロードよりも利点があります。

追加リソース

次のチュートリアルでは、Python の他の一般的なエラーを修正する方法を説明します。

パンダの KeyError を修正する方法
修正方法: ValueError: float NaN を int に変換できません
修正方法: ValueError: オペランドをシェイプでブロードキャストできませんでした

コメントを追加する

メールアドレスが公開されることはありません。 が付いている欄は必須項目です