在 Python 中编写函数时使用 pandas 数据框作为参数

Using a pandas dataframe as an argument when writing function in Python

当我 运行 在我笔记本的单元格中生成一些数据的快速图表时,以下代码工作正常:

def xyz_plot(df=df, sensor='acc', position='t', activity='walking_treadmill_flat', 
        person=np.random.randint(1,9)):
        sensors = [f'{position}_{i}{sensor}' for i in ['x','y','z']]
        subset = df.query(f"person=='{person}' & activity=='{activity}'")
        for j in sensors:
            sns.lineplot(subset.seconds[100:200], subset[f'{j}'][100:200], label=f'{j}', legend='full').set(xlabel='', ylabel='Seconds',                                                      title=f'Person:{person}')
    

但是,当我将其保存在按如下方式导入的 my_functions.py 文件中时,它不再有效并且找不到我的数据框。我该如何解决这个问题?

from my_functions import xyz_plot

调用函数时,将参数传递给它,而不是将其设置为默认参数!

如果您必须使用默认参数,请确保它们是 not mutable

函数声明

def myfunction(arg, arg2=None):
    work_with_arg(arg)

函数调用

from mylibrary import myfunction

...
myfunction(dataframe)  # arg refers to the dataframe in the function

此结构还应该用于防止您的 person 参数出现问题(请参阅有关可变默认参数的注释),因为 随机值只会计算一次 关于导入/函数声明(这可能是需要的,但可能不是..)

>>> import numpy as np
>>> def broken(x=np.random.randint(1,9)):
...     print(x)
...
>>> broken()
7
>>> broken()
7
>>> broken()
7
>>> broken()
7

更合适

>>> def happy(x=None):
...     if x is None:
...         x=np.random.randint(1,9)
...     print(x)
...
>>> happy()
4
>>> happy()
7