gpt4 book ai didi

python - 如何在python中将一个函数的变量运行到另一个函数?

转载 作者:行者123 更新时间:2023-12-04 12:14:52 28 4
gpt4 key购买 nike

我是初学者。我有两个功能:
第一个创建数据框和一些打印语句
第二是将数据帧下载到 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

最佳答案

如果它不会改变,直接在类中设置永久变量
只为行动定义乐趣。

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

关于python - 如何在python中将一个函数的变量运行到另一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69330023/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com