如何修复:“pandas”模块没有“dataframe”属性


使用 pandas 时可能遇到的错误是:

 AttributeError : module 'pandas' has no attribute 'dataframe'

此错误通常由以下三个原因之一引起:

1.你写pd.dataframe而不是pd.DataFrame

2.另一个变量命名为“pd”或“pandas”

3.文件名为pd.py或pandas.py

以下示例展示了如何在每种情况下解决此错误。

原因1:使用pd.dataframe

假设我们尝试使用以下语法创建 pandas DataFrame:

 import pandas as pd

#attempt to create DataFrame
df = pd. dataframe ({' points ': [25, 12, 15, 14],
                   ' assists ': [5, 7, 13, 12]})

AttributeError : module 'pandas' has no attribute 'dataframe'

我们收到错误,因为我们以小写形式写入了单词 dataframe。

要创建 pandas DataFrame,您必须以驼峰式大小写形式编写单词“DataFrame”:

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' points ': [25, 12, 15, 14],
                   ' assists ': [5, 7, 13, 12]})

#view DataFrame
df

	assist points
0 25 5
1 12 7
2 15 13
3 14 12

请注意,我们能够成功创建 DataFrame,没有任何错误。

原因 2:另一个变量名为“pd”或“pandas”

如果脚本中的另一个变量名为“pd”或“pandas”,我们也可能会收到此错误:

 import pandas as pd

#create a list named 'pd'
pd = [1, 2, 3, 4]

#attempt to create DataFrame
df = pd. dataframe ({' points ': [25, 12, 15, 14],
                   ' assists ': [5, 7, 13, 12]})

AttributeError : module 'pandas' has no attribute 'dataframe'

要解决此错误,我们只需将当前名为“pd”的变量重命名为其他名称:

 import pandas as pd

#create a list named 'data'
data = [1, 2, 3, 4]

#createDataFrame
df = pd. DataFrame ({' points ': [25, 12, 15, 14],
                   ' assists ': [5, 7, 13, 12]})

#view DataFrame
df

	assist points
0 25 5
1 12 7
2 15 13
3 14 12

请注意,我们没有收到错误,因为我们不再有名为 py 或 pandas 的变量。

原因3.文件名为pd.py或pandas.py

您可能收到错误的另一个原因是脚本的文件名是否为pd.pypandas.py

要解决此错误,您只需将文件重命名为其他名称,例如my_script.pymy_data.py或任何其他名称。

其他资源

以下教程解释了如何修复 Python 中的其他常见错误:

如何修复 Pandas 中的 KeyError
如何修复:ValueError:无法将 float NaN 转换为 int
如何修复:ValueError:操作数无法与形状一起广播

添加评论

您的电子邮箱地址不会被公开。 必填项已用*标注