# 使用重复的值来增加列 [关闭]Use duplicated values to increment column [closed]

SM
0  AB
1  AC
3  AB
4  AB
5  AC
6  AE

SM DM
0  AB AB
1  AC AC
3  AB AB_1
4  AB AB_2
5  AC AC_1
6  AE AE

np.where(a.SM.duplicated(keep='first'), a.SM+'_1', a.SM)

## 2 个回复2

### #1楼 票数：2 已采纳

s = df.groupby('SM').cumcount()

df['DM'] = df['SM'].where(s.eq(0), df['SM'] + '_' + s.astype(str))

[出去]

SM    DM
0  AB    AB
1  AC    AC
3  AB  AB_1
4  AB  AB_2
5  AC  AC_1
6  AE    AE

### #2楼 票数：1

dplyr按组创建 counter-1 然后paste()可以为您提供想要的结果：

library(dplyr)
library(tidyr)
# Getting those whose value which Are repeated
df\$BoolDup<-duplicated(df\$SM)
# Creating counting variable and a second counter that keeps track of the repetitions-1 to then Join if duplicated
df %>% mutate(count = 1) %>%
group_by(SM)%>%
mutate(count2 = cumsum(count)-1) %>%
mutate(DM = ifelse(BoolDup==TRUE,paste(SM,"_",count2,sep =""), SM))%>%
dplyr::select(SM=SM, DM=DM)

# A tibble: 8 x 2
# Groups:   SM [4]
# SM    DM
# <chr> <chr>
# 1 AB    AB
# 2 AC    AC
# 4 AB    AB_1
# 5 AB    AB_2
# 6 AC    AC_1
# 7 AE    AE

1回复

2回复

2回复

2回复

1回复

1回复

3回复

2回复