代码之家  ›  专栏  ›  技术社区  ›  vitamin Cho

如何将pandas函数放在列表中并全部运行?

  •  0
  • vitamin Cho  · 技术社区  · 2 年前
    from itertools import cobminations as combi
    
    # this code doesn't work.
    for func1, func2 in combi([pd.DataFrame.count,pd.DataFrame.min, 
                               pd.DataFrame.max, pd.DataFrame.std, 
                               pd.DataFrame.var, pd.DataFrame.mean]):
       x = df.col1.func1()
       y = df.col1.func2()
       ax = fig.add_subplot(8, 2, counter)
       ax.scatter(x,y)
    

    这段代码不起作用,因为func1&func2不是调用函数的正确名称。 如何在pandas函数列表中循环?那怎么称呼呢?

    2 回复  |  直到 2 年前
        1
  •  2
  •   chthonicdaemon    2 年前

    import pandas as pd
    from itertools import combinations
    
    for func1, func2 in combinations([pd.DataFrame.count,pd.DataFrame.min, 
                               pd.DataFrame.max, pd.DataFrame.std, 
                               pd.DataFrame.var, pd.DataFrame.mean], 2):
        x = func1(df).col1
        y = func2(df).col1
    

    但也有一些问题:我们多次重新计算这些内容,在这种方法中,如果df中有许多列,那么函数也将应用于这些列。所以你也可以使用 pd.Series 函数的版本并通过列,如下所示:

    for func1, func2 in combinations([pd.Series.count,pd.Series.min, 
                               pd.Series.max, pd.Series.std, 
                               pd.Series.var, pd.Series.mean], 2):
        x = func1(df.col1)
        y = func2(df.col1)
    

    .agg :

    aggs = df.col1.agg(['count', 'min', 'max', 'std', 'var', 'mean'])
    

    for func1, func2 in combinations(aggs.index, 2):
        x = aggs[func1]
        y = aggs[func2]
    
        2
  •  0
  •   lucas galdino    2 年前

    为什么不列出函数结果?比如,你可以做一个嵌套函数,从numpy/pandas中应用你想要的所有函数,并赋值。从这些值中创建一个列表,并分配另一个列表/元组/字典。我推荐字典,它们更容易使用,尤其是熊猫。

    而且我认为你不能像你尝试的那样迭代。您的函数缺少函数末尾的“()”,这不是for循环中列表的工作方式。