【问题标题】:Printing error with python class attributes, where have I gone wrong?python类属性的打印错误,我哪里出错了?
【发布时间】:2021-03-25 15:05:38
【问题描述】:

我正在尝试打印电子表格中的选定行和列,但是当我调用电子表格数据框属性时,它无法打印名称数据框未定义的状态。我哪里出错了?

import pandas

class spreadsheet:
    def __init__(self, location, dataframe, column, rows):
        self.location = ('Readfrom.xlsx')
        self.dataframe = pandas.read_excel(location)
        self.column = 2
        self.rows = 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 28, 29

a = dataframe.iloc[column,[rows]]

print(a)

【问题讨论】:

    标签: python pandas dataframe class attributes


    【解决方案1】:

    您应该从电子表格类中实例化一个对象,然后访问该实例的属性。您可以了解更多关于 Python 中的面向对象编程here

    我认为您想要在代码中执行的操作类似于下面的代码。

    import pandas
    
    class Spreadsheet:
        def __init__(self, location):
            self.location = location
            self.dataframe = pandas.read_excel(location)
    
    
    sp = Spreadsheet(location="Readfrom.xlsx")
    
    rows = [4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 28, 29]
    
    a = sp.dataframe.iloc[rows, 2]
    
    print(a)
    

    【讨论】:

      【解决方案2】:

      我认为你有缩进问题。

      您的dataframe 是您的spreadsheet 构造方法的参数,您甚至尝试从类外部访问它。

      要访问dataframe 变量,您必须将您的代码a = dataframe.iloc[column,[rows]] 移动到您的__init__ 方法中,或者您需要先创建一个spreadsheet 对象并通过该对象访问它。

      编辑:

      再想一想,我认为您应该了解如何在 Python 中使用类的基础知识。

      1. 你不使用__init__ 的参数,为什么你有它们?
      2. dataframe 只能由电子表格对象访问

      此代码应该可以解决您的问题,但我建议您阅读一些基本教程以了解类和对象的工作原理:

      import pandas
      
      class spreadsheet:
          def __init__(self):
              self.location = ('Readfrom.xlsx')
              self.dataframe = pandas.read_excel(self.location)
              self.column = 2
              self.rows = 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 28, 29
      
      s = spreadsheet()
      a = s.dataframe.iloc[s.column,[s.rows]]
      
      print(a)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-03
        • 2016-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-05
        • 2011-03-14
        相关资源
        最近更新 更多