前提・実現したいこと
forループ等の処理によって、下記col_0のユニークな値毎にcol_1の累積数を、col2に代入したいです。
ソースコード
python
1import pandas as pd 2df_sample = pd.DataFrame({ 3 "col_0": ["A", "A", "A", "A", "B", "B", "C"], 4 "col_1": [1, 1, 1, 1, 1, 1, 1], 5 "col_2": [0, 0, 0, 0, 0, 0, 0]}) 6display(df_sample) 7 8# 計算結果 9# col_0 col_1 col2 10#0 A 1 0 11#1 A 1 0 12#2 A 1 0 13#3 A 1 0 14#4 B 1 0 15#5 B 1 0 16#6 C 1 0 17 18 19# 処理 20xxx 21 22# 期待したい計算結果 23# col_0 col_1 col2 24#0 A 1 1 25#1 A 1 2 26#2 A 1 3 27#3 A 1 4 28#4 B 1 1 29#5 B 1 2 30#6 C 1 1
試したこと
python
1tmp = list(df_sample["col_0"].unique()) 2for idx in df_sample.index: 3 if df_sample.loc[idx, "col_0"] in tmp: 4 df_sample.loc[idx,"col_2"] += 1 5 else: 6 continue 7display(df_sample) 8 9# 計算結果 10# col_0 col_1 col2 11#0 A 1 1 12#1 A 1 1 13#2 A 1 1 14#3 A 1 1 15#4 B 1 1 16#5 B 1 1 17#6 C 1 1
調査しましたが、上手い参考例が見当たりませんでした。
ご教授のほど、よろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー