修正方法: nameerror 'pd' が定義されていません


Python の使用時に発生する可能性のある一般的なエラーは次のとおりです。

 NameError : name 'pd' is not defined

このエラーは通常、Python pandasライブラリをインポートするときに、インポート中にpdというエイリアスを付けることができなかった場合に発生します。

次の例は、このエラーが実際にどのように発生するか、およびそれを迅速に修正する方法を示しています。

例 1: import pandas を pd として使用する

次のコードを使用して pandas ライブラリをインポートするとします。

 import pandas

その後、pandas DataFrame を作成しようとすると、次のエラーが発生します。

 #create pandas DataFrame
df = pd. DataFrame ({' points ': [25, 12, 15, 14, 19, 23, 25, 29],
                   ' assists ': [5, 7, 7, 9, 12, 9, 9, 4],
                   ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]})

#attempt to print DataFrame
print (df)

Traceback (most recent call last):
      1 panda import
----> 2 df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
      3 'assists': [5, 7, 7, 9, 12, 9, 9, 4],
      4 'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})
      5 

NameError : name 'pd' is not defined

このエラーを修正するには、パンダをインポートするときにpdのエイリアスを指定する必要があります

 import pandas as pd

#create pandas DataFrame
df = pd. DataFrame ({' points ': [25, 12, 15, 14, 19, 23, 25, 29],
                   ' assists ': [5, 7, 7, 9, 12, 9, 9, 4],
                   ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]})

#printDataFrame
print (df)

   points assists rebounds
0 25 5 11
1 12 7 8
2 15 7 10
3 14 9 6
4 19 12 6
5 23 9 5
6 25 9 9
7 29 4 12

例 2: インポートパンダの使用

次のコードを使用して pandas ライブラリをインポートするとします。

 import pandas

その後、pandas DataFrame を作成しようとすると、次のエラーが発生します。

 #create pandas DataFrame
df = pd. DataFrame ({' points ': [25, 12, 15, 14, 19, 23, 25, 29],
                   ' assists ': [5, 7, 7, 9, 12, 9, 9, 4],
                   ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]})

#attempt to print DataFrame
print (df)

Traceback (most recent call last):
      1 panda import
----> 2 df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
      3 'assists': [5, 7, 7, 9, 12, 9, 9, 4],
      4 'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})
      5 

NameError : name 'pd' is not defined

このエラーを修正するには、 pdエイリアスをまったく使用しないことを選択するだけです。

 import pandas

#create pandas DataFrame
df = pandas. DataFrame ({' points ': [25, 12, 15, 14, 19, 23, 25, 29],
                   ' assists ': [5, 7, 7, 9, 12, 9, 9, 4],
                   ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]})

#printDataFrame
print (df)

   points assists rebounds
0 25 5 11
1 12 7 8
2 15 7 10
3 14 9 6
4 19 12 6
5 23 9 5
6 25 9 9
7 29 4 12

注: 「import pandas as pd」構文は、pandas 関数をより簡潔に使用できるため、一般的に使用されます。毎回「pandas」と入力する代わりに、「pd」と入力するだけで済み、より速く読みやすくなります。

追加リソース

修正方法: pandas という名前のモジュールがありません
修正方法: NameError ‘np’ が定義されていません

コメントを追加する

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