Nic*_*ico 6 python pivot-table dataframe pandas tidyr
我知道在RI中可以使用tidyr进行以下操作:
data_wide <- spread(data_protein, Fraction, Count)
Run Code Online (Sandbox Code Playgroud)
和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
Run Code Online (Sandbox Code Playgroud)
变
Protein Peptide Start F1 F2
1 A 122 1 2
1 B 230 3 4
Run Code Online (Sandbox Code Playgroud)
但在熊猫(Python)中,
data_wide = data_prot2.reset_index(drop=True).pivot('Peptide','Fraction','Count').fillna(0)
Run Code Online (Sandbox Code Playgroud)
不继承函数中未指定的任何内容(索引,键,值).因此,我决定通过df.join()加入它:
data_wide2 = data_wide.join(data_prot2.set_index('Peptide')['Start']).sort_values('Start')
Run Code Online (Sandbox Code Playgroud)
但这会产生肽的重复,因为有几个起始值.有没有更直接的方法来解决这个问题?或者一个特殊的连接参数,省略重复?先感谢您.
尝试这个:
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
Run Code Online (Sandbox Code Playgroud)
您还可以显式指定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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1267 次 |
| 最近记录: |