【问题标题】:split columns and name them using pandas拆分列并使用 pandas 命名它们
【发布时间】:2015-03-31 02:48:55
【问题描述】:

我想根据分隔符 ":" 将一列拆分为 3,我可以做到 使用下面的代码。但是现在想改分裂的名字 列从默认的 1,2,3,4。请建议我如何做到这一点。

from pandas import *
df = DataFrame(
     {'CustomerName' : ["Paul", "John"], 'Seatblocks' : ["2:218:10:4,6","2:218:10:4,6"]}); 
df

df.join(df.Seatblocks.apply(lambda x: Series(x.split(':'))))

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    人们已经给出了rename 的方法,但我发现如果你避免将所有内容都塞进一行的诱惑,这些事情会更容易。一旦你有了一个框架,你可以简单地分配给.columns

    >>> sb = df.Seatblocks.str.split(":").apply(pd.Series)
    >>> sb.columns = ["a", "Three Digit", "??", "coord"]
    >>> pd.concat([df, sb], axis=1)
      CustomerName    Seatblocks  a Three Digit  ?? coord
    0         Paul  2:218:10:4,6  2         218  10   4,6
    1         John  2:218:10:4,6  2         218  10   4,6
    

    第一行只是您的(df.Seatblocks.apply(lambda x: Series(x.split(':')))) 的一个版本,它利用了矢量化字符串操作访问器.str (docs)。

    【讨论】:

      【解决方案2】:

      rename他们:

      df.rename(columns={0:'col_1', 1:'col_2', 2:'col_3', 3:'col_4'},inplace=True)
      

      一种更晦涩的方法是将新名称合并到列的前 2 个元素并直接分配:

      In [14]:
      
      df.columns = df.columns[:2] | pd.Index(['col_1', 'col_2', 'col_3', 'col_4'])
      df
      Out[14]:
        CustomerName    Seatblocks col_1 col_2 col_3 col_4
      0         Paul  2:218:10:4,6     2   218    10   4,6
      1         John  2:218:10:4,6     2   218    10   4,6
      

      【讨论】:

        【解决方案3】:

        列重命名为 A、B、C、D。

        from pandas import *
        df = DataFrame(
             {'CustomerName' : ["Paul", "John"], 'Seatblocks' : ["2:218:10:4,6","2:218:10:4,6"]}); 
        df = df.join(df.Seatblocks.apply(lambda x: Series(x.split(':'))))
        df.rename(columns={0: 'A', 1: 'B', 2: 'C', 3: 'D'}, inplace=True)
        df
        

        【讨论】:

          【解决方案4】:

          你可以修改df.column来获取新的列名

          In [1]: from pandas import *
          
          In [2]: df = DataFrame(
             ...:      {'CustomerName' : ["Paul", "John"], 'Seatblocks' : ["2:218:10:4,6","2:218:10:4,6"]}); 
          
          In [3]: df2 = df.join(df.Seatblocks.apply(lambda x: Series(x.split(':'))))
          
          In [4]: names = ['foo', 'bar', 'baz', 'booz']
          
          In [5]: df2.columns = [x if str(x).isalpha() else names.pop() for x in df2.columns]
          
          In [6]: df2.columns                                              
          Out[6]: Index([u'CustomerName', u'Seatblocks', u'booz', u'baz', u'bar', u'foo'], dtype='object')
          
          In [7]: 
          

          【讨论】:

            【解决方案5】:

            这可能会有所帮助:

            import pandas as pd
            import numpy as np
            
            df = pd.DataFrame(
                 {'CustomerName' : ["Paul", "John"], 'Seatblocks' : ["2:218:10:4,6","2:218:10:4,6"]}); 
            #df
            #1.split, rename
            df_extraction = df['Seatblocks'].str.split(':', expand=True)
            df_extraction.columns = ['seatBlock'+str(i) for i in df_extraction.columns]
            
            # 2.merge extracted to df
            df = pd.concat([df, df_extraction], axis=1)
            df
            
            CustomerName    Seatblocks  seatBlock0  seatBlock1  seatBlock2  seatBlock3
            0   Paul    2:218:10:4,6    2   218     10  4,6
            1   John    2:218:10:4,6    2   218     10  4,6
            

            【讨论】:

            • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
            猜你喜欢
            • 2020-12-16
            • 1970-01-01
            • 2021-11-25
            • 2018-08-04
            • 2020-12-21
            • 2012-09-25
            • 2014-09-25
            • 1970-01-01
            • 2016-01-05
            相关资源
            最近更新 更多