熊猫将行分成多行

时间:2020-06-29 13:45:07

标签: python python-3.x pandas pandas-groupby

我在这样的表/数据框中有一个输入行:

        0                                     1                2       
  1. 期间说明开始日期结束日期2015年8月1日2016年7月31日2016年8月1日2017年7月31日 3 2017年8月1日2018年7月31日

需要的输出:

       0           1        2         3
 1. Start Date 8/1/2015  8/1/2016  8/1/2017  

 2. End Date   7/31/2016 7/31/2017 7/31/2018 

这可能吗?我不确定如何进行此操作,将行分为两行。该列中不需要“期间描述”文本。 其中0、1、2和3列标题。

第0列标题具有:期间说明开始日期结束日期, 第一栏标题为:8/1/2015 7/31/2016, 第二列标题为:8/1/2016 7/31/2017

以此类推...

1 个答案:

答案 0 :(得分:0)

简单的拆分和合并方法就可以了。

>>> a='Period Description Start Date End Date 8/1/2015 7/31/2016 8/1/2016 7/31/2017 8/1/2017 7/31/2018'
>>> a.split()
['Period', 'Description', 'Start', 'Date', 'End', 'Date', '8/1/2015', '7/31/2016', '8/1/2016', '7/31/2017', '8/1/2017', '7/31/2018']
>>> b = a.split()[2:]
>>> b
['Start', 'Date', 'End', 'Date', '8/1/2015', '7/31/2016', '8/1/2016', '7/31/2017', '8/1/2017', '7/31/2018']
>>> c = [' '.join(b[:2]),*b[4:-3]]
>>> c
['Start Date', '8/1/2015', '7/31/2016', '8/1/2016']
>>> d = [' '.join(b[2:4]),*b[-3:]]
>>> d
['End Date', '7/31/2017', '8/1/2017', '7/31/2018']
>>> df = pd.DataFrame([c,d])
>>> df
           0          1          2          3
0  Start Date   8/1/2015  7/31/2016   8/1/2016
1    End Date  7/31/2017   8/1/2017  7/31/2018