[英]How to slice pandas column with index list?
我正在嘗試從 dataframe 中的字符串中提取前兩個單詞
df[“姓名”]
Name
Anthony Frank Hawk
John Rodney Mullen
Robert Dean Silva Burnquis
Geoffrey Joseph Rowley
為了獲得第二個“”(空格)的索引,我嘗試了這個,但發現返回 NaN 而不是返回字符數,直到第二個空格。
df["temp"] = df["Name"].str.find(" ")+1
df["temp"] = df["Status"].str.find(" ", start=df["Status"], end=None)
df["temp"]
0 NaN
1 NaN
2 NaN
3 NaN
最后一步是對這些名稱進行切片,我嘗試使用此代碼但不起作用。
df["Status"] = df["Status"].str.slice(0,df["temp"])
df["Status"]
0 NaN
1 NaN
2 NaN
3 NaN
expected return
0 Anthony Frank
1 John Rodney
2 Robert Dean
3 Geoffrey Joseph
如果您有更有效的方法,請告訴我?
df['temp'] = df.Name.str.rpartition().get(0)
df
Output
Name temp
0 Anthony Frank Hawk Anthony Frank
1 John Rodney Mullen John Rodney
2 Robert Dean Silva Burnquis Robert Dean Silva
3 Geoffrey Joseph Rowley Geoffrey Joseph
編輯
如果 output 中只需要前兩個元素。
df['temp'] = df.Name.str.split().str[:2].str.join(' ')
df
或者
df['temp'] = df.Name.str.split().apply(lambda x:' '.join(x[:2]))
df
或者
df['temp'] = df.Name.str.split().apply(lambda x:' '.join([x[0], x[1]]))
df
Output
Name temp
0 Anthony Frank Hawk Anthony Frank
1 John Rodney Mullen John Rodney
2 Robert Dean Silva Burnquis Robert Dean
3 Geoffrey Joseph Rowley Geoffrey Joseph
可以使用 str.index(substring) 代替 str.find,它返回在字符串中找到的子字符串的最小索引(如“”、空格)。 然后,您可以按該索引拆分字符串,並將上述內容重新應用於結果列表中的第二個字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.