0
0

More than 1 year has passed since last update.

Pandas: データフレームについて--09: データフレームを表示する

Last updated at Posted at 2022-06-22

データフレームの表示

import pandas as pd
import numpy as np

n = 65
np.random.seed(123)
df = pd.DataFrame({
    'a': np.arange(n) + 100,
    'b': np.random.rand(n),
    'c': np.around(np.random.normal(50, 10, n)),
    'd': np.random.choice(['A', 'B', 'C', 'D', 'E'], n)
})
df
a b c d
0 100 0.696469 51.0 A
1 101 0.286139 48.0 A
2 102 0.226851 43.0 E
3 103 0.551315 44.0 B
4 104 0.719469 41.0 C
... ... ... ... ...
60 160 0.669314 49.0 E
61 161 0.585937 42.0 A
62 162 0.624904 48.0 B
63 163 0.674689 36.0 C
64 164 0.842342 41.0 C

65 rows × 4 columns

1. 最初の n 行を表示

head(n: 'int' = 5)
df.head()
a b c d
0 100 0.696469 51.0 A
1 101 0.286139 48.0 A
2 102 0.226851 43.0 E
3 103 0.551315 44.0 B
4 104 0.719469 41.0 C
df.head(2)
a b c d
0 100 0.696469 51.0 A
1 101 0.286139 48.0 A

2. 最後の n 行を表示

tail(n: 'int' = 5)
df.tail()
a b c d
60 160 0.669314 49.0 E
61 161 0.585937 42.0 A
62 162 0.624904 48.0 B
63 163 0.674689 36.0 C
64 164 0.842342 41.0 C
df.tail(2)
a b c d
63 163 0.674689 36.0 C
64 164 0.842342 41.0 C

3. 任意の行を表示

以下の方法以外は 「データフレームについて--03: 行,列の取り出し」 を参照のこと。

df.iloc[8:12, :]
a b c d
8 108 0.480932 63.0 D
9 109 0.392118 71.0 E
10 110 0.343178 48.0 C
11 111 0.729050 48.0 C

以下のような場合,[1, 3, 5, 7:10] と指定したくなるが,それではエラーになる。

df.iloc[[1, 3, 5, 7, 8, 9, 10], :]
a b c d
1 101 0.286139 48.0 A
3 103 0.551315 44.0 B
5 105 0.423106 52.0 B
7 107 0.684830 59.0 B
8 108 0.480932 63.0 D
9 109 0.392118 71.0 E
10 110 0.343178 48.0 C

4. 全部の行を表示させる

冒頭に示したように,60 行を超える場合は,デフォルトで省略表示される。

無理やり全行表示させるには,オプションを設定する。

set_option(pat, value)

'display.max_rows'None を設定すればよい。当然,数値で希望する値を設定することもできる。

pd.set_option('display.max_rows', None)
df
a b c d
0 100 0.696469 51.0 A
1 101 0.286139 48.0 A
2 102 0.226851 43.0 E
以下略

5. もっと知りたい人

help(pd.set_option) # Help on CallableDynamicDoc in module pandas._config.config
help(df.first)      # Help on method first in module pandas.core.generic
help(df.last)       # Help on method last in module pandas.core.generic
help(df.iloc)       # Help on _iLocIndexer in module pandas.core.indexing object
help(df.loc)        # Help on _LocIndexer in module pandas.core.indexing object
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