python - 将 pandas 数据框分组并将多个值收集到集合中

标签 python pandas dataframe data-munging

假设我有以下数据框df1:

     A    B  C   D 
0  foo  one  1  0
1  bar  two  2  1
2  foo  two  3  0
3  bar  two  4  1
4  foo  two  5  0
5  bar  two  6  1
6  foo  one  7  0
7  foo  two  8  1

我想将其转换为数据框df2,如下所示:

A     B            C                 D             
foo  [one,two]  [1,3,5,7,8]          0
bar  [two]          [2,4,6]          1

更准确地说:

  • A分组,即A列是索引,每行A的值都是唯一的

  • BC 包含出现的值的聚合集。对于 A = "foo"B"one""two",而对于 >“酒吧”它只是“两个”

    • 从逻辑上讲,这应该是一个集合,其中出现的每个值都只出现一次。它可能是一个 Python set,但我也想问用 pandas 表示它的最优雅的方式是什么
  • D 不包含集合,因为对于 foo D 始终为 0,而对于 bar > 它始终为 1。如果索引值和列值之间始终存在 1:1 关系,则该列不应包含集合。

我预计会有一个像 df1.groupby("A").aggregate_like_this() 这样的单行聚合,但到目前为止我还没有找到它。

最佳答案

使用groupby + agg:

f = {'B' : lambda x: np.unique(x).tolist(), 
     'C' : lambda x: np.unique(x).tolist(), 
     'D' : 'first'
}

df.groupby('A', as_index=False).agg(f).reindex(columns=df.columns)

     A           B                C  D
0  bar       [two]        [2, 4, 6]  1
1  foo  [one, two]  [1, 3, 5, 7, 8]  0 
<小时/>

如果您无法提前确定 A 的哪些值与 D 具有 1:1 关系,请使用 groupby + 进行检查>nunique,然后相应地过滤您的数据集。

x = df.groupby('A').D.nunique().eq(1)
df = df[df.A.isin(x[x].index)]
df

     A    B  C  D
1  bar  two  2  1
3  bar  two  4  1
5  bar  two  6  1

df.groupby('A', as_index=False).agg(f).reindex(columns=df.columns)

     A      B          C  D
0  bar  [two]  [2, 4, 6]  1

关于python - 将 pandas 数据框分组并将多个值收集到集合中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47054318/

相关文章:

python - BS4 : How would I remove unncessary html tags and only keep the <p> and <ruby> tags?

python(pandas)在数据帧内合并,无需for循环

python - ValueError : Number of labels is 1. 使用 silhouette_score 时有效值为 2 到 n_samples - 1(含)

python - 在包含 'X' 的列中,检查并删除包含 'Y' 的行

python - 将包含整数的数据框列转换为日期

python - Thrift:Python 服务器、Erlang 客户端错误... {thrift_socket_server,244,{child_error,function_clause,[]}}

python - 具有 Python 代码完成功能的 Emacs > 代码完成建议未弹出

python - 在文件上打开资源管理器

python - 使用正则表达式在 python 中的数据框或列中的大写字母之前添加空格

Pandas Dataframe 重命名行中的重复值