茅侃侃
我们可以做的cumcountdf.Name=df.Name+df.groupby('Name').cumcount().astype(str)df Name Age0 Tom0 201 Tom1 212 Jack0 193 Terry0 18更新suf = lambda n: "%d%s"%(n,{1:"st",2:"nd",3:"rd"}.get(n if n<20 else n%10,"th"))g=df.groupby('Name')df.Name=df.Name.radd(g.cumcount().add(1).map(suf).mask(g.Name.transform('count')==1,''))df Name Age0 1stTom 201 2ndTom 212 Jack 193 Terry 18更新 2 列suf = lambda n: "%d%s"%(n,{1:"st",2:"nd",3:"rd"}.get(n if n<20 else n%10,"th"))g=s.groupby([s.index.get_level_values(0),s])s=s.radd(g.cumcount().add(1).map(suf).mask(g.transform('count')==1,''))s=s.unstack() Name OtherName0 1stTom 2ndTom1 Jerry John2 Jack Bob3 Terry Steve
红颜莎娜
编辑:对于每行重复的计数,请使用:df = pd.DataFrame(data = {'Name':['Tom', 'Jerry', 'Jack', 'Terry'], 'OtherName':['Tom', 'John', 'Bob','Steve'], 'Age':[20, 21, 19, 18]})print (df) Name OtherName Age0 Tom Tom 201 Jerry John 212 Jack Bob 193 Terry Steve 18import inflectp = inflect.engine()#map by function for dynamic counterf = lambda i: p.number_to_words(p.ordinal(i))#columns filled by namescols = ['Name','OtherName']#reshaped to MultiIndex Seriess = df[cols].stack()#counter per groupscount = s.groupby([s.index.get_level_values(0),s]).cumcount().add(1)#mask for filter duplicatesmask = s.reset_index().duplicated(['level_0',0], keep=False).values#filter only duplicates and map, reshape back and add to original datadf[cols] = count[mask].map(f).unstack().add(df[cols], fill_value='')print (df) Name OtherName Age0 firstTom secondTom 201 Jerry John 212 Jack Bob 193 Terry Steve 18使用GroupBy.cumcountwith Series.map,但仅适用于重复值 by Series.duplicated:data = {'Name':['Tom', 'Tom', 'Jack', 'Terry'], 'Age':[20, 21, 19, 18]} df = pd.DataFrame(data)nth = {0: "First",1: "Second",2: "Third",3: "Fourth"}mask = df.Name.duplicated(keep=False)df.loc[mask, 'Name'] = df[mask].groupby('Name').cumcount().map(nth) + df.loc[mask, 'Name']print (df) Name Age0 FirstTom 201 SecondTom 212 Jack 193 Terry 18动态字典应该是这样的:import inflectp = inflect.engine()mask = df.Name.duplicated(keep=False)f = lambda i: p.number_to_words(p.ordinal(i))df.loc[mask, 'Name'] = df[mask].groupby('Name').cumcount().add(1).map(f) + df.loc[mask, 'Name']print (df) Name Age0 firstTom 201 secondTom 212 Jack 193 Terry 18