熊猫-每行以不同的长度子串

ric*_*ich 5 python string slice pandas

美好的一天,

我有一个数据框,我想为该列的每一行隔离一部分字符串。我遇到的问题是,每一行都需要具有不同长度的子字符串,特别是我只想一直将该字符串保留到第一次出现“。”。(一个周期)加上接下来的两个字母

例:

import pandas as pd

x = [ [ 34, 'Sydney.Au123XX'] ,
             [30, 'Delhi.As1q' ] ,
             [16, 'New York.US3qqa']]
x = pd.DataFrame(x)
x.columns = ["a", "b"]

#now I want to substring each row based on where "." occurs.
#I have tried the following:
y = x["b"].str.slice( stop = x["b"].str.find(".") + 2)
y = x["b"].str[0: x["b"].str.find(".")+ 2]

#desired output
desired = [[ 34, 'Sydney.Au'] ,
             [30, 'Delhi.As' ] ,
             [16, 'New York.US'] ]
desired  = pd.DataFrame(desired )
desired .columns = ["a", "b"] 
Run Code Online (Sandbox Code Playgroud)

请查看我的代码以获取所需的输出。

我不想使用循环。

提前致谢。

U10*_*ard 4

IIUC尝试:

x['b'] = x['b'].str.split('.').str[0]
print(x)
Run Code Online (Sandbox Code Playgroud)

你也可以做一行:

print(x.assign(b=x['b'].str.split('.').str[0]))
Run Code Online (Sandbox Code Playgroud)

他们都输出:

    a         b
0  34    Sydney
1  30     Delhi
2  16  New York
Run Code Online (Sandbox Code Playgroud)

编辑:

做:

x['b'] = x['b'].str.extract('(.*\...)')
print(x)
Run Code Online (Sandbox Code Playgroud)

或者使用:

print(x.assign(b=x['b'].str.extract('(.*\...)')))
Run Code Online (Sandbox Code Playgroud)