Drkcore

25 12 2013 Python pandas Tweet

逆引きPandas (ベクトル編)

pandas本はpandasの話がメインなので逆引きがないのが辛いかなと思う。pandasに慣れると手放せないけど☆

ProductName Pythonによるデータ分析入門 ―NumPy、pandasを使ったデータ処理
Wes McKinney
オライリージャパン / 3780円 ( 2013-12-26 )


というわけで、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逆引きハンドブックは手元に置いておくと重宝する☆

ProductName R言語逆引きハンドブック
石田基広
シーアンドアール研究所 / 4830円 ( 2012-01-26 )


About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021