【问题标题】:How to split a column into many columns where the name of this columns change如何将一列拆分为多个列名称更改的列
【发布时间】:2020-08-15 15:29:02
【问题描述】:

我将一个数据框定义为一个“函数”,其中数据框中每一列的名称不断变化,因此我无法指定该列的名称,然后将其拆分为多列。比如我不能说df ['name']然后拆分成很多列。此数据帧的列数和行数不是恒定的。我需要将包含多个项目的任何列拆分为多个组件(列)。

例如:

这是我拥有的数据框之一:

name/one                                                name/three         

(192.26949,)                                      (435.54,436.65,87.3,5432) 

(189.4033245,)                                (45.51,56.612, 54253.543, 54.321) 

(184.4593252,)                                 (45.58,56.6412,654.876,765.66543) 

我想把它转换成:

name/one                 name/three1      name/three2     name/three3       name/three4 

192.26949                  435.54          436.65            87.3              5432 


189.4033245                45.51           56.612          54253.543          54.321 

184.4593252                45.58           56.6412          654.876          765.66543

【问题讨论】:

    标签: python pandas split multiple-columns


    【解决方案1】:

    如果所有数据都是所有行中的元组并且所有列都使用concatDataFrame构造函数和DataFrame.add_prefix的解决方案:

    df = pd.concat([pd.DataFrame(df[c].tolist()).add_prefix(c) for c in df.columns], axis=1)
    print (df)
        name/one0  name/three0  name/three1  name/three2  name/three3
    0  192.269490       435.54     436.6500       87.300   5432.00000
    1  189.403324        45.51      56.6120    54253.543     54.32100
    2  184.459325        45.58      56.6412      654.876    765.66543
    

    如果可能的话,字符串 repr 的元组:

    import ast
    
    L = [pd.DataFrame([ast.literal_eval(y) for y in df[c]]).add_prefix(c) for c in df.columns]
    df = pd.concat(L, axis=1)
    print (df)
        name/one0  name/three0  name/three1  name/three2  name/three3
    0  192.269490       435.54     436.6500       87.300   5432.00000
    1  189.403324        45.51      56.6120    54253.543     54.32100
    2  184.459325        45.58      56.6412      654.876    765.66543
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 2013-01-23
    相关资源
    最近更新 更多