繁体   English   中英

如果另一列中的值为 x,如何更改 pandas 列中的某些字符串

[英]How to alter certain strings in a pandas column if value in another column is x

我有一个简单的 df。

    Genotype    freq
0   HET         0/1
1   REF         0/1
2   HOM         0/1
3   HOM         1/1

如果 'freq' == '0/1' 或 '1/0',我想将 'HOM' 更改为 'REF'。 我不想更改任何“HET”行。 我试图根据堆栈中的其他答案来做到这一点,但收效甚微。 我的尝试已粘贴在下面。

df = {'Genotype':  ['HET', 'REF', 'HOM', 'HOM'],
    'freq': ['0/1', '0/1', '0/1', '1/1']
    }

df = pd.DataFrame(df)

catch=['0/1', '1/0']
#attempt 1 - error: For argument "inplace" expected type bool, received  type int.
df.where(df['Genotype'] != 'HET', df.loc[df.freq.isin(catch), 'Genotype'] == 'REF', 0)
#attempt 2 - Ignores HET but adds TRUE/FALSE to other rows - looks messy.
df['Genotype']=df['Genotype'].apply(lambda x: 'HET' if x =='HET' else df.loc[df.freq.isin(catch), 'Genotype'] == 'REF')
#attempt 3 - Converts all '0/1' to REF
for index, row in df.iterrows():
    if row['Genotype'] == 'HOM':
        df.loc[df.freq.isin(catch), 'Genotype'] = 'REF'

如果可能的话,有没有一种简单的方法可以在 python/pandas 中执行此操作而无需创建新的 object - 索引在我拥有的较大的 function 中很重要。 干杯。

对于按位AND您需要通过&链接这两个条件:

catch=['0/1', '1/0']
df.loc[df.freq.isin(catch) & df['Genotype'].ne('HET'), 'Genotype'] = 'REF'
print (df)
  Genotype freq
0      HET  0/1
1      REF  0/1
2      REF  0/1
3      HOM  1/1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM