【问题标题】:Taking the unique values to a dataframe Pandas Python将唯一值放入数据框 Pandas Python
【发布时间】:2021-12-13 09:23:10
【问题描述】:

我有一个以下格式的数据框。

Col1 Col2
123 abc
123 xyz
111 abc
456 abc
456 xyz
456 pqr

我想从上述数据集中导出如下数据框。

abc xyz pqr abc, xyz abc, xyz, pqr
111 123 456

这更像是一个组合问题,但在 Pandas 中,

【问题讨论】:

  • Col1abc 中是否有另一行有112,在Col2 中没有其他行有112Col1 中?
  • 顺便说一句:你有没有赞成和/或接受你得到的任何答案?可能有助于激励用户帮助您。

标签: python pandas combinations


【解决方案1】:

IIUC,您可以首先在 Col1 上使用 groupby,将 Col2 的所有元素连接起来,然后在结果转换上创建 pivot_table,将 Col2 元素作为列:

out = df.groupby('Col1',as_index=False)\
    .agg({'Col2':lambda x: ','.join(list(x))})\
            .pivot_table(columns='Col2',aggfunc='first')

print(out)

Col2  abc  abc,xyz  abc,xyz,pqr
Col1  111      123          456

然后,您可以通过比较新数据框中的哪些列和原始 df2 的唯一值来添加其他列:

out[[x for x in df.Col2.unique() if x not in out.columns]] = np.nan

结果将是:

print(out)

Col2  abc  abc,xyz  abc,xyz,pqr  xyz  pqr
Col1  111      123          456  NaN  NaN

【讨论】:

  • 我有大约 700 万行。有没有更快的方法?
  • 这仅给出 Col1 的第一次出现。我需要所有的事件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
  • 2023-03-22
  • 2019-01-28
  • 2020-10-01
  • 1970-01-01
  • 2021-01-12
  • 1970-01-01
相关资源
最近更新 更多