回答:
このようなもの?
import random
def some(x, n):
return x.ix[random.sample(x.index, n)]
注: Pandas v0.20.0の時点で、ラベルベースのインデックス付けのためにix
廃止されましたloc
。
df.ix[np.random.random_integers(0, len(df), 10)]
。
df.ix[np.random.choice(df.index, 10)]
。
np.random.choice
が2倍の速さで言及しているrandom.sample
pandasバージョン0.16.1
以降では、DataFrame.sample
メソッドが組み込まれています。
import pandas
df = pandas.DataFrame(pandas.np.random.random(100))
# Randomly sample 70% of your dataframe
df_percent = df.sample(frac=0.7)
# Randomly sample 7 elements from your dataframe
df_elements = df.sample(n=7)
上記のいずれの方法でも、次のようにして残りの行を取得できます。
df_rest = df.loc[~df.index.isin(df_percent.index)]
df_0.7
は有効な名前ではありません。さらに、に置き換えることをお勧めdf_rest = df.loc[~df.index.isin(df_0_7.index)]
しdf_rest = df.loc[df.index.difference(df_0_7.index)]
ます。
difference()
ますか?
df_percent.index.get_indexer(df.index) == -1
代わりにはるかに効率的です(ただし、醜くなります)...
sample
v0.20.0以降では、を使用できますpd.DataFrame.sample
。これを使用して、固定数の行のランダムなサンプルまたは行の割合を返すことができます。
df = df.sample(n=k) # k rows
df = df.sample(frac=k) # int(len(df.index) * k) rows
再現性のために、を使用するのrandom_state
と同等の整数を指定できますnp.ramdom.seed
。したがって、たとえばを設定する代わりにnp.random.seed = 0
、次のことができます。
df = df.sample(n=k, random_state=0)
df.sample(N, replace=True)
。詳細はこちら。