[英]Pivot Pandas Dataframe with Duplicates using Masking
未索引的df包含基因行,包含該基因突變的細胞以及該基因突變的類型:
df = pd.DataFrame({'gene': ['one','one','one','two','two','two','three'],
'cell': ['A', 'A', 'C', 'A', 'B', 'C','A'],
'mutation': ['frameshift', 'missense', 'nonsense', '3UTR', '3UTR', '3UTR', '3UTR']})
df:
cell gene mutation
0 A one frameshift
1 A one missense
2 C one nonsense
3 A two 3UTR
4 B two 3UTR
5 C two 3UTR
6 A three 3UTR
我想旋轉此df,以便我可以按基因索引並為細胞設置列。 問題在於每個細胞可能有多個條目:給定細胞中的任何一個基因都可能存在多個突變(細胞A在一個基因中具有兩個不同的突變)。 因此,當我運行時:
df.pivot_table(index='gene', columns='cell', values='mutation')
有時候是這樣的:
DataError: No numeric types to aggregate
我想使用遮罩來執行數據透視,同時捕獲至少一個突變的存在:
A B C
gene
one 1 1 1
two 0 1 0
three 1 1 0
該錯誤消息不是您運行pivot_table
時產生的。 您可以在數據pivot_table
的索引中包含多個值。 我不認為這對於pivot
方法是正確的。 但是,您可以通過將聚合更改為適用於字符串而不是數字的內容來解決問題。 大多數聚合函數都在數字列上運行,並且您上面編寫的代碼將產生與列的數據類型有關的錯誤,而不是索引錯誤。
df.pivot_table(index='gene',
columns='cell',
values='mutation',
aggfunc='count', fill_value=0)
如果每個單元格只需要1個值,則可以執行groupby並將所有內容匯總為1,然后取消堆疊級別。
df.groupby(['cell', 'gene']).agg(lambda x: 1).unstack(fill_value=0)
drop_duplicates
和pivot_table
解決方案:
df = df.drop_duplicates(['cell','gene'])
.pivot_table(index='gene',
columns='cell',
values='mutation',
aggfunc=len,
fill_value=0)
print (df)
cell A B C
gene
one 1 0 1
three 1 0 0
two 1 1 1
用另一種解決方案drop_duplicates
, groupby
與總size
由和最后重塑unstack
:
df = df.drop_duplicates(['cell','gene'])
.groupby(['cell', 'gene'])
.size()
.unstack(0, fill_value=0)
print (df)
cell A B C
gene
one 1 0 1
three 1 0 0
two 1 1 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.