目次
※サンプルデータ:学校のテストの点数
![学校のイメージ](https://smart-hint.com/wp-content/uploads/2021/03/image-46-2.jpg)
student_data.head()
![学校のテストデータのイメージ](https://smart-hint.com/wp-content/uploads/2021/03/image-45.png)
len()でデータの量を数える
Pythonでデータ量を数えるにはlen()を使います
DataFrameを()カッコの中に入れることで、その行数を返します
len(student_data)
500
MEMO
注意点としてはすべてのデータが出るわけではなく、行数(レコード)が抽出されるので注意しましょう
データ数を変数として格納する
len()は単にデータ量を確認するだけではなく、変数として格納することができます
「student_data(テストの点数)」をlen()で数えたものを
「total_number」という変数に入れます
total_number = len(student_data)
もちろん「total_number」を出してみると、総数である500が抽出されます
そして「数値」として格納されるため、そのまま計算に使うこともできます
100 / total_number
0.2
応用編として「性別」ごとのデータを抽出して、全体(total_number)で割りましょう
全体に対する「男性・女性の人数の割合」を抽出してみます
まずは性別ごとの個数をvalue_counts()を使って抽出します
![](https://smart-hint.com/wp-content/uploads/2021/03/value_counts_2-520x300.png)
student_data['性別'].value_counts()
![school_data['性別'].value_counts()の結果](https://smart-hint.com/wp-content/uploads/2021/03/image-63.png)
続いて、その結果に対して先ほど変数として格納した「total_number」で割ります
student_data['性別'].value_counts() / total_number
![school_data['性別'].value_counts() / total_numberの結果](https://smart-hint.com/wp-content/uploads/2021/03/image-64.png)
ご覧の通り「割合」として男性・女性の差分が分かります
student_data['性別'].value_counts() / total_number
student_data['性別'].value_counts() / len(student_data) #こちらでもOK
カラム数を数える
len()のデフォルトの仕様では「行数」を抽出しますが、「列数」を抽出することもできます
columnsカラム名を抽出して、そこから個数を数えます
まずはカラム名だけをcolumnsで抽出します
student_data.columns
![](https://smart-hint.com/wp-content/uploads/2021/03/image-65-1024x40.png)
そしてlen()を使い項目数を数えましょう
len(student_data.columns)
9
まとめ
今回はデータ数を数えるlen()をご紹介してきました
非常にベーシックな機能なので、しっかり覚えて何も見ずに使えるようにしてみてください
![お気に入り登録お願いします](https://smart-hint.com/wp-content/uploads/2021/09/お気に入り登録.png)