gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:50:47 26 4
gpt4 key购买 nike

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

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

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)

关于python - 如何根据另一列中的条件转置一列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55085042/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com