【问题标题】:How to reorder timestamps in multiple columns into a single column python如何将多列中的时间戳重新排序为单列python
【发布时间】:2018-12-21 08:08:15
【问题描述】:

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

所以对于下面的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

除了第一排,其他都是有序的?

【问题讨论】:

    标签: python pandas sorting dataframe merge


    【解决方案1】:

    试试这个:

    newdf = pd.DataFrame(np.repeat(df.T.values,3,axis=1)).T
    newdf.columns=df.columns
    newdf['new']=list(set(df['A']))+list(set(df['B']))+list(set(df['C']))
    newdf['']=newdf[''][::3].tolist()*3
    newdf['n']=sorted([1,2,3]*3)
    newdf=newdf[['','n','new']]
    print(newdf)
    

    输出:

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

    【讨论】:

    • 感谢@U9-Forward。我似乎无法对此进行排序?我正在使用newdf = newdf.sort_values(by='new',ascending=True)
    【解决方案2】:

    IIUC

    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
    

    【讨论】:

    • 谢谢@Wen。你有什么版本的熊猫。我有 0.19.2。我收到一个错误 AttributeError: 'DataFrame' object has no attribute 'melt'
    • @Punter345 然后你可以试试 pd.melt 我在 0.20.0
    • @Punter345 融化后,您可以将 pd.time_delta 应用于 value 列,更改后它们是 sort_values
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2018-01-13
    相关资源
    最近更新 更多