【问题标题】:how to pass object to a function in python如何将对象传递给python中的函数
【发布时间】:2020-02-03 14:28:10
【问题描述】:

我在 python 中创建了一个类:

class dataframe():
    #    
    # Initializer / Instance Attributes
    def __init__(self, fcsv, colp, label,DataFrame):

        label = r'\textbf{' + label +'}'

        self.fcsv  = fcsv  
        self.colp  = colp
        self.label = label
        self.dfr   = pd.DataFrame()

如您所见,每个对象都是具有某些特征的数据框。

因此,在主代码中,我将以下对象列表创建为:

DFC =[]
DFC.append(dataframe('econ_real' ,'r','real price'       ,pd.DataFrame))
DFC.append(dataframe('autoarimax','b','autoarimax model' ,pd.DataFrame))
DFC.append(dataframe('benchmark' ,'g','benchmark model'  ,pd.DataFrame))

我想将其中一些作为参数传递给函数。

我尝试过类似 taht 的方法:

sp='2017-03-01 00:00:00'
ep='2017-05-01 00:00:00'
plot_hh(DFC[:].dfr[sp:ep,'A'])

基本上,我想传递数据框及其特征以及它们的一些行和列,即我想打印的那些。

不幸的是,这似乎不起作用。事实上,情节子例程给了我一个无效的语法错误,情节子例程是:

def plot_hh(DFC[:].dfr):

  print('hello')

这是我填写数据框的方法:

for idf in range(0,3):
  DFC[idf].dfr = pd.read_csv(fname, sep=';',index_col=0, header = 0)

我试图研究函数和参数,但我无法解决这个问题。

感谢您的任何帮助。 最好的问候

【问题讨论】:

  • 您没有使用DataFrame 参数到__init__;你可以摆脱它。事实上,这可能是继承合适的情况; dataframe 可以是 pd.DataFrame 的子类。
  • def __init__(self, fcsv, colp, label,DataFrame): 您正在使用DataFrame 的变量名(这很糟糕,因为它可能会隐藏类名,可能使用dfr 作为变量/参数名。但随后在正文中您所做的 init self.dfr = pd.DataFrame() 基本上忽略了传递给类的数据帧,并将 self.dfr 设置为一个新的空数据帧。
  • 亲爱的@TomDalton,感谢您的建议。我已将 self.dfr = pd.DataFrame() 相应地更改为 self.dfr = dfr。我已经添加了填充数据框的部分。
  • @chepner。我没有使用它,但我会使用它。因此,我无法摆脱数据框

标签: python function dataframe object arguments


【解决方案1】:

您的绘图例程中的语法无效,请尝试更改:

def plot_hh(DFC[:].dfr):
  print('hello')

收件人:

def plot_hh(df):
  print('hello')
  print(df)

【讨论】:

  • 感谢您的建议。它似乎不起作用。我已经完成了以下操作:plot_hh(DFC[:]) 和 def plot_hh(DFC):基本上,我传递了所有对象
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-07
  • 2011-01-09
  • 2021-11-26
  • 1970-01-01
  • 2022-12-05
  • 1970-01-01
相关资源
最近更新 更多