Skip to main content
 首页 » 编程设计

python之如何根据另一列中的条件转置一列

2025年05月04日15telwanggs

我确定之前有人问过这个问题(因为这是一个常见问题),但我找不到。

所以我的数据框看起来像这样:

ID     Name 
1      A 
1      B 
2      X 
2      Y 
2      Z 

我想要这种格式(我不关心列名)

1    A    B 
2    X    Y   Z  and so on... 

请您参考如下方法:

通过 DataFrame.set_index 创建 MultiIndex带柜台 GroupBy.cumcount并通过 Series.unstack reshape 与 DataFrame.reset_index对于 index 中的列:

df1 = (df.set_index(['ID',df.groupby('ID').cumcount()])['Name'] 
         .unstack(fill_value='') 
         .reset_index()) 
print (df1) 
   ID  0  1  2 
0   1  A  B    
1   2  X  Y  Z 

在小型 DataFrame 中执行:

np.random.seed(123) 
N = 1000 
L = list('abcdefghijklmno') 
df = pd.DataFrame({'Name': np.random.choice(L, N), 
                   'ID':np.random.randint(100, size=N)}).sort_values('ID') 
#print (df) 
 
In [15]: %%timeit 
    ...: df_new=df.groupby('ID')['Name'].apply(lambda x: ','.join(list(x))).reset_index() 
    ...: df_new.join(df_new.pop('Name').str.split(",",expand=True)) 
    ...:  
22 ms ± 411 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) 
 
In [16]: %%timeit 
    ...: df1 = (df.set_index(['ID',df.groupby('ID').cumcount()])['Name'] 
    ...:          .unstack(fill_value='') 
    ...:          .reset_index()) 
    ...:  
6.05 ms ± 212 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 
 
In [17]: %%timeit 
    ...: df.set_index('ID').groupby('ID').apply(lambda x: x.reset_index(drop=True).T).reset_index(level=1,drop=True) 
    ...:  
151 ms ± 1.25 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)