【问题标题】:Convert Python Dataframe in 1 Line Dataframe where columns and index values are concatinated在列和索引值连接的 1 行数据框中转换 Python 数据框
【发布时间】:2017-05-16 20:04:08
【问题描述】:

我有以下结构,但要大得多

    1y   2y   3y
1w  2    8    40
2w  3    10   50 
1m  4    12   60

在python中有什么快速将其转换为单行数据帧的好方法:

         1w/1y  1w/2y  1w/3y  2w/1y  2w/2y  2w/3y  1m/1y  1m/2y  1m/3y
NewIndex  2       8     40     3       10    50     4       12    60

新索引最终将是日期,因为我将以下数据存储在每个日期的单独 CSV 中,我想将其转换为单个数据框以对其运行一些统计信息。

非常感谢
Here's the image as the text got misaligned. https://i.stack.imgur.com/K3s7V.png

【问题讨论】:

    标签: python python-2.7 pandas dataframe


    【解决方案1】:
    In [16]: x = df.stack()
    
    In [17]: x
    Out[17]:
    1w  1y     2
        2y     8
        3y    40
    2w  1y     3
        2y    10
        3y    50
    1m  1y     4
        2y    12
        3y    60
    dtype: int64
    
    In [18]: new = pd.DataFrame(x.values, index=x.index.map('/'.join)).T
    
    In [19]: new
    Out[19]:
       1w/1y  1w/2y  1w/3y  2w/1y  2w/2y  2w/3y  1m/1y  1m/2y  1m/3y
    0      2      8     40      3     10     50      4     12     60
    

    或更好,无需转置:

    In [30]: new = pd.DataFrame(x.values[None, :], columns=x.index.map('/'.join), index=[0])
    
    In [31]: new
    Out[31]:
       1w/1y  1w/2y  1w/3y  2w/1y  2w/2y  2w/3y  1m/1y  1m/2y  1m/3y
    0      2      8     40      3     10     50      4     12     60
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-11
    • 2018-01-31
    • 2019-10-13
    • 2020-10-16
    • 1970-01-01
    • 2022-12-17
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多