LoginSignup
0
0

【Python】Pandasを利用して、CSVファイルから特定の列の値をランダムで100行抽出する方法

Posted at

概要

Pandasを使用してCSVファイルからデータを読み込み、ランダムに選択された100行のデータから指定の列(サンプルコードでは"company_code"列)の値を抽出し、結果を表示する方法を紹介します。
開くのが重いCSVファイルで「この列にはどんな値が入っているんだろう?」をすぐに調べる際に使えました。

サンプルコード解説

import pandas as pd
import random

# CSVファイルのパス
csv_file_path = '/Users/xxxx/Desktop/hogehoge/sample.csv'
csv_encoding = "cp932"  # エンコーディングを指定

# ランダムな100行のインデックスを生成
all_data = pd.read_csv(csv_file_path, encoding=csv_encoding)
row_indexes = random.sample(range(len(all_data)), 100)

# "company_code"列の値を抽出(NaNを除外)
company_code_column = all_data.loc[row_indexes, "company_code"].dropna()

# 結果を表示
print(company_code_column.values)

はじめに、CSVファイルのパスとエンコーディングを指定します。
"cp932"というエンコーディングは、Windowsで一般的に使用される日本語の文字コードです。異なるエンコーディングが必要な場合は、適切なエンコーディングを指定してください。

次に、pd.read_csv()関数を使用して、指定されたCSVファイルをデータフレームとして読み込んでいます。ランダムで100行としていますが、10行で良い場合は、10と指定してください。

dropna()関数を使用して、NaN(欠損値)を除外する処理をしています。ランダムで100件選んだものが全て空白のものの可能性もあるため、除外しています。空白も許容する場合はこちら消します。
dropna()関数は、Pandasのデータフレームやシリーズオブジェクトに対して欠損値(NaN)を含む行や列を除外するために使用されます。

最後に、values属性を使用することで、NumPyの配列として値を取得します。

以下、出力例です。

  all_data = pd.read_csv(csv_file_path, encoding=csv_encoding)
[1 5 2 3 2 1 2 5 5 2 2 3 1 3 5 2 3 2 2 1 2 2 2 2 5 1 3 2 3 2 1 5 1 5 5 5 1
 2 5 2 2 2 3 5 5 2 5 2 2 3 1 1 5 5 2 2 1 1 3 1 2 5 3 1 2 1 2 2 2 2 5 3 2 5
 2 1 5 5 3 2 1 1 2 2 5 1 2 2 3 1 1 5 2 2 1 1 1 1 3 5]
0
0
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
0
0