我正在寻找设置一个增量计数器与数据帧中的一个组。除非满足条件,否则我希望增加组内每一行的计数器。如果满足条件,我想使用以前的计数。我还希望为每个组重置此设置。
示例:
d1 = {'col1': [1, 1, 1, 2, 2, 3], 'col2': ['A', 'A', 'B', 'A', 'A', 'B']}
df1 = pd.DataFrame(data=d1)
df1输出:
col1 col2
0 1 A
1 1 A
2 1 B
3 2 A
4 2 A
5 3 B预期输出:
col1 col2 count
0 1 A 1
1 1 A 2
2 1 B 2
3 2 A 1
4 2 A 2
5 3 B 0我试过使用numpy cumsum。但我真的不确定如何重用最后的累积量
编辑:查找按列1分组。
发布于 2020-04-01 09:36:47
我根据我认为是你想要的东西做了一个代码片段,如果有些东西并不完全像你期望的那样,你绝对可以重用来适应它。
我认为这里的关键是: 1)迭代(previousRow,currentRow)对,这样您就可以轻松地访问最后一行信息
2)符合您期望的特定if条件。
3)尝试更新if条件中的计数,然后设置该值
import pandas as pd
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
from itertools import zip_longest
d1 = {'col1': [1, 1, 1, 2, 2, 3], 'col2': ['A', 'A', 'B', 'A', 'A', 'B']}
df1 = pd.DataFrame(data=d1)
df1['count'] = 0
df1_previterrows = df1.iterrows()
df1_curriterrows = df1.iterrows()
df1_curriterrows.__next__()
groups_counter = {}
df1_firstRow = df1.iloc[0]
if df1_firstRow["col2"] == "A":
groups_counter[df1_firstRow['col1']]=1
df1.set_value(0, 'count', 1)
elif df1_firstRow["col2"] == "B":
groups_counter["B"]=1
df1.set_value(0, 'count', 0)
zip_list = zip_longest(df1_previterrows, df1_curriterrows)
for (prevRow_idx, prevRow), Curr in zip_list:
if not (Curr is None):
(currRow_idx, currRow) = Curr
if((currRow["col1"] == prevRow["col1"]) and (currRow["col2"] == "A")):
count = groups_counter.get(currRow["col1"],False)
if not count:
groups_counter[currRow["col1"]]=0
groups_counter[currRow["col1"]]+=1
elif((currRow["col1"] != prevRow["col1"]) and (currRow["col2"] == "A")):
groups_counter[currRow["col1"]]=1
elif((currRow["col1"] == prevRow["col1"]) and (currRow["col2"] == "B")):
if not groups_counter.get(currRow["col1"],False):
groups_counter[curr["col1"]] = 1
elif((currRow["col1"] != prevRow["col1"]) and (currRow["col2"] == "B")):
groups_counter[currRow["col1"]]=0
df1.set_value(currRow_idx, 'count', groups_counter[currRow["col1"]])
print(df1)输出:
col1 col2 count
0 1 A 1
1 1 A 2
2 1 B 2
3 2 A 1
4 2 A 2
5 3 B 0https://stackoverflow.com/questions/60961476
复制相似问题