python - 识别重复项和相应的索引
问题描述
我正在连接来自不同样本的突变数据的几个数据帧。我知道会有重复,即几个样本将具有相同的常见突变。我想删除相同突变的额外重复行,而是包含一个包含所有具有该突变的样本的列。我不认为 df.drop_duplicates() 这样做,就像 np.unique() 一样。
简化示例:
import pandas as pd
df = pd.DataFrame({"Chromosome":[1, 1, 1, 1, 1],
'Position': [100, 220,300,100,220],
"Gene":["CHD1","BRCA2","TP53","CHD1", "BRCA2"],
"SAMPLE":["A1","A2","A3","A4", "A5"]})
df
Output:
Chromosome Position Gene SAMPLE
0 1 100 CHD1 S1
1 1 220 BRCA2 S2
2 1 300 TP53 S3
3 1 100 CHD1 S4
4 1 220 BRCA2 S5
我想结束这个:
df_new
Output:
Chromosome Position Gene SAMPLES Count
0 1 100 CHD1 [S1, S4] 2
1 1 220 BRCA2 [S2,S5] 2
2 1 300 TP53 S3 1
我确信有一些我缺少的简单方法可以做到这一点。
这是我在 numpy 中所做的方式(使用 np.uniue(return_inverse=True) 的反向输出。它有效,但效率不高。
Samples = array(master_df['Sample_ID'], dtype=str)
temp_array = array(master_df[master_df.columns[0:3]], dtype=str)
temp_unq, ind1, inv1, cnts1 = unique(temp_array, return_index= True, return_inverse=True, return_counts=True, axis=0)
s1 = [[] for i in cnts1]
for i in range(temp_unq.shape[0]):
whr = np.where(inv1==i)[0]
s1[i].append(list(Samples[whr]))
unq_combo = master_df.iloc[ind1]
unq_combo = unq_combo.reset_index(drop=True)
unq_combo['Counts'] =pd.Series(cnts1)
unq_combo['Samples#'] = pd.Series(s1)
解决方案
使用groupby
和agg
:
df.groupby(['Chromosome', 'Position', 'Gene']).SAMPLE.agg([list, 'count'])
list count
Chromosome Position Gene
1 100 CHD1 [S1, S4] 2
220 BRCA2 [S2, S5] 2
300 TP53 [S3] 1
(df.groupby(['Chromosome', 'Position', 'Gene']).SAMPLE
.agg([list, 'count'])
.reset_index())
Chromosome Position Gene list count
0 1 100 CHD1 [S1, S4] 2
1 1 220 BRCA2 [S2, S5] 2
2 1 300 TP53 [S3] 1
推荐阅读
- pandas - 如何在python中将列表垂直对齐到熊猫数据框
- java - 类的模拟方法
- c# - C# 中的随机数生成错误
- mysql - SQL查找每组中第N个值对应的行
- spring - 为什么 Spring Initializr 拼写为 initializr 而不是 initializer?
- json - 获取错误类型'_InternalLinkedHashMap
' 不是类型 'Iterable 的子类型 ' 同时从 API 中获取数据 - css - 如何删除角度材料模态内按钮的自动对焦?
- mysql - 什么是在 SQL 中使用的正确方法
- android - 如果我在 greendao 中使用 rowQuery 更新表,那么在我无法使用下面的 Querybuilder 获取更新数据之后?
- apache-kafka - Kafka 流 - 为变更日志定义保留策略