我是pandas的初学者(如果我使用的术语错误,我深表歉意),我目前正在从事基因组计划。使用drop_duplicates()后,无法处理数据框列。我想更改删除重复项后保留的ID的“突变”列中的列值,以表明此ID具有多个突变。
df = pd.DataFrame([
('MYC', 'nonsense', 's1'),
('MYC', 'missense', 's1'),
('MYCL', 'nonsense', 's1'),
('MYCL', 'missense', 's2'),
('MYCN', 'missense', 's3'),
('MYCN', 'UTR', 's1'),
('MYCN', 'nonsense', 's1')
], columns=['id', 'mutation', 'sample'])
print(df)
id mutation sample
0 MYC nonsense s1
1 MYC nonsense s1
2 MYC missense s1
3 MYCL nonsense s1
4 MYCL missense s2
5 MYCN missense s3
6 MYCN UTR s1
7 MYCN nonsense s1
我尝试使用drop_duplicates(),但我接近想要的东西。但是,如何将“突变”列中的值更改为“多”?
print(df.drop_duplicates(subset=('sample','id')))
id mutation sample
0 MYC nonsense s1
3 MYCL nonsense s1
4 MYCL missense s2
5 MYCN missense s3
6 MYCN UTR s1
id mutation sample
0 MYC multi s1
3 MYCL nonsense s1
4 MYCL missense s2
5 MYCN missense s3
6 MYCN multi s1
答案 0 :(得分:1)
df.loc[df.duplicated(subset=['id', 'sample'], keep='last'), 'mutation'] = 'multi'
df.drop_duplicates(subset=['id', 'sample'])
说明:首先确定哪些是重复项,然后更改这些重复项的突变列。仅在此之后,删除重复项。
答案 1 :(得分:1)
duplicated
mask = df.duplicated(['id', 'sample'], keep=False)
df.assign(mutation=df.mutation.mask(mask, 'multi')).drop_duplicates()
id mutation sample
0 MYC multi s1
2 MYCL nonsens s1
3 MYCL missense s2
4 MYCN missense s3
5 MYCN multi s1
groupby
df.groupby(['id', 'sample'], sort=False).mutation.pipe(
lambda g: g.first().mask(g.size() > 1, 'multi')
).reset_index().reindex(df.columns, axis=1)
id mutation sample
0 MYC multi s1
1 MYCL nonsens s1
2 MYCL missense s2
3 MYCN missense s3
4 MYCN multi s1