我目前正在进行一项测试,其中我有不同的区域和一些相关的统计数据,以及位于这些区域的以逗号分隔的基因列表。此列表的数量是可变的,并且可能不包含任何内容 ("NA"
)。
我怎样才能“融化”这个数据框:
region_id statistic genelist
1 2.5 A, B, C
2 0.5 B, C, D, E
3 3.2 <NA>
4 0.1 E, F
像这样:
region_id statistic gene
1 2.5 A
1 2.5 B
1 2.5 C
2 0.5 B
2 0.5 C
2 0.5 D
2 0.5 E
3 3.2 <NA>
4 0.1 E
4 0.1 F
最佳答案
使用下面的代码,使用stack
进行堆叠,拆分后在','
上,然后再次堆叠,因为我们堆叠了两次,使用unstack
使用 -2
取消堆叠,然后使用 reset_index
和 -1
重置索引,然后执行最后的 reset_index
没有参数:
print(df.set_index(['region_id', 'statistic'])
.stack()
.str.split(', ', expand=True)
.stack()
.unstack(-2)
.reset_index(-1, drop=True)
.reset_index()
)
关于Python melt dataframe 基于逗号分隔的字符向量列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55016520/