>我有一个数据帧,其中有一列包含个人名称。名称并不总是采用相同的格式,因此我尝试将名字和姓氏拆分为单独的列。例如,我可能会看到:
Smith John
Smith, John
Smith, John A
Smith John A
Smith John and Jane
一致的模式是姓氏在前。如何为姓氏创建两个单独的字段,然后是第二列,该列不是姓氏。这是我到目前为止所拥有的
owners_df['normal_name'] = owners_df['name'].str.replace(', ', ' ')
owners_df['lastname'] = owners_df["normal_name"].str.split(' ', 1)[0]
owners_df['firstname'] = owners_df["normal_name"].str.split(' ', 1)[1]
问题是我收到错误"值错误:值的长度与索引的长度不匹配">
正如@Datanovice评论中已经说过的那样"当你运行这个owners_df["normal_name"].str.split(' ', 1)[0]
你只抓住第一行">
使用.str
访问器获取预期输出
owners_df['lastname'] = owners_df["normal_name"].str.split(' ', n=1).str[0]
owners_df['firstname'] = owners_df["normal_name"].str.split(' ', n=1).str[1]
查看文档 请注意n
参数以将拆分限制为一次。
你正在寻找分手后的.str[0]
和.str[1:]
。
ser=pd.Series(['Smith John',
'Smith John',
'Smith John A',
'Smith John A',
'Smith John and Jane'])
ser.str.split(' ').str[0]
0 Smith
1 Smith
2 Smith
3 Smith
4 Smith
#leaving off the .str.join will give a list, which may be preferable in some use cases
ser.str.split(' ').str[1:].str.join(' ')
0 John
1 John
2 John A
3 John A
4 John and Jane
相反,如果您只想将每个元素移动到单独的列中,则可以传递expand=True
ser.str.split(' ', expand=True)
0 1 2 3
0 Smith John None None
1 Smith John None None
2 Smith John A None
3 Smith John A None
4 Smith John and Jane