gpt4 book ai didi

python - 如何不按行排序值,而是按 Pandas 中的列排序?

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:58 25 4
gpt4 key购买 nike

假设我有这个数据框。

df = pd.DataFrame([['A-store',5,'B-store',4,'C-store',6], \
['B-store',3,'P-store',4,np.nan,np.nan], \
['N-store',20,np.nan,np.nan,'I-store',9], \
['L-store',8,'N-store',2,'A-store',5]],
columns=['store_1','time_1','store_2','time_2','store_3','time_3'])
   store_1  time_1  store_2  time_2  store_3  time_3
0 A-store 5 B-store 4.0 C-store 6.0
1 B-store 3 P-store 4.0 NaN NaN
2 N-store 20 NaN NaN I-store 9.0
3 L-store 8 N-store 2.0 A-store 5.0

例如:到 A 店需要 5 分钟。

如何对值集(商店、时间)进行排序,以便最左边的值集最短,最右边的值集最长。我需要对多列值集进行排序。此外,它还包括 NaN。

这是理想的输出。

shorter <----------------------------------->  longer
store_1 time_1 store_2 time_2 store_3 time_3
0 B-store 4.0 A-store 5 C-store 6.0
1 B-store 3 P-store 4.0 NaN NaN
2 I-store 9.0 N-store 20 NaN NaN
3 N-store 2.0 A-store 5.0 L-store 8

我可能可以旋转或堆叠,然后按行排序。但是,我不确定该怎么做。

如果有人有任何好的想法或代码,请告诉我。

谢谢!

最佳答案

想法是用 Series.str.split reshape 值和 DataFrame.stack ,然后按第一级和 time 列排序,按 GroupBy.cumcount 创建新订单最后 reshape 回原来的形状:

df.columns = df.columns.str.split('_', expand=True)

df1=df.stack().reset_index(level=1,drop=True).rename_axis('lvl1').sort_values(['lvl1','time'])
df1 = df1.set_index(df1.groupby(level=0).cumcount().add(1), append=True)

df1 = df1.unstack().sort_index(axis=1, level=1).rename_axis(None)
df1.columns = [f'{a}_{b}' for a, b in df1.columns]
print (df1)
store_1 time_1 store_2 time_2 store_3 time_3
0 B-store 4.0 A-store 5.0 C-store 6.0
1 B-store 3.0 P-store 4.0 NaN NaN
2 I-store 9.0 N-store 20.0 NaN NaN
3 N-store 2.0 A-store 5.0 L-store 8.0

关于python - 如何不按行排序值,而是按 Pandas 中的列排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58497035/

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