4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pandasでデータを操る。数値だけ読み込んで統計処理をしたい編

Last updated at Posted at 2019-03-04

Introduction

以下のような実験データファイル(test.tsv)があるとします。実験データが得られなかった部分がハイフン'-'で埋められています。これを普通に読み込んで、何らかの数値処理を行いたいと思ったとします。

スクリーンショット 2019-03-04 12.21.18.png

普通に読み込んで、平均をとる...これができない。

1列目の'HGVD_AltAlleleFreq'の数値部分の平均を取りたいと思います。0.482と0.238の平均なので、0.36ぐらいが得られればここでは正解ですね。以下に普通に平均をとるスクリプトを示します。

test_proto.py
'''
    test.py
'''

import pandas as pd


# read data
data = pd.read_csv('test.tsv', delimiter='\t', index_col=0)

# calcurate mean
HGVD_AltAlleleFreq_mean = data['HGVD_AltAlleleFreq'].mean()

# print data_mean
print(HGVD_AltAlleleFreq_mean)

これを実行すると
TypeError: Could not convert -0.482----0.238--- to numeric
とエラーが返ってきます。ハイフンは数値ではないので、このままでは平均値という数値には変換できない、とおっしゃってますね。

数値以外はNaNに変換する

~.mean()の上に次の一行を追加しましょう。

# convert str to NaN
data['HGVD_AltAlleleFreq'] = data['HGVD_AltAlleleFreq'].convert_objects(convert_numeric=True)

これを行うと、数値型(intやfloat)以外のものはNaNに変換されます。試しに

print(data['HGVD_AltAlleleFreq'].convert_objects(convert_numeric=True))

とすると以下のような出力結果を得ます。

CHROM
chr1      NaN
chr1    0.482
chr1      NaN
chr1      NaN
chr1      NaN
chr1      NaN
chr1    0.238
chr1      NaN
chr1      NaN
chr1      NaN

これで無事、数値部分の平均のみをとることができます。ということで最終的なスクリプトは以下のようになります。

test.py

'''
    test.py
'''

import pandas as pd


# read data
data = pd.read_csv('test.tsv', delimiter='\t', index_col=0)

# convert str to NaN
data['HGVD_AltAlleleFreq'] = data['HGVD_AltAlleleFreq'].convert_objects(convert_numeric=True)

# calcurate mean
HGVD_AltAlleleFreq_mean = data['HGVD_AltAlleleFreq'].mean()

# print data_mean
print(HGVD_AltAlleleFreq_mean)
4
2
0

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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?