我的谷歌功能失败了.我有一个简单的框架,看起来像这样:

Sample Subject Person Place Thing
1-1 Janet
1-1 Boston
1-1 Hat
1-2 Chris
1-2 Austin
1-2 Scarf

我希望主题列中的值移动到相应的列中,这样我就得到了如下所示的结果:

Sample Subject Person Place Thing
1-1 Janet Janet Boston Hat
1-2 Chris Chris Austin Scarf

我看过旋转和转置,但它们看起来不太对劲.

任何 idea 都将受到赞赏!:)

推荐答案

如果组被排序,并且模式总是相同的(没有缺失值),则使用numpy重新塑造:

cols = ['Person', 'Place', 'Thing']

out = df.loc[::len(cols), ['Sample']].reset_index(drop=True)

out[cols] = df['Subject'].to_numpy().reshape(-1, len(cols))

对于更通用的方法,仅假设类别在一个组中总是以相同的顺序,标识每个组的位置:groupby.cumcountmap名称,然后pivot:

order = ['Person', 'Place', 'Thing']

out = (df.assign(col=df.groupby('Sample').cumcount()
                       .map(dict(enumerate(order))))
         .pivot(index='Sample', columns='col', values='Subject')
         .reset_index().rename_axis(columns=None)
      )

rename的变种:

order = ['Person', 'Place', 'Thing']

out = (df.assign(col=df.groupby('Sample').cumcount())
         .pivot(index='Sample', columns='col', values='Subject')
         .rename(columns=dict(enumerate(order)))
         .reset_index().rename_axis(columns=None)
      )

输出:

  Sample Person   Place  Thing
0    1-1  Janet  Boston    Hat
1    1-2  Chris  Austin  Scarf

最后,如果你真的想要"主题"一栏,insert它:

out.insert(1, 'Subject', out['Person'])

print(out)

  Sample Subject Person   Place  Thing
0    1-1   Janet  Janet  Boston    Hat
1    1-2   Chris  Chris  Austin  Scarf

timings

如果可以使用numpy方法,它对输入更严格,但速度更快:

enter image description here

Python相关问答推荐

如何自动抓取以下CSV

ModuleNotFound错误:没有名为Crypto Windows 11、Python 3.11.6的模块

Gekko:Spring-Mass系统的参数识别

. str.替换pandas.series的方法未按预期工作

在Python Attrs包中,如何在field_Transformer函数中添加字段?

如何过滤包含2个指定子字符串的收件箱列名?

在Mac上安装ipython

如何使用它?

如何在Python数据框架中加速序列的符号化

OR—Tools CP SAT条件约束

ThreadPoolExecutor和单个线程的超时

迭代嵌套字典的值

判断solve_ivp中的事件

Matplotlib中的字体权重

基于多个数组的多个条件将值添加到numpy数组

python sklearn ValueError:使用序列设置数组元素

操作布尔值的Series时出现索引问题

为什么我的scipy.optimize.minimize(method=";newton-cg";)函数停留在局部最大值上?

大型稀疏CSR二进制矩阵乘法结果中的错误

如何删除剪裁圆的对角线的外部部分