PyR*_*Rar 1 python dataframe pandas
我目前正在进行一项测试,在该测试中,我具有不同的区域以及一些相关的统计信息,并且用逗号分隔了这些区域中的基因。该列表的数量是可变的,并且可能不包含任何内容("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
Run Code Online (Sandbox Code Playgroud)
变成这样的东西:
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
Run Code Online (Sandbox Code Playgroud)
使用下面的代码,使用stack将其堆叠', ',然后在上拆分,然后再次对其进行堆叠,因为我们将其堆叠了两次,使用unstack进行了的堆叠-2,然后使用reset_indexwith 重置了索引-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()
)
Run Code Online (Sandbox Code Playgroud)
使用:
# Splitting on , and joining with region_id and statistic columns
val = pd.concat([df.region_id,
df.statistic,
df.genelist.str.split(',', expand=True)],
axis=1)
# Unpivoting and ignoring variable column
m = pd.melt(val, id_vars=['region_id', 'statistic'])\
.loc[:, ['region_id', 'statistic', 'value']]
# Ignoring Null values and sorting based on region_id
m[m.value.notnull()]\
.sort_values('region_id')\
.reset_index(drop=True)\
.rename(columns={'value':'gene'})
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
282 次 |
| 最近记录: |