LoginSignup
2
1

More than 3 years have passed since last update.

Pandasの基本操作

Last updated at Posted at 2020-08-31

DataFrameの作成

二次元のリストを引数として入れることでデータフレームの作成が可能。
パラメーターとしてcolumns,indexの指定をリストで指定可能。

import pandas as pd

df = pd.DataFrame([['a', 'e', 1, 5],
              ['b', 'f', None, 6],
              ['c', 'g', 3, 7],
              ['d', 'h', 4, 8],
              ],
             columns = ['column1', 'column2', 'column3', 'column4'],
             index = ['first', 'second', 'third', 'forth']
             )
df
#   column1 column2 column3 column4
# first a   e   1.0 5
# second    b   f   NaN 6
# third c   g   3.0 7
# forth d   h   4.0 8

DataFrameの情報確認

欠損地やデータ型の確認

df.info()
# <class 'pandas.core.frame.DataFrame'>
# Index: 4 entries, first to forth
# Data columns (total 4 columns):
#  #   Column  Non-Null Count  Dtype  
# ---  ------  --------------  -----  
#  0   col1    4 non-null      object 
#  1   col2    4 non-null      object 
#  2   col3    3 non-null      float64
#  3   col4    4 non-null      int64  
# dtypes: float64(1), int64(1), object(2)
# memory usage: 320.0+ bytes

統計データの確認

df.describe()
# col3  col4
# count 3.000000    4.000000
# mean  2.666667    6.500000
# std   1.527525    1.290994
# min   1.000000    5.000000
# 25%   2.000000    5.750000
# 50%   3.000000    6.500000
# 75%   3.500000    7.250000
# max   4.000000    8.000000

カラムの一覧をリストで作成

df.columns
# Index(['col1', 'col2', 'col3', 'col4'], dtype='object')

# リストにしたい場合は
df.columns.tolist()
list(df.columns)
# ['col1', 'col2', 'col3', 'col4']

インデックスの一覧をリストで作成

df.index
# Index(['first', 'second', 'third', 'forth'], dtype='object')

項目名の変更

df.columns = ['col1', 'col2', 'col3', 'col4']
df
# col1  col2    col3    col4
# first a   e   1.0 5
# second    b   f   NaN 6
# third c   g   3.0 7
# forth d   h   4.0 8

項目名の置換

df.rename(columns={'col1': 'changed_col1', 'col2':'changed_col2'})
#   changed_col1    changed_col2    col3    col4
# first a   e   1.0 5
# second    b   f   NaN 6
# third c   g   3.0 7
# forth d   h   4.0 8

空白行の削除

# 空白のある行全てを削除
df.dropna()
#   col1    col2    col3    col4
# first a   e   1.0 5
# third c   g   3.0 7
# forth d   h   4.0 8

# 指定した項目名の空白行全て削除
df.dropna(subset=['col1', 'col3'])
#   col1    col2    col3    col4
# first a   e   1.0 5
# third c   g   3.0 7
# forth d   h   4.0 8

特定の項目を削除

del df['col1', 'col2', 'col4']

特定の項目で並び替え

columns = ['col1', 'col2', 'col3']
df[columns]
# col1  col2    col3
# first a   e   1.0
# second    b   f   NaN
# third c   g   3.0
# forth d   h   4.0

文字の検索①

df.isin(['a', 'b', 'f'])
#   col1    col2    col3    col4
# first True    False   False   False
# second    True    True    False   False
# third False   False   False   False
# forth False   False   False   False

上記を使って特定の文字が項目や行にいくつあるかをカウント可能です。

項目でカウントする場合
df.isin(['a', 'b', 'f']).sum()
# col1    2
# col2    1
# col3    0
# col4    0
# dtype: int64
行でカウントする場合
df.isin(['a', 'b', 'f']).sum()
# first     1
# second    2
# third     0
# forth     0
# dtype: int64

文字の検索②


# 検索ワードと一致
df.query('col1 == "a" | col1 == "c"')
#   col1    col2    col3    col4
# first a   e   1.0 5
# third c   g   3.0 7

# 検索ワードを含む
# 含むの場合は後ろにengine='python'を付ける必要がある
df.query('column1.str.contains("search_word1") & column2.str.contains("search_word2") | column3.str.contains("search_word3")', engine='python')

文字の変換

# 辞書型で持つことによって複数を一度に変更可能
# NaNはnumpyのnanで変換可能
import numpy as np
df.replace({'a': 'changed_a',
            'b': 'changed_b',
            np.nan: ''})
#   col1    col2    col3    col4
# first changed_a   e   1   5
# second    changed_b   f       6
# third c   g   3   7
# forth d   h   4   8

DataFrameだとオブジェクトで一度に変換できますが、
テキストはオブジェクトで一度に変換することはできないので注意。

関数で特定の列を処理する場合

def function(data):
  # 行いたい処理
  return 

df['column'].map(lambda data: function(data))

上記で新しいcol4が7以上の場合はTrue、未満の場合はFalseが入るabove7を作る場合

def above7(data):
  return data >= 7

# 下記どちらでも追加可能
df['above7'] = df['col4'].map(lambda data: above7(data))
df.assign(above7 = df['col4'].map(lambda data: above6(data)))
# col1  col2    col3    col4    above7
# first a   e   1.0 5   False
# second    b   f   NaN 6   False
# third c   g   3.0 7   True
# forth d   h   4.0 8   True

横結合

行数が同じ場合しか使えないので注意

pd.concat([df1, df2], axis=1)

横持ちデータを縦持ちデータに変換

別記事を書いたのでこちらを参照ください。
https://qiita.com/plumfield56/items/4dbc7388d1673c6cf764

2
1
1

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