実現したいこと
group列のグループごとの最終行に値を代入したいのですが、
最終行に値「1」を代入(それ以外は0)するところまではできたのですが、
groupごとにする方法を教えて頂けませんでしょうか
該当のソースコード
import pandas as pd df = pd.DataFrame({'group':['A','A','B','B'],'col1': [0, 3, 2, 3], 'col2': [4, 0, 2, 1]}) df['col3'] = np.where(df.index == df.index[-1], '1','0')
<追加>
下記のように条件を追加したい場合を試してはみたのですが、うまくいかず…
1度に質問すべきだったのですが、申し訳ありません。
import pandas as pd df = pd.DataFrame({'group':['A','A','B','B'],'col1': [0, 3, 2, 3], 'col2': [4, 0, 2, 1]}) df['col3'] ="" df.loc[(df.groupby('group').tail(1).index) & (df['group']=='A'), 'col3'] = "1"
IndexError: Boolean index has wrong length: 2 instead of 4
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/11/28 11:01
2022/11/28 11:09
2022/11/28 13:35