Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将数据从一列分隔为三列_Python_Pandas - Fatal编程技术网

Python 将数据从一列分隔为三列

Python 将数据从一列分隔为三列,python,pandas,Python,Pandas,我在excel中有一个列,包含名字、姓氏和职务的混合。唯一可以观察到的模式是-在每一组3行中,每第一行是名字,第二行是姓,第三行是职称。我想创建3个不同的列并隔离这些数据 样本数据: John Bush Manager Katrina Cohn Secretary 我想要:约翰,布什,经理,作为一行,分别放在名字,姓氏和职务下面的三个不同的栏中。像- First Name Last Name Job Title John Bush Manager K

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

John
Bush
Manager
Katrina
Cohn
Secretary 
我想要:约翰,布什,经理,作为一行,分别放在名字,姓氏和职务下面的三个不同的栏中。像-

First Name   Last Name    Job Title
John         Bush         Manager
Katrina      Cohn         Secretary 
我们如何完成这项任务?

您可以使用以不同起点获取每三个元素

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


如果数据长度不是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

ValueError:数组必须全部相同长度ValueError:新数组的总大小必须为unchanged@user6461192这意味着序列的长度不是3的倍数。见编辑后的文章。谢谢你的工作。如果我们需要将excel作为输入,而不是对数据进行硬编码,我们该怎么办
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