私は以下のデータフレームを持っています。 (これは必ずしもデータフレームではなく、numpyのアレイdf.values
で解決策も十分であろう)列の値と配列のサイズ(または系列)を比較すると、
np.random.seed(42)
df = pd.DataFrame(np.random.random((10,2)),columns=['a', 'b'])
df
a b
0 0.374540 0.950714
1 0.731994 0.598658
2 0.156019 0.155995
3 0.058084 0.866176
4 0.601115 0.708073
5 0.020584 0.969910
6 0.832443 0.212339
7 0.181825 0.183405
8 0.304242 0.524756
9 0.431945 0.291229
Iは、以下の論理に従って値を持つ新しいカラム含める:
を真:そうでなければ
:特定のa
値の後b
値のいずれかがそのpartiulcar a
値より大きい Falseの場合予想される出力は次のようになります。 は、上記のforループで可能でなければなりません
a b c
0 0.374540 0.950714 True
1 0.731994 0.598658 True
2 0.156019 0.155995 True
3 0.058084 0.866176 True <- np.any(0.058084 < np.array([0.708073, 0.969910, 0.212339, 0.183405, 0.524756, 0.291229]))
4 0.601115 0.708073 True <- np.any(0.601115 < np.array([0.969910, 0.212339, 0.183405, 0.524756, 0.291229]))
5 0.020584 0.969910 True <- np.any(0.020584 < np.array([0.212339, 0.183405, 0.524756, 0.291229]))
6 0.832443 0.212339 False <- np.any(0.832443 < np.array([0.183405, 0.524756, 0.291229]))
7 0.181825 0.183405 True <- np.any(0.181825 < np.array([0.524756, 0.291229]))
8 0.304242 0.524756 False <- np.any(0.304242 < np.array([0.291229]))
9 0.431945 0.291229 UNDEFINED <- Ignore this
(下記の行の一部の説明を参照)が、それをするパンダ/ numpyの方法は何ですか?
私はa
にラムダ関数を適用するアプローチをしようとしていたが、lは上記のようnp.any
比較を行うために、それぞれのa
値のインデックスを取得する方法を見つけることができませんでした。
df['c'] = df['a'].apply(lambda x: np.any(x < df['b'].values[<i>:])) # Where <i> is the respective index value of x; which I didn't know how to find
がシフトが必要な場合があります。シフト(1) '? – Divakar
ありがとう@Divakar!見逃した。 .df ['b'] [:: - 1] .cummax()[:: - 1] .reset_index(drop = True).shift(-1) 'を追加しました。ここでは 'df ['a']'をシフトできないと思う。 – akilat90