DIEA
使用factorize并滚动相应的值def swaparoo(col): i, r = col.factorize() return pd.Series(r[(i + 1) % len(r)], col.index)df[['id']].join(df[['val1', 'val2']].apply(swaparoo)) id val1 val20 0 B A1 1 A A2 2 B B3 3 B B替代体操使用相同的功能。这将整个数据帧合并到分解中。df.set_index('id').stack().pipe(swaparoo).unstack().reset_index()例子df = pd.DataFrame(dict(id=range(4), val1=[*'ABAA'], val2=[*'BBAA']))print( df, df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(), sep='\n\n') id val1 val20 0 A B1 1 B B2 2 A A3 3 A A id val1 val20 0 B A1 1 A A2 2 B B3 3 B Bdf = pd.DataFrame(dict(id=range(4), val1=[*'AAAA'], val2=[*'BBBB']))print( df, df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(), sep='\n\n') id val1 val20 0 A B1 1 A B2 2 A B3 3 A B id val1 val20 0 B A1 1 B A2 2 B A3 3 B Adf = pd.DataFrame(dict(id=range(4), val1=[*'AAAA'], val2=[*'BBBB'], val3=[*'CCCC']))print( df, df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(), sep='\n\n') id val1 val2 val30 0 A B C1 1 A B C2 2 A B C3 3 A B C id val1 val2 val30 0 B C A1 1 B C A2 2 B C A3 3 B C Adf = pd.DataFrame(dict(id=range(4), val1=[*'ABCD'], val2=[*'BCDA'], val3=[*'CDAB']))print( df, df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(), sep='\n\n') id val1 val2 val30 0 A B C1 1 B C D2 2 C D A3 3 D A B id val1 val2 val30 0 B C D1 1 C D A2 2 D A B3 3 A B C