【问题标题】:Create a column of list from another column and display only unique values in pandas dataframe从另一列创建一列列表并仅在熊猫数据框中显示唯一值
【发布时间】:2021-08-27 05:34:50
【问题描述】:

我是 pandas 的新手,我正在尝试使用 group by 并在新列中创建一个列表。 我的数据框中有 3 列,我创建了第 4 列(New_List)来从另一列创建列表,如下所示:使用以下代码:

new_df = df.join(pd.Series(df.groupby(by='NO_ACCOUNTS').apply(lambda x: list(x.Bucket)), name="list_of_b"), on='NO_ACCOUNTS')

Account_Number   Bucket  Number_Transactions     New_List
   ABA            APP          155                 [APP]
   ABC            APP          1352                [APP]
   AAA            APP          90                  [API,APP]
   AAA            API          5                   [API,APP]

我希望通过 3 列获得所需的输出:

Account_Number     Number_Transactions     New_List
   ABA                      155                 [APP]
   ABC                      1352                [APP]
   AAA                      95                  [API,APP]

【问题讨论】:

    标签: python pandas list dataframe pandas-groupby


    【解决方案1】:

    您可以aggregate 这两列:

    out = (df.groupby("Account_Number", sort=False, as_index=False)
             .agg(Number_Transactions=("Number_Transactions", "sum"),
                  New_List=("Bucket", list)))
    

    首先按Account_Number 分组,同时用sort=False 保持顺序,而不用as_index=False 使其索引,然后用求和聚合Number_Transactions 列并将其指定给同名列,类似地,aggs带有listBucket 列并将其分配给输出中的New_List 列,

    得到

    >>> out
    
      Account_Number  Number_Transactions    New_List
    0            ABA                  155       [APP]
    1            ABC                 1352       [APP]
    2            AAA                   95  [APP, API]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-01
      • 2021-06-25
      • 1970-01-01
      • 1970-01-01
      • 2022-12-06
      • 1970-01-01
      • 1970-01-01
      • 2020-12-27
      相关资源
      最近更新 更多