Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a column Name of string data type. I want to get all the values except the last one and put it in a new column FName, which I could achieve

df = pd.DataFrame({'Name': ['John A Sether', 'Robert D Junior', 'Jonny S Rab'], 
                        'Age':[32, 34, 36]})
df['FName'] = df['Name'].str.split(' ').str[0:-1]

              Name  Age        FName
0    John A Sether   32    [John, A]
1  Robert D Junior   34  [Robert, D]
2      Jonny S Rab   36   [Jonny, S]

But the new column FName looks like a list, which I don't want. I want it to be like: John A.

I tried convert the list to string, but it does not seems to be right. Any suggestion ?

question from:https://stackoverflow.com/questions/65643135/get-string-instead-of-list-in-pandas-dataframe

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
76 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use .str.rsplit:

df['FName'] = df['Name'].str.rsplit(n=1).str[0]

Or you can use .str.extract:

df['FName'] = df['Name'].str.extract(r'(S+s?S*)', expand=False)

Or, you can chain .str.join after .str.split:

df['FName'] = df['Name'].str.split().str[:-1].str.join(' ')

              Name  Age     FName
0    John A Sether   32    John A
1  Robert D Junior   34  Robert D
2      Jonny S Rab   36   Jonny S

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...