LoginSignup
24
21

More than 5 years have passed since last update.

Pandasでデータを操る。ある列に特定の文字(文字列)を含んだ行を削除編

Last updated at Posted at 2019-03-01

タイトルの通り、「ある列に特定の文字(文字列)が含まれている場合、それを行ごと削除したい」という願いを叶えるPythonスクリプトをご紹介します。

Pythonスクリプト

nonG.py

'''
    nonG.py
    purpose: delete G row in ALT column
'''

import os
import pandas as pd
import argparse
import sys


def main():

    # make parser
    parser = argparse.ArgumentParser()

    # add argument
    parser.add_argument('input')
    parser.add_argument('output')

    # analize arguments
    args = parser.parse_args()

    # set input filename and the number of vcf header
    inputfile = args.input
    print(inputfile)

    # if inputfile does not exist, print error message and program done
    if os.path.exists(inputfile) == False:
        print(inputfile+' does not exist. Please check file name.')
        sys.exit(1)

    # set output filename
    outputfile = args.output

    # if outputfile already exists, print error message and program done
    if os.path.exists(outputfile) == True:
        print(outputfile+' already exists. Please delete or rename.')
        sys.exit(1)

    # input tsv
    data = pd.read_csv(inputfile, delimiter='\t')

    # delete row contains G in ALT column
    data = data[~data['ALT'].str.contains('G')]

    # output data to outputfile
    data.to_csv(outputfile, index=False, mode='a', sep='\t')


if __name__ == '__main__':

    main()

テストデータには以下のようなinput.tsvファイルを用います。

スクリーンショット 2019-03-01 10.24.48.png

このスクリプトを実行するにはターミナルで以下のようにタイプしてください。

$ python nonG.py input.tsv output.tsv

結果がoutput.tsvとして出力されます。

スクリプト詳細

最初の方はinput.tsvを読み込む作業をしているので無視して、本題のデータ操作を説明したいと思います。

 # delete row contains G in ALT column
data = data[~data['ALT'].str.contains('G')]

このたった1行で「'ALT'列にある、'G'を含む行を削除」しています。

data['ALT'].str.contains('G')

でdataの中の'ALT'列の中で、文字(文字列)'G'を含むものを抽出しています。そこに否定を意味する演算子 ~ をつけ、

~data['ALT'].str.contains('G')

とすることで、文字(文字列)'G'を含まないものを抽出することができます。このようにすることで、特定の文字を含む行を削除したデータテーブルを簡単に作成することができます。結果は以下のようになります。

スクリーンショット 2019-03-01 10.26.41.png

'ALT'列から文字(文字列)'G'を含む行が削除されていることがわかります。

24
21
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
21