Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 3 years have passed since last update.

[Python] pandasメモ

Last updated at Posted at 2019-09-20

[pandas.Series]
(https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.html)
[pandas.DataFrame]
(https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html)

全般

クラス

pandas.Seriesは1次元,pandas.DataFrameは2次元.

Qiita: pandasのSeriesとDataFrameを区別して使えてますか?

DataFrame -> Seriesの変換

["列名"], loc["列名"], iloc[列番号]でOK.
これらの引数にリスト (スライス) を入れると長さ1でもDataFrameになる.

[note.nkmk.me: pandas.DatraFrameとSeriesを相互に変換]
(https://note.nkmk.me/python-pandas-dataframe-series-conversion/)

Series.values.tolist(): Series -> Listの変換

[note.nkmk.me: pandas.DataFrame, SeriesとPython標準のリストを相互に変換]
(https://note.nkmk.me/python-pandas-list/)

IO

read_csvはカンマ,区切り(多くは.csv),read_tableはタブ\t区切り(多くは.tsv)だが,内部的には同じ.
rad_csvのsep=オプションで``'\t'`を指定すればタブ区切りでも読める.

pandas.read_csv
note.nkmk.me: pandasでcsvファイルの書き出し・追記(to_csv)
note.nkmk.me: pandasでExcelファイル(xlsx, xls)の読み込み(read_excel)

これで作られるデータフレームはusecolsで指定した通りの順番には並んでいない.
順番を保証したい場合は以下の通り.

df_ret = pd.read_csv(filepath, index_col=False, usecols=cols_to_use)[cols_to_use]

[stackoverflow: Keeping columns in the specified order when using UseCols in Pandas Read_CSV]
(https://stackoverflow.com/questions/40024406/keeping-columns-in-the-specified-order-when-using-usecols-in-pandas-read-csv)

データ型

数字への変換

to_numeric()を使う.これはpandas.Seriesを引数にとる関数.errors='coerce'で変換できなかった値をNaNにすることができる.

pandas.to_numeric

Series.dt.date: datetime -> dateの変換
df['just_date'] = df['dates'].dt.date

[stackoverflow: Keep only date part when using pandas.to_datetime]
(https://stackoverflow.com/questions/16176996/keep-only-date-part-when-using-pandas-to-datetime)

変換

DataFrame → dict

to_dict()で可能だが,データ全てが辞書に変換される.
{index: 指定した列の値}とするには,

df['列名'].to_dict() # { index: その列の値(リスト,辞書ではなくスカラー) }

teratail: 【python】pandasのDataFrame から辞書型のデータを抜き出したい。

複数の列をタプルで結合するには,

df['new_col'] = list(zip(df.lat, df.long))

stackoverflow: How to form tuple column from two columns in Pandas

dict → DataFrame

元の辞書の構造には2通りある:

  • {index: value}型
  • {column: value}型

{index: value} 型

# Pattern 1
adict = {'idx1': 'one', 'idx2': 'two'}
df = pd.DataFrame(adict.items(), columns=['idx', 'num'])
'''
    idx  num
------------
0  idx1  one
1  idx2  two
'''

# Pattern 2
df = pd.DataFrame.from_dict(adict, orient='index', columns=['num'])
df.index.name = 'idx'
'''
 idx  num
---------
idx1  one
idx2  two
'''

# Pattern 3
s = pd.Series(adict, name='num')
s.index.name = 'idx'
'''
idx
-----------
idx1    one
idx2    two
Name: num, dtype: object
'''

[stackoverflow: Convert Python dict into a dataframe]
(https://stackoverflow.com/questions/18837262/convert-python-dict-into-a-dataframe)

{column: value}型

[Qiita@ShoheiKojima: 辞書をpd.DataFrameに変換]
(https://qiita.com/ShoheiKojima/items/30ee0925472b7b3e5d5c)

値の取得

note.nkmk.me: pandasで任意の位置の値を取得・変更するat, iat, loc, iloc

インデックスによる行の取得はloc[]

df.loc['Bob']
df.iloc[1] # 行番号で指定するときは"i"loc

※行番号でスライスは可能だが,スカラー値で指定は出来ない

df[1:2] # OK
df[1]   # NG!!

note.nkmk.me: pandasのインデックス参照で行・列を選択し取得

MultiIndexもできる

Series,DataFrameどちらも対応.

[DeepAge: PandasのMultiIndexについて理解する]
(https://deepage.net/features/pandas-multiindex.html)

辞書のように指定したインデックスがないときにはデフォルト値を返す

Seriesのget(index, default_value)メソッド.

[stackoverrun: return default if pandas dataframe.loc location doesn't exist]
(https://stackoverrun.com/ja/q/6411001)

メソッド

メソッド全般

多くのメソッドは,inplace=Trueをつけないとオブジェクト自体を変更しない.
inplace=Trueを付けない場合は,df = df.~~()と再代入が必要.

特定の行・列の削除

列の削除

df.drop( 'A', axis=1 )

Pandas のデータフレームの特定の行・列を削除する

欠損値の削除

df.dropna( how='any', axis=0 )
①how…'any':1つでも行or列nに欠損値が含まれていれば削除,'all': その行or列の全てが欠損値であれば削除
②axis…0:行

特定の行・列に関して欠損値を探して削除する場合にはsubset=
ただし1つの行・列を指定する場合でもリストで.

in listを使うにはisin()メソッド

countries = ['UK','China']
df.countries.isin(countries)

ユニークな要素の扱い

Seriesのメソッドが複数存在.

  • Serires.unique() -> numpy.ndarray: ユニークな値を配列として取得
    • pd.unique(array)
  • Series.value_counts() -> Series: {ユニークな値: その出現数}
  • Series.nunique() -> int: ユニークな値の個数
    • DataFrame.nunique() -> Series: 各列or各行のユニークな値の個数

note.nkmk.me: pandasでユニークな要素の個数、頻度(出現回数)をカウント

他の列の値でグループ化してからユニークな要素の数を集計
df = df.groupby("グループ化に使う列名")["ユニークな値を集計する列名"].nunique()
# {"各グループ名": ユニークの値の個数}

[stackoverflow: Count unique values with pandas per groups [duplicate]]
(https://stackoverflow.com/questions/38309729/count-unique-values-with-pandas-per-groups)

列の並び替え

df.loc[:, 列名を格納したリスト]

Qiita: Pandasのdataframeの列を並べ替え。

ソート

df.sort_values(by=[列名のリスト], ascending=True)

ascending=Trueで値が小→大の順で並ぶ.

Qiita: pandas でソート

高速化

高速化

  • read_csv()usecols=を指定してデータ数を減らす
  • forは使わずにmapを使う,applyは微妙らしい

Qiita: pandasで1000万件のデータの前処理を高速にするTips集
Lean Baseball: うわっ…私のpandas、遅すぎ…?って時にやるべきこと(先人の知恵より)

空のDataFrameにデータを追加していく

Qiita@567000: Python pandas で動的に行を追加するTips(プログラマ向け)

但しこのページで使われているappendはとても遅いので注意(以下の2通りで代用可)

append高速化

Qiita@studio_haneya: pandas.DataFrameに1行ずつ書き足す早い方法を調べた
Qiita@xtkd: Pandas DataFrame で append すると遅い

その他

表示行数の拡張

pd.set_option("display.max_rows", 101)

GAミント至上主義: pandasで表示が省略されるのを防ぐ

算術

actdf['depth'][ isfeet ] = actdf['depth'][ isfeet ] * 0.3048

actdf['depth'] = だと[ isfeet ]に該当しないところ以外がNaNになってしまう

複数条件には(式) &, |, ~ (式)を使う

and, or, notはダメ.

note.nkmk.me: pandasで複数条件のAND, OR, NOTから行を抽出(選択)

pandasでExcelファイルを使う

[note.nkmk.me:pandasでExcelファイル(xlsx, xls)の読み込み(read_excel)]
(https://note.nkmk.me/python-pandas-read-excel/)

A value is trying to be set on a copy of a slice from a DataFrameエラーへの対応

.locを使う

data.loc[data['col1'] == 1, 'col3'] = data['col2'] * 3

Qiita@gymnstcs: python pandas でSettingWithCopyWarning A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value insteadを出ないようにする

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?