data = {'Sample':['S1', 'S1', 'S1' ,'S1' ,'S2' ,'S2' ,'S3' ,'S3', 'S4', 'Negative', 'Positive', 'Negative',
'S1', 'S1', 'S1' ,'S2' ,'S2' ,'S2' ,'S3' ,'S4', 'S4', 'Positive', 'Positive', 'Negative'],
'Location':['A1', 'A2', 'A3' ,'A4' ,'A5' ,'A6' ,'A7' ,'A8', 'A9', 'A10', 'A11', 'A12',
'B1', 'B2', 'B3' ,'B4' ,'B5' ,'B6' ,'B7' ,'B8', 'B9', 'B10', 'B11', 'B12']}
df1 = pd.DataFrame(data)
df1
对于上面的示例代码,我想对同一位置组的“Sample”列中的重复项进行计数,并在新的“repeat number”列中为其指定一个重复编号。例如,位置组A中有4个S1,我想给出第一个S1重复编号1和第二个S1重复编号2,依此类推。 对于位置B,有3个S1,给出第一个S1重复编号1和第二个S1重复编号2,依此类推
理想的结果如下所示:
data = {'Sample':['S1', 'S1', 'S1' ,'S1' ,'S2' ,'S2' ,'S3' ,'S3', 'S4', 'Negative', 'Positive', 'Negative',
'S1', 'S1', 'S1' ,'S2' ,'S2' ,'S2' ,'S3' ,'S4', 'S4', 'Positive', 'Positive', 'Negative'],
'Location':['A1', 'A2', 'A3' ,'A4' ,'A5' ,'A6' ,'A7' ,'A8', 'A9', 'A10', 'A11', 'A12',
'B1', 'B2', 'B3' ,'B4' ,'B5' ,'B6' ,'B7' ,'B8', 'B9', 'B10', 'B11', 'B12'],
'Repeat Number':['1', '2', '3' ,'4' ,'1' ,'2' ,'1' ,'2', '1', '1', '1', '2',
'1', '2', '3' ,'1' ,'2' ,'3' ,'1' ,'1', '2', '1', '2', '1',]}
df1 = pd.DataFrame(data)
df1
@ansev的(原始)答案只有在
Sample
列已经相对于Location
列排序时才有效,因为它比较了Sample
和Sample.shift()
如果不是这样,则应首先使用
sort_values
,或同时按Sample
列和df1['Location'].str.extract('(^[A-Z])')
的结果分组:这里有一种使用
.factorize()
和.groupby().rank()
的方法。我创建了临时列来简化groupby()
语句然后,我调用了预期结果
df2
,并用以下方法进行验证:我们可以试试^{}
每次
Sample
更改时,块将从上一行开始递增另一个选择是:
输出
相关问题 更多 >
编程相关推荐