【问题标题】:Separate data from one column into three columns将数据从一列分成三列
【发布时间】:2016-12-11 05:39:08
【问题描述】:

我在 Excel 中有一个列,其中包含名字、姓氏和职位的混合。唯一可以观察到的模式是 - 在每组 3 行中,第 1 行是名字,第 2 行是姓氏,第 3 行是职位。我想创建 3 个不同的列并隔离这些数据 样本数据:

John
Bush
Manager
Katrina
Cohn
Secretary 

我想要: John 、 Bush 、 Manager 作为一行,分别在 First Name、Last name 和 Job title 下的三个不同列中。喜欢 -

First Name   Last Name    Job Title
John         Bush         Manager
Katrina      Cohn         Secretary 

我们怎样才能完成这项任务?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以使用this notation 获取具有不同起点的每三个元素。

    l = ['John', 'Bush', 'Manager', 'Katrina', 'Cohn', 'Secretary']
    
    pd.DataFrame({'First Name': l[::3], 'Last Name': l[1::3], 'Job Title': l[2::3]})
    

    输出

      First Name  Job Title Last Name
    0       John    Manager      Bush
    1    Katrina  Secretary      Cohn
    

    【讨论】:

    • ValueError: 数组的长度必须相同
    【解决方案2】:
    s = pd.Series([
            'John',
            'Bush',
            'Manager',
            'Katrina',
            'Cohn',
            'Secretary'])
    
    df = pd.DataFrame(s.values.reshape(-1, 3),
                      columns=['First Name', 'Last Name', 'Job Title'])
    
    df
    


    如果您的数据长度不是 3 的倍数,那么您可以像这样强制它:

    s = pd.Series([
            'John',
            'Bush',
            'Manager',
            'Katrina',
            'Cohn',
            'Secretary',
            'Bogus'])
    
    s_ = s.iloc[:s.shape[0] // 3 * 3]
    df = pd.DataFrame(s_.values.reshape(-1, 3), columns=['First Name', 'Last Name', 'Job Title'])
    
    df
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多