0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

R ⇄ python 対応シート(表計算系)

Last updated at Posted at 2021-03-09

pythonをやっていて、Rで言うあの関数が使いたい!(逆も然り)となった時のためのメモです。
私はpythonがわからないのでpythonメインで、Rの中身は適当です。
例のためDataFrameはdfと表記しています。(Rはtidyとごっちゃになってるかもしれないです、大体大丈夫ですが、、)
あと、import pandas as pdをはじめに入れているという前提でコマンドを書いています。
Kaggle Coursesのpandasをやりながら途中でまとめたものです。他にもあれば(私が上のような状態になった時に)随時更新していきます。
※tidyverseでできるtableとpandasのDataFrameは若干違うのであくまでも似たような関数を並べているという事だけご了承ください。

unique() ⇄ df[~df.duplicated()]

重複をなくす
df['column'].unique()
であれば要素についてuniqueなものを出してくれる
df['column'].nunique()という個数だけ返してくれるものもあるみたい

table() ⇄ df['column'].value_counts()

Rの標準関数とpandasの関数

cross_tab.py
import numpy as np;
import pandas as pd;
x = np.array([1, 1, 1, 1, 2, 2]);
y = np.array(["a", "a", "b", "a", "a", "b"]);
pd.crosstab(x, y, rownames = ['x'], colnames = ['y']);

でもできるらしい。

rename() ⇄ df.rename(columns={'before': 'after'})

pythonの方は列のインデックスでも指定できるとのこと。(index={0: '0_after', 1: '1_after'})
ちなみにDataFrameの軸の名前をつける場合にはdf.rename_axis()を使うらしい。

rbind(first_df, second_df) ⇄ pd.concat([first_df, second_df])

tidyverseだとbind_rows()もありますね
pythonの方はリストにしないといけない、、(なぜ)
ignore_index=Trueとするとindexを振りなおしてくれます。

left_join(left_df, right_df, by='common_name') ⇄ left.join(right, lsuffix='_1',rsuffix='_2')

pythonの方はkeyとなる列名を予めindexとして指定する必要がある?
left = left_df.set_index(['column_1', 'column_2']) right = right_df.set_index(['column_1', 'column_2'])
あとpythonの方はjoinで使うkey以外で共通の列名に対してsuffixを指定できるみたいです。(Rは勝手に.x/.y がつくイメージでしたがRでも指定できるのかな→できるんですね!)

df.merge(left, right, on='common_column')もあるみたいです。うまく使い分けたら良さそうです。

filter(df, 条件) ⇄ df.query('条件', inplace=False)

条件は''で囲む必要がある。dfのcolumnであればそのまま使えるが、スペースのあるものは` ` で囲んだり、dfにない変数であれば頭に@をつける必要がある。
inplace=Trueにすると新たにindexをふってくれる ←挙動がよくわかりません、、

arrange(df,column) ⇄ df.sort_values('column', ascending=True)

デフォルトはどちらも昇順。降順にする場合は、Rならdesc(column)、pythonならascending=Falseとする

select(df, -column) ⇄ df.drop(columns='column', axis=1)

selectだと列の選択も除去も同じ関数でできるが、pandasだとそうもいかなさそう。。
残す列を指定する場合には
df=df[['column1','column2']]
でよい。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?