Skip to main content
 首页 » 编程设计

python之如何将多列中的时间戳重新排序为单列python

2024年12月31日8zhoujg

我正在尝试将 pandas df 中多个 columns 的 timestamps 排序为单个时间顺序 列。

所以对于下面的 df,我想将它们组合起来创建一列

import pandas as pd 
 
d = ({ 
    '' : ['Bar','Foo','Fubar'], 
    'A' : ['8:00','8:29','8:58'],         
    'B' : ['8:30','8:59','9:28'],             
    'C' : ['9:00','9:29','10:00'],  
    }) 
 
df = pd.DataFrame(data=d) 

输出:

             A     B      C 
0    Bar  8:00  8:30   9:00 
1    Foo  8:29  8:59   9:29 
2  Fubar  8:58  9:28  10:00 

预期输出:

       1  2      3 
0    Bar  1   8:00 
1    Foo  1   8:29 
2    Bar  2   8:30 
3  Fubar  1   8:58 
4    Foo  2   8:59 
5    Bar  3   9:00 
6  Fubar  2   9:28 
7    Foo  3   9:29 
8  Fubar  3  10:00 

我可以通过 df = df.sort_values(by='1',ascending=True) 对它们进行排序,但我需要以某种方式合并它们。我努力了;

df =  df.sum(axis=1) 

我也尝试过类似的加入方法,但结果总是这样

0       Bar8:008:309:00 
1       Foo8:298:599:29 
2    Fubar8:589:2810:00 

更新:

使用@Wen 的代码我得到以下输出

df.columns=['',1,2,3] 
df = pd.melt(df, '') 
df = df.sort_values(by='value',ascending=True) 
 
         variable  value 
8  Fubar        3  10:00 #All ordered except for the first row? 
0    Bar        1   8:00 
1    Foo        1   8:29 
3    Bar        2   8:30 
2  Fubar        1   8:58 
4    Foo        2   8:59 
6    Bar        3   9:00 
5  Fubar        2   9:28 
7    Foo        3   9:29 

除了第一行,其他的都排序了吗?

请您参考如下方法:

国际联合会

df.columns=['',1,2,3] 
df.melt('') 
Out[99]:  
         variable  value 
0    Bar        1   8:00 
1    Foo        1   8:29 
2  Fubar        1   8:58 
3    Bar        2   8:30 
4    Foo        2   8:59 
5  Fubar        2   9:28 
6    Bar        3   9:00 
7    Foo        3   9:29 
8  Fubar        3  10:00