【问题标题】:Pandas update column with array熊猫用数组更新列
【发布时间】:2017-07-19 16:02:12
【问题描述】:

所以,我正在学习 pandas,我遇到了这个问题。

假设我有一个这样的数据框:

A B C
1 x NaN
2 y NaN
3 x NaN
4 x NaN
5 y NaN

我正在尝试创建这个:

A B C
1 x [1,3,4]
2 y [2,5]
3 x [1,3,4]
4 x [1,3,4]
5 y [2,5]

基于 B 相似性。

我这样做了:

teste = df.groupby(['B'])
for name,group in teste:
    df.loc[df['B'] == name[0],'C'] = group['A'].tolist()

我得到了这个。就像C列是基于A列的。

A B C
1 x 1
2 y 2
3 x 3
4 x 4
5 y 5

任何人都可以向我解释为什么会发生这种情况以及按照我想要的方式执行此操作的解决方案吗? 谢谢:)

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    您可以先根据列B进行聚合,然后在B上加入原始df:

    df
    #   A   B
    #0  1   x
    #1  2   y
    #2  3   x
    #3  4   x
    #4  5   y
    
    df.groupby('B').A.apply(list).rename('C').reset_index().merge(df)
    
    #   B           C   A
    #0  x   [1, 3, 4]   1
    #1  x   [1, 3, 4]   3
    #2  x   [1, 3, 4]   4
    #3  y      [2, 5]   2
    #4  y      [2, 5]   5
    

    【讨论】:

    • 运行它会产生错误:TypeError: unhashable type: 'list'
    • @E.Ducateme 您需要删除C 列并尝试此操作。
    • 实际上,这代替了我标记为答案的其他解决方案:)
    • 只有一个问题(因为我是 pandas 的新手):你为什么放 reset_index()?
    • 使用groupby('B')时,将B列设置为索引,reset_index将其转换为普通列。
    【解决方案2】:

    您可以使用transform 创建列表。

    In [324]: df['C'] = df.groupby('B')['A'].transform(lambda x: [x.values])
    
    In [325]: df
    Out[325]:
       A  B          C
    0  1  x  [1, 3, 4]
    1  2  y     [2, 5]
    2  3  x  [1, 3, 4]
    3  4  x  [1, 3, 4]
    4  5  y     [2, 5]
    

    【讨论】:

    • 成功了!非常感谢! :)
    【解决方案3】:

    求和创意!
    制作A 单值列表。然后使用sum 进行转换。

    df.assign(
        C=pd.Series(
            df.A.values[:, None].tolist(), df.index
        ).groupby(df.B).transform('sum')
    )
    
       A  B          C
    0  1  x  [1, 3, 4]
    1  2  y     [2, 5]
    2  3  x  [1, 3, 4]
    3  4  x  [1, 3, 4]
    4  5  y     [2, 5]
    

    【讨论】:

      【解决方案4】:
      test = df.groupby('B')['A'].apply(list)
      

      【讨论】:

        猜你喜欢
        • 2019-04-21
        • 2018-12-29
        • 2019-07-28
        • 2018-02-01
        • 2016-03-26
        • 2015-10-23
        • 2017-02-21
        • 2022-01-26
        相关资源
        最近更新 更多