【问题标题】:How to run variable of one function to another in python?如何在python中将一个函数的变量运行到另一个函数?
【发布时间】:2021-11-18 14:58:45
【问题描述】:

我是初学者。我有两个功能: 第一次创建数据框和一些打印语句 第二个是将数据帧下载到 colab 中的 csv。

我想通过 df_name 下载所有数据帧。 代码:

def fun1():
  import pandas as pd
  d = {'col1': [1, 2], 'col2': [3, 4]}
  d2 = {'col1': [-5, -6], 'col2': [-7, -8]}
  df = pd.DataFrame(data=d)
  df2 = pd.DataFrame(data=d2)
  print('info', df.info())
  print('info', df2.info())
  return df, df2
def fun2(df):
  from google.colab import files
  name1 = 'positive.csv'
  name2 = 'negative.csv'
  df.to_csv(name1)
  df2.to_csv(name2)
  files.download(name1)
  files.download(name2)
fun2(df) #looking something like this that download my df, func2 should read my df and df2 from fun1() 

我试过了:

class tom:
  def fun1(self):
    import pandas as pd
    d = {'col1': [1, 2], 'col2': [3, 4]}
    d2 = {'col1': [-5, -6], 'col2': [-7, -8]}
    df = pd.DataFrame(data=d)
    df2 = pd.DataFrame(data=d2)
    print('info', df.info())
    print('info', df2.info())
    self.df= df
    self.df2 = df2
    
    return df, df2
 
  def fun2(self):
    df,df2 = fun1()
    from google.colab import files
    name1 = 'positive.csv'
    name2 = 'negative.csv'
    df.to_csv(name1)
    df2.to_csv(name2)
    return files.download(name1) ,files.download(name2)
tom().fun2() #it download files but shows print of fun1 as well which I don't want. 

寻找类似的东西

tom().fun2(dataframe_name) #it just download the files nothing else

【问题讨论】:

  • "显示 fun1 的打印以及我不想要的" - 您应该在 fun1 中编写额外的代码,让调用者决定是否打印任何内容。现在这个函数总是会打印东西,而调用者基本上无法控制这个(你可以将stdout重定向到某个地方,但这不值得麻烦)
  • 将参数添加到fun1,如print_info=True 然后在fun2 中调用fun1 时包含参数值,如print_info=False?或者在某些情况下解决仅打印信息问题的许多其他方法
  • 在 fun2() 中还有其他方法可以从 fun1() 中读取 df1 和 df2 吗?

标签: python function oop google-colaboratory user-defined-functions


【解决方案1】:

也许您可以将所需的数据保存在类变量中或创建另一个函数,将第一个函数的数据保留为您需要的值(我们称之为 A),然后将 A 作为参数传递给第二个函数。

【讨论】:

  • 你能在课堂上写吗
【解决方案2】:

如果它不会改变,直接在类中设置永久变量

为行动定义乐趣。

class s:
  import pandas as pd
  
  d = {'col1': [1, 2], 'col2': [3, 4]}
  d2 = {'col1': [-5, -6], 'col2': [-7, -8]}
  df = pd.DataFrame(data=d)
  df2 = pd.DataFrame(data=d2)


  name1 = 'positive.csv'
  name2 = 'negative.csv'
  df.to_csv(name1)
  df2.to_csv(name2)
  def f():
    print('info', df.info())
    print('info', df2.info())
  
  def fun(x):
    from google.colab import files
    return files.download(x)

运行

s.f() --it will print value only
s.fun(s.name1) --it will just download the file

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-23
    • 2015-11-21
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多