在透视表(pandas)中添加列

6

我知道在R中,我可以使用tidyr来进行以下操作:

data_wide <- spread(data_protein, Fraction, Count)

data_wide将继承data_protein中未分列的所有列。

Protein Peptide  Start  Fraction  Count
1             A    122       F1     1
1             A    122       F2     2     
1             B    230       F1     3     
1             B    230       F2     4

变成

Protein Peptide  Start  F1  F2
1             A    122   1  2
1             B    230   3  4     

但是在pandas(Python)中,

data_wide = data_prot2.reset_index(drop=True).pivot('Peptide','Fraction','Count').fillna(0)

在函数中没有指定的属性(索引,键,值)不会被继承。因此,我决定通过df.join()进行连接:

data_wide2 = data_wide.join(data_prot2.set_index('Peptide')['Start']).sort_values('Start')

但是由于存在多个起始值,这会产生肽段的重复。有没有更简单的方法来解决这个问题?或者join函数中是否有一些特殊参数可以排除重复?提前感谢您的帮助。
3个回答

4

尝试这个:

In [144]: df
Out[144]:
   Protein Peptide  Start Fraction  Count
0        1       A    122       F1      1
1        1       A    122       F2      2
2        1       B    230       F1      3
3        1       B    230       F2      4

In [145]: df.pivot_table(index=['Protein','Peptide','Start'], columns='Fraction').reset_index()
Out[145]:
         Protein Peptide Start Count
Fraction                          F1 F2
0              1       A   122     1  2
1              1       B   230     3  4

您也可以明确指定Count列:

In [146]: df.pivot_table(index=['Protein','Peptide','Start'], columns='Fraction', values='Count').reset_index()
Out[146]:
Fraction  Protein Peptide  Start  F1  F2
0               1       A    122   1   2
1               1       B    230   3   4

我应该在哪一步做这个?我什么时候指定Count是Fraction的值? - Nico

1
使用 stack
df.set_index(df.columns[:4].tolist()) \
  .Count.unstack().reset_index() \
  .rename_axis(None, axis=1)

enter image description here


0

spreadtidyr中已被pivot_wider取代。

使用遵循tidyr API设计的datar如何?

>>> from datar.all import f, tribble, pivot_wider
>>> data_protein = tribble(
...     f.Protein, f.Peptide,  f.Start,  f.Fraction,  f.Count,
...     1,         "A",        122,      "F1",        1,
...     1,         "A",        122,      "F2",        2,     
...     1,         "B",        230,      "F1",        3,     
...     1,         "B",        230,      "F2",        4,
... )
>>> data_wide = pivot_wider(data_protein, names_from=f.Fraction, values_from=f.Count)
>>> data_wide
  Peptide  Protein  Start  F1  F2
0       A        1    122   1   2
1       B        1    230   3   4

我是这个软件包的作者。如果您有任何问题,请随时提交问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接