非索引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发布于 2016-12-16 06:12:45
基于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的另一种解决方案,带有聚合size的groupby和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发布于 2016-12-16 05:53:28
错误消息不是在运行pivot_table时产生的。pivot_table的索引中可以有多个值。我不认为pivot方法是正确的。但是,您可以通过将聚合更改为对字符串(而不是数字)有效的方法来解决问题。大多数聚合函数都对数值列进行操作,上面编写的代码将产生与列的数据类型有关的错误,而不是索引错误。
df.pivot_table(index='gene',
columns='cell',
values='mutation',
aggfunc='count', fill_value=0)如果您只希望每个单元格有一个值,则可以按组进行分组,并将所有内容聚合到1,然后展开一个级别。
df.groupby(['cell', 'gene']).agg(lambda x: 1).unstack(fill_value=0)https://stackoverflow.com/questions/41177925
复制相似问题