代码之家  ›  专栏  ›  技术社区  ›  Kamikaze_goldfish

python pandas的“head”属性不起作用

  •  0
  • Kamikaze_goldfish  · 技术社区  · 7 年前

    我正在做一个快速脚本,与python和pandas一起使用一些数据,但是,我正在尝试打印 'head' 但当我这样做的时候,我会得到一个错误。有什么问题吗?

    AttributeError: 'collections.OrderedDict' object has no attribute 'head'

    import pandas as pd
    my_file_location = "whatever.xlsx"
    dfs = pd.read_excel(my_file_location, sheet_name=None)
    
    print(dfs.head())
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   Craig    7 年前

    您正在加载包含多个工作表的工作簿,并通过 sheet_name = None pd.read_excel() 它告诉它加载工作簿中的所有工作表并将它们作为字典返回。从字典中选择一张工作表,或将工作表的名称传递给 Read Excel() .

    例如,要显示所有工作表:

    import pandas as pd
    my_file_location = "whatever.xlsx"
    dfs = pd.read_excel(my_file_location, sheet_name=None)
    for n,d in dfs.items():
      print('Sheet Name:{}'.format(n))
      print(d.head())
    

    或选择名为“somename”的工作表:

    import pandas as pd
    my_file_location = "whatever.xlsx"
    dfs = pd.read_excel(my_file_location, sheet_name='somename')
    print(d.head())
    

    更多选项在 documentation for pandas.read_excel()

        2
  •  0
  •   U13-Forward    7 年前

    缩短克雷格的解决方案:

    import pandas as pd
    my_file_location = "whatever.xlsx"
    dfs = pd.read_excel(my_file_location, sheet_name=None)
    [(print('Sheet Name:{}'.format(n)),print(d.head())) for n,d in dfs.items()]
    

    使用 print 在列表理解中。

    您的代码的问题在于 dfs 是一个对象的序列 head 属性:(有趣的解释方式)

    如果您的工作表只包含一张工作表:

    ...
    print(dfs[0].head())