如何不按行排序,而是按列排序?

2024-04-25 21:57:58 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这个数据帧。你知道吗

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分钟。你知道吗

如何对值集(存储、时间)进行排序,使最左边的值集变为最短的值集,最右边的值集变为最长的值集。我需要对值集进行多列排序。此外,它还包括南。你知道吗

这是理想的输出。你知道吗

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

我可能会旋转或堆叠,并按行排序。但是,我不知道怎么做。你知道吗

如果有人有任何好的想法或代码,让我知道。你知道吗

谢谢!你知道吗


Tags: columns数据storedataframedftime排序np
2条回答

这也许是一个较长的方法。也许有人能给你一个更好的方法。但这会提供您需要的输出。你知道吗

import pandas as pd
import numpy as np
import operator

def func(lst):
    d = ({lst[i]: lst[i + 1] for i in range(0, len(lst), 2)})
    d = sorted(d.items(), key=operator.itemgetter(1))
    return [val for sublist in d for val in sublist]

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'])

pd.DataFrame.from_records(df.apply(lambda x : func(x),axis=1) 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   B-store 4.0     A-store 5.0     C-store 6.0
1   B-store 3.0     P-store 4.0     NaN     NaN
2   N-store 20.0    NaN     NaN     I-store 9.0
3   N-store 2.0     A-store 5.0     L-store 8.0

想法是用^{}^{}重塑值,然后按第一级和time列排序,按^{}创建新的顺序,最后重塑为原始:

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

相关问题 更多 >