ここ"D"
カラムからユニークな要素に基づいてグループを形成するために、ベクトル化アプローチだ -
# Sort the dataframe based on the sorted indices of column 'D'
df_sorted = df.iloc[df['D'].argsort()]
# In the sorted dataframe's 'D' column find the shift/cut indces
# (places where elements change values, indicating change of groups).
# Cut the dataframe at those indices for the final groups with NumPy Split.
cut_idx = np.where(np.diff(df_sorted['D'])>0)[0]+1
df_split = np.split(df_sorted,cut_idx)
サンプル試験
1]はランダム要素とサンプルデータフレームフォーム:
>>> df = pd.DataFrame(np.random.randint(0,100,size=(5, 4)), columns=list('ABCD'))
>>> df
A B C D
0 68 68 90 39
1 53 99 20 85
2 64 76 21 19
3 90 91 32 36
4 24 9 89 19
を
2]元のコードを実行し、結果を印刷します。
>>> myunique = df['D'].unique()
>>> for i in myunique:
... itemp = df[df['D'] == i]
... print itemp
...
A B C D
0 68 68 90 39
A B C D
1 53 99 20 85
A B C D
2 64 76 21 19
4 24 9 89 19
A B C D
3 90 91 32 36
3]提案されたコードを実行し、結果を印刷する:] [、最小完全、かつ検証例を提供するために、常に試し
>>> df_sorted = df.iloc[df['D'].argsort()]
>>> cut_idx = np.where(np.diff(df_sorted['D'])>0)[0]+1
>>> df_split = np.split(df_sorted,cut_idx)
>>> for split in df_split:
... print split
...
A B C D
2 64 76 21 19
4 24 9 89 19
A B C D
3 90 91 32 36
A B C D
0 68 68 90 39
A B C D
1 53 99 20 85
を(http://stackoverflow.com/help/mcve)質問をするとき。 _pandas_の質問の場合は、サンプルの_input_と_output_データセット(CSV/dict/JSON/Pythonコードの形式で_7行〜_ text_です)を入力して、回答をコーディングする際に使用できます。これは、「あなたのコードは私のために働いていない」、あるいは「自分のデータでは動かない」などのような_situations_を避けるのに役立ちます。 – MaxU
あなたは何をしたいのかはっきりしません... – MaxU
私はしませんデータフレームの行を通して単純なループが必要です。それ以外の場合は簡単にnumpyで実装できます。元のデータフレームのサブセットを生成するolumn 'D'のユニークな値を使用するループが必要です。 numpyでは、2次元配列のすべての要素を繰り返し処理し、列 'D'に同じ値の行を格納する必要があります。実際のデータはありません。そのため、私はデータフレームにランダムな値を与えました。 – ilias