我有一个数据框,其中有一列包含个人姓名。姓名并不总是采用相同的格式,因此我尝试将名字和姓氏分成单独的列。例如,我可能会看到:
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]
问题是我收到错误“ValueError:值的长度与索引的长度不匹配”
最佳答案
正如 @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]
See docs请注意 n
参数将拆分限制为一次。
关于python - Pandas Dataframe str split max,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59775009/