我敢肯定这是以前被问过的(因为这是一个常见问题),但是我找不到它。
所以我的数据框看起来像这样:
ID Name
1 A
1 B
2 X
2 Y
2 Z
我想要这种格式(我不在乎列名)
1 A B
2 X Y Z and so on...
创建MultiIndex
通过DataFrame.set_index
由计数器GroupBy.cumcount
和重塑通过Series.unstack
与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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句