【问题标题】:Pandas Dataframe: loop and calculate mean and std over increasing number of columnsPandas Dataframe:循环并计算列数增加的平均值和标准差
【发布时间】:2019-02-28 09:57:01
【问题描述】:

基本上,我有一个包含 20 个属性和一个值的表。我想找到 std = 0 - 所需的最少属性数量(即粒度级别完美允许 1:1 的位置)。

我想设置一个循环如果使用列名硬编码,它看起来像这样:

for iter in range(1,21):
  dfcalc = df.groupby("LINE_NUM")["RATIO"].agg([np.mean, np.std])
  dfcalc = df.groupby("LINE_NUM","TYPE")["RATIO"].agg([np.mean, np.std])

如何在循环中使用 iter 变量来定义我想要分组的列?

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    如果我正确理解你想要什么,你可以这样做:

    for i in range(1, len(df.columns) + 1):
        df.groupby(df.columns[:i].tolist()).agg([np.mean, np.std])
    

    iter 是内置函数的名称)

    您也可以将.iloc 用于integer-based indexing

    【讨论】:

    • 我得到“ValueError: Grouper and axis must be the same length”。另外,它不需要指定它应该表示的列和std:
    • import pandas as pd, numpy as np df = pd.DataFrame(np.array([['A','A', 'C', 7], ['W','C ', 'D', 8], ['W','A', 'C', 9]]),columns=['att1', 'att2', 'att3','ratio']) for i in range(1, len(df.columns) + 1): df.groupby(df.columns[:i]).agg([np.mean, np.std])
    猜你喜欢
    • 1970-01-01
    • 2012-04-20
    • 2014-03-21
    • 2014-09-28
    • 1970-01-01
    • 2016-04-17
    • 2020-09-01
    相关资源
    最近更新 更多