简体   繁体   English

如何使用索引列表对 pandas 列进行切片?

[英]How to slice pandas column with index list?

I'm try extract the first two words from a string in dataframe我正在尝试从 dataframe 中的字符串中提取前两个单词

df["Name"] df[“姓名”]

     Name                            
     Anthony Frank Hawk               
     John Rodney Mullen               
     Robert Dean Silva Burnquis
     Geoffrey Joseph Rowley 

To get index of the second " "(Space) I try this but find return NaN instead return number of characters until second Space.为了获得第二个“”(空格)的索引,我尝试了这个,但发现返回 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

and the last step is slice those names, I try this code but don't work to.最后一步是对这些名称进行切片,我尝试使用此代码但不起作用。

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

if you have a more efficient way to do this please let me know??如果您有更有效的方法,请告诉我?

df['temp'] = df.Name.str.rpartition().get(0)
df

Output 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

EDIT编辑

If only first two elements are required in output.如果 output 中只需要前两个元素。

df['temp'] = df.Name.str.split().str[:2].str.join(' ')
df

OR或者

df['temp'] = df.Name.str.split().apply(lambda x:' '.join(x[:2]))
df

OR或者

df['temp'] = df.Name.str.split().apply(lambda x:' '.join([x[0], x[1]]))
df

Output 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

You can use str.index(substring) instead of str.find, it returns the smallest index of the substring(such as " ", empty space) found in the string.可以使用 str.index(substring) 代替 str.find,它返回在字符串中找到的子字符串的最小索引(如“”、空格)。 Then you can split the string by that index and reapply the above to the second string in the resulting list.然后,您可以按该索引拆分字符串,并将上述内容重新应用于结果列表中的第二个字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM