使用pandas.Series.str.split可以按空格字符" "拆分Fullname列,n=-1表示返回所有拆分的单词。所以,使用df["Fullname"].str.split(" ", n = -1, expand = True)的完整工作示例
import pandas as pd
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
df = pd.DataFrame({'Name': {0: ' Braund', 1: ' Heikkinen', 2: ' Allen', 3: ' Moran', 4: ' McCarthy'}, 'Fullname': {0: ' Mr. Owen Harris ', 1: ' Miss. Laina ', 2: ' Mr. William Henry ', 3: ' Mr. James ', 4: ' Mr. Timothy J '}, 'num': {0: 1, 1: 0, 2: 0, 3: 0, 4: 0}})
new = df["Fullname"].str.split(" ", n = -1, expand = True)
# making seperate title column from new data frame
df["Title"]= new[1]
# making seperate first name column from new data frame
df["First Name"]= new[2]
# making seperate last name column from new data frame
df["Last Name"]= new[3]
print(df.head())
print(df)
Name Fullname num Title First_name
0 Braund Mr. Owen Harris 1 Mr. Owen Harris
1 Heikkinen Miss. Laina 0 Miss. Laina
2 Allen Mr. William Henry 0 Mr. William Henry
3 Moran Mr. James 0 Mr. James
4 McCarthy Mr. Timothy J 0 Mr. Timothy J
使用pandas.Series.str.split可以按空格字符
" "
拆分Fullname
列,n=-1
表示返回所有拆分的单词。所以,使用df["Fullname"].str.split(" ", n = -1, expand = True)
的完整工作示例输出:
^{pr2}$要点:使用函数
str.split(' ', n=1, expand=True)
我在你的例子中没有看到姓,所以我只做了一个分割。您可以使用参数n=1或n=2等来生成任意多个
首先:strip从你的名字中多出一些空格,然后split名字在第一个空格上:
然后:使用pd.concat()将此拆分名称添加到数据帧:
^{pr2}$结果:
相关问题 更多 >
编程相关推荐