【问题标题】:How to build a statement to perform a groupby operation during runtime on a Pandas DataFrame?如何在运行时在 Pandas DataFrame 上构建语句以执行 groupby 操作?
【发布时间】:2021-03-12 18:33:04
【问题描述】:

我有一个 Pandas DataFrame dfs 和一个列表 headers

列表headers 在运行时被分配DataFrame dfs 的列名。

例如,让我们考虑为列表分配dfs 的列名:

["Information_type", "Interface", "Type_of_Interface", "Connection_Mechanism"]

我想对 DataFrame dfs 执行下面的 groupbyagg 操作 没有明确提及 groupby 操作中的列名,即"Information_type": " ".join"Interface": " ".join"Type_of_Interface": " ".join"Connection_Mechanism": " ".join

dfs[0]=dfs[0].groupby("grp").agg({"Information_type": " ".join, "Interface": " ".join, "Type_of_Interface": " ".join, "Connection_Mechanism": " ".join})

基本上在运行时将"Information_type": " ".join , "Interface": " ".join , "Type_of_Interface": " ".join , "Connection_Mechanism": " ".join写入上述行。

如果这样的事情是可能的,那就太好了,否则我将不得不手动编辑列名并为每个表执行groupbyagg操作!

感谢您的帮助。提前致谢!

【问题讨论】:

    标签: python pandas dataframe dynamic-programming


    【解决方案1】:

    IIUC 这就是你想要的:

    #setup
    df = pd.DataFrame({'a':np.random.randint(0,5,25),
                       'b':np.random.randint(0,5,25),
                       'c':np.random.randint(0,5,25), 
                       'd':np.random.randint(0,5,25)}, dtype = str)
    
    cols = ['b','c']
    
    df.groupby('a').agg({col: " ".join for col in cols})
    

    输出

                   b              c
    a                              
    0  0 0 3 3 4 2 3  3 3 4 0 4 3 2
    1      2 4 1 2 1      3 0 2 1 3
    2        0 0 4 2        1 3 1 3
    3    2 2 4 1 3 0    3 1 1 1 2 0
    4          4 2 0          2 0 3
    

    【讨论】:

      猜你喜欢
      • 2019-01-21
      • 2014-06-28
      • 1970-01-01
      • 2015-10-15
      • 1970-01-01
      • 2018-02-01
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多