熊猫的全名分为一个,中间和姓氏
我有一个带有FullNames字段的Pandas DataFrame,我想更改逻辑,以便第一个和姓氏将具有所有第一个和最后一个字,其余的将进入中间名字段。
注意:全名可以包含两个单词,在这种情况下,中间名将为null,名称之间也可能有额外的空间。
当前逻辑:
fullnames = "Walter John Ross Schmidt"
first, middle, *last = name.split()
print("First = {first}".format(first=first))
print("Middle = {middle}".format(middle=middle))
print("Last = {last}".format(last=" ".join(last)))
Output :
First = Walter
Middle = John
Last = Ross Schmidt
预期输出:
FirstName = Walter
Middle = John Ross
Last = Schmidt
I have a pandas dataframe with a fullnames field, I want to change the logic so that the First and Last name will have all the first and last word and the rest will go into the middle name field.
Note: The full name can contain two words in that case middle name will be null and there may be also extra spaces between the names.
Current Logic:
fullnames = "Walter John Ross Schmidt"
first, middle, *last = name.split()
print("First = {first}".format(first=first))
print("Middle = {middle}".format(middle=middle))
print("Last = {last}".format(last=" ".join(last)))
Output :
First = Walter
Middle = John
Last = Ross Schmidt
Expected Output :
FirstName = Walter
Middle = John Ross
Last = Schmidt
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用否定索引获取姓氏列表中的最后一项,还可以使用切片来获取中间名的第一个和最后一个:
PS,如果您使用数据框架,则可以使用:
输出:输出:
You can use negative indexing to get the last item in the list for the last name and also use a slice to get all but the first and last for the middle name:
PS if you are working with a data frame you can use:
Output:
您可以使用传递给
str.extract()
的捕获组中的捕获组,这将使您在一个操作中执行此操作:这给您:
You can use capture groups in the regex passed to
str.extract()
, which will let you do this in a single operation:This gives you:
我将使用
str.Replace
和str.stract
在这里:I would use
str.replace
andstr.extract
here:您可以使用以下行。
You can use the following line instead.