pandas本はpandasの話がメインなので逆引きがないのが辛いかなと思う。pandasに慣れると手放せないけど☆
というわけで、R言語逆引きハンドブックのベクトルの章をPandasでやってみた。
文字列を規則的に合成したベクトルを作成する
n = pd.Series(range(1,10)) n.apply(lambda r: "ID " + str(r))
因子を作成する
f = pd.Series(["y","n","y","n","n"]) pd.factorize(f) (array([0, 1, 0, 1, 1]), array(['y', 'n'], dtype=object))
Why does pandas (python library) has no factor like variable?に書かれている
- 因子の水準に並び順を定義する
- 使われていない因子の水準を削除する
- 因子の水準に大小関係を設定する
- 因子の水準を自由に組み合わせる
- 因子の水準ごとに関数を適用する
論理ベクトルを作成する
as.logicalに対応するものはない?
pd.Series([True, False, True, True])
論理ベクトルを計算する
>>> r = pd.Series(range(11)) >>> l = r[r > 5] >>> l.sum() 5 >>> l.any() True
which?
>>> l[l == True].index Int64Index([6, 7, 8, 9, 10], dtype=int64)
空のベクトルを初期化する
>>> pd.Series([]) Series([], dtype: float64)
ベクトルの要素数を変更する
length(x) <- 10
みたいにサイズを増やすことはできない?
減らすのは
>>> a = pd.Series(range(10)) >>> a[:5] 0 0 1 1 2 2 3 3 4 4 dtype: int64
ベクトルの要素に名前をつける
>>> a = pd.Series(range(5), index=list("abcde")) >>> a a 0 b 1 c 2 d 3 e 4 dtype: int64 >>> a["c"] 2
ベクトルから要素を抽出する
>>> a = pd.Series(range(5), index=list("abcde")) >>> a[list("ace")] a 0 c 2 e 4 dtype: int64 >>> a[[0,2,4]] a 0 c 2 e 4 dtype: int64 >>> a[(a<1)|(a>3)] a 0 e 4 dtype: int64
ベクトルから条件に適合する添字番号を取得する
indexを使う
>>> a = pd.Series(range(5)) >>> a[(a<1)|(a>3)].index Int64Index([0, 4], dtype=int64)
ベクトルの要素を並べ替える
>>> import numpy as np >>> a = pd.Series(range(5)) >>> a.reindex(np.random.permutation(a.index)) 2 2 0 0 3 3 1 1 4 4 dtype: int64 >>> b = a.reindex(np.random.permutation(a.index)) >>> b.sort() >>> b 0 0 1 1 2 2 3 3 4 4 dtype: int64
ベクトルの要素を置き換える
>>> a = pd.Series(range(5)) >>> a 0 0 1 1 2 2 3 3 4 4 dtype: int64 >>> a[(a<1)|(a>3)] = 10 >>> a 0 10 1 1 2 2 3 3 4 10 dtype: int64
ベクトルに要素を追加する
>>> a = pd.Series(range(5)) >>> a.append(pd.Series([0,0,0,0])) 0 0 1 1 2 2 3 3 4 4 0 0 1 0 2 0 3 0 dtype: int64
ベクトルの要素の重複を調べる
>>> a = pd.Series([1,2,3,4,5,4,6,3,2]) >>> a.duplicated() 0 False 1 False 2 False 3 False 4 False 5 True 6 False 7 True 8 True dtype: bool >>> a[a.duplicated()] 5 4 7 3 8 2 dtype: int64
ベクトルの要素の重複を削除する
>>> a.drop_duplicates() 0 1 1 2 2 3 3 4 4 5 6 6 dtype: int64
R逆引きハンドブックは手元に置いておくと重宝する☆
Pythonによるデータ分析入門 ―NumPy、pandasを使ったデータ処理
R言語逆引きハンドブック
メディシナルケミストリー
落下する夕方 (角川文庫)
模倣犯1 (新潮文庫)
模倣犯2 (新潮文庫)
砂の女 (新潮文庫)
陰翳礼讃 (中公文庫)
新装版 限りなく透明に近いブルー (講談社文庫)
最後の恋―つまり、自分史上最高の恋。 (新潮文庫)
□ しかく
銀の匙 (岩波文庫)
郵便配達夫はいつも二度ベルを鳴らす (ハヤカワ・ミステリ文庫 77-1)
叶えられた祈り (新潮文庫)




国道沿いのファミレス
神様のボート (新潮文庫)
センセイの鞄 (文春文庫)
ダンス・ダンス・ダンス(上) (講談社文庫)
ダンス・ダンス・ダンス(下) (講談社文庫)
真昼なのに昏い部屋 (講談社文庫)
ヘヴンリー・ブルー (集英社文庫)
かたちだけの愛
白痴 (新潮文庫)
天国旅行 (新潮文庫)
カラフル (文春文庫)
蹴りたい背中
つめたいよるに (新潮文庫)
号泣する準備はできていた
決壊〈上〉 (新潮文庫)
決壊〈下〉 (新潮文庫)
夏の約束
わたくし率 イン 歯ー、または世界
ニッポニアニッポン
Harkitek or ta ayoro





