首页 > 解决方案 > 返回 2 个或更多 dfs 的函数 - 如何在 main() 函数中调用它?

问题描述

我有一系列函数,然后我想在 main() 函数中调用它们。我已经能够做到这一点,除了我不确定如何处理返回两个或更多数据帧的函数。你如何在 main() 函数中调用这个函数?谢谢您的帮助!

我的猜测是这样的:

df, df2 = operation_one(df, df2)
import pandas as pd
import numpy as np


def loader():

    df = pd.read_excel('file_example.xlsx')
    return df


def clean_data(df):

    del df['column_7']
    return df


def operation_one(df):

    del df['column_12']

    df2 = pd.DataFrame({'Color': ['Blue', 'Yellow'], 'Size': ['big', 'small']})
    
    return df, df2


def main():

    df = loader()
    df = clean_data(df)
    df = operation_one(df)

    df, df2 = operation_one(df, df2)

    with pd.ExcelWriter("file.xlsx") as writer:
        df.to_excel(writer, sheet_name='first' , index=False)
        df2.to_excel(writer, sheet_name='second' , index=False)

if __name__ == "__main__":
    main()

标签: pythonpandasfunctiondataframe

解决方案


问题不在于分配返回值,而在于传递给函数的参数 df2 从未分配过。我假设更远的“df =”分配之一应该是“df2 =”。


推荐阅读