计算按日期和标签分组的行中列表元素的频率

Count the frequency of list element in a row grouped by Date and tag

我有一个数据框 df,它看起来像这样:

ID       Date        Input
   1         1-Nov       A,B
   1         2-NOV       A
   2         3-NOV       A,B,C
   2         4-NOV       B,D

我希望我的输出计算每个输入的出现次数,如果它是连续的,否则再次将其重置为零(如果 ID 相同则只计数),并且输出应重命名为 X.A, X.B、X.C 和 X.D 所以我的输出将如下所示:

ID      Date       Input      X.A      X.B      X.C      X.D
   1       1-NOV      A,B        1      1      0      0
   1       2-NOV      A          2      0      0      0
   2       3-NOV      A,B,C      1      1      1      0
   2       4-NOV      B,D        0      2      0      1

我如何创建输出(A、B、C 和 D)来计算输入的发生日期和 ID。

使用Series.str.get_dummies for indicator columns and then count consecutive 1 per groups - so use GroupBy.cumsum with subtract by GroupBy.ffill, change columns names by DataFrame.add_prefix and last DataFrame.join 为原文:

a = df['Input'].str.get_dummies(',') == 1
b = a.groupby(df.ID).cumsum().astype(int)
df1 = (b-b.mask(a).groupby(df.ID).ffill().fillna(0).astype(int)).add_prefix('X.')

df = df.join(df1)
print (df)
   ID   Date  Input  X.A  X.B  X.C  X.D
0   1  1-Nov    A,B    1    1    0    0
1   1  2-NOV      A    2    0    0    0
2   2  3-NOV  A,B,C    1    1    1    0
3   2  4-NOV    B,D    0    2    0    1

首先添加新列的计数,然后使用 group by 进行累加和

# find which columns to add
cols = set([l for sublist in df['Input'].apply(lambda x: x.split(',')).values for l in sublist])

# add the new columns
for col in cols:
    df['X.' + col] = df['Input'].apply(lambda x: int(col in x))

# group by and add cumulative sum conditional it has a positive value
group = df.groupby('ID')
for col in cols:
    df['X.' + col] = group['X.' + col].apply(lambda x: np.cumsum(x) * (x > 0).astype(int))

结果是

print(df)
   ID   Date  Input  X.C  X.D  X.A  X.B
0   1  1-NOV    A,B    0    0    1    1
1   1  2-NOV      A    0    0    2    0
2   2  3-NOV  A,B,C    1    0    1    1
3   2  4-NOV    B,D    0    1    0    2