【问题标题】:Transpose rows to column with limit of special character将行转置到具有特殊字符限制的列
【发布时间】:2020-07-14 05:16:21
【问题描述】:

数据在需要转置(行)到列中的列中,对特殊字符(如“.”)有限制句号。在每个特殊字符(如“.”)之后,循环重复,直到整列变为行。 ,所以输出如下。

df :

index ID-0 ID-1 info_string
0 4 20 This
1 6 8 is 
2 8 6 an 
3 12 15 apple
4 29 9.
5 45 5 It
6 56 8 is
7 60 10 sweet
8 62 15 .

输出 df_out :

index ID-0 ID-1 info_string
0 4 6 8 12 29 20 8 6 15 9 This is an apple.
1 45 56 60 62 5 8 10 15 It is sweet.

还有。在此之后,再次如何恢复原始状态...

df_out_reverse:

index ID-0 ID-1 info_string
0 4 20 This
1 6 8 is 
2 8 6 an 
3 12 15 apple
4 29 9.
5 45 5 It
6 56 8 is
7 60 10 sweet
8 62 15 .

我尝试了转置,但我无法停止特殊字符。转置完成。

【问题讨论】:

    标签: python pandas transpose


    【解决方案1】:

    从长到宽

    s = df.astype(str).groupby(df['info_string'].iloc[::-1].eq('.').cumsum()).agg(' '.join)
    Out[178]: 
                        ID-0         ID-1         info_string
    info_string                                              
    1            45 56 60 62    5 8 10 15       It is sweet .
    2            4 6 8 12 29  20 8 6 15 9  This is an apple .
    

    从宽到长

    pd.concat([s[x].str.split().explode() for x in s.columns],axis=1)
    Out[184]: 
                ID-0 ID-1 info_string
    info_string                      
    1             45    5          It
    1             56    8          is
    1             60   10       sweet
    1             62   15           .
    2              4   20        This
    2              6    8          is
    2              8    6          an
    2             12   15       apple
    2             29    9           .
    

    【讨论】:

      猜你喜欢
      • 2016-04-29
      • 2019-09-20
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      相关资源
      最近更新 更多