簡體   English   中英

捕獲Pandas中第2個和第3個空格之前的所有字符串

[英]Capture all the string before the 2nd and 3rd whitespace in Pandas

我了解如何從第一次出現的空格中拆分字符串。 我的問題是如何拆分第二個第三次出現的空格並捕獲之前的所有字符串。

df = pd.DataFrame({"cid" : {0 : "cd1", 1 : "cd2", 2 : "cd3"},
                   "Name" : {0 : "John Maike Leiws", 1 : "Katie Sue Adam", 2 : "Tanaka Ubri Kse Suri"}}).set_index(['cid'])

                     Name
cid
cd1      John Maike Leiws
cd2        Katie Sue Adam
cd3  Tanaka Ubri Kse Suri

df['split_one'] = df.Name.str.split().str[0]

預計 output:

                     Name  split_one   split_two   split_three
cid
cd1      John Maike Leiws      John    John Maike  John Maike Leiws
cd2        Katie Sue Adam     Katie    Katie Sue   Katie Sue Adam
cd3  Tanaka Ubri Kse Suri    Tanaka    Tanaka Ubri Tanaka Ubri Kse

使用str索引,然后使用Series.str.join

s = df.Name.str.split()
df['split_one'] = s.str[0]
df['split_two'] = s.str[:2].str.join(' ')
df['split_three'] = s.str[:3].str.join(' ')
print (df)
                     Name split_one    split_two       split_three
cid                                                               
cd1      John Maike Leiws      John   John Maike  John Maike Leiws
cd2        Katie Sue Adam     Katie    Katie Sue    Katie Sue Adam
cd3  Tanaka Ubri Kse Suri    Tanaka  Tanaka Ubri   Tanaka Ubri Kse

使用正則表達式的一種簡單方法是使用嵌套捕獲組:

df['Name'].str.extract('(((\S+)\s\S+)\s\S+)').iloc[:,::-1]

output:

                    0            1       2
cid                                       
cd1  John Maike Leiws   John Maike    John
cd2    Katie Sue Adam    Katie Sue   Katie
cd3   Tanaka Ubri Kse  Tanaka Ubri  Tanaka

要添加,只需顛倒順序:

df[['split_one', 'split_two', 'split_three']] = df['Name'].str.extract('(((\S+)\s\S+)\s\S+)').iloc[:,::-1]

output:

                     Name split_one    split_two       split_three
cid                                                               
cd1      John Maike Leiws      John   John Maike  John Maike Leiws
cd2        Katie Sue Adam     Katie    Katie Sue    Katie Sue Adam
cd3  Tanaka Ubri Kse Suri    Tanaka  Tanaka Ubri   Tanaka Ubri Kse

我不知道您是在尋找通用的東西還是簡單的東西。 這是一種簡單的方法。

 df = pd.DataFrame({"cid" : {0 : "cd1", 1 : "cd2", 2 : "cd3"},
                       "Name" : {0 : "John Maike Leiws", 1 : "Katie Sue Adam", 2 : "Tanaka Ubri Kse Suri"}}).set_index(['cid'])
    
    s = df.Name.str.split().str
    df['split_one'] = s[0]
    df['split_two'] = s[0] + ' ' + s[1]
    df['split_three'] = s[0] + ' ' + s[1] + ' ' + s[2]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM