python - Pandas - 用不同的长度对每一行进行子串

标签 python string pandas slice

你好,

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

例子:

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"] 

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

我不想使用循环。

提前致谢。

最佳答案

IIUC 尝试:

x['b'] = x['b'].str.split('.').str[0]
print(x)

你也可以做一个单行:

print(x.assign(b=x['b'].str.split('.').str[0]))

它们都输出:

    a         b
0  34    Sydney
1  30     Delhi
2  16  New York

编辑:

做:

x['b'] = x['b'].str.extract('(.*\...)')
print(x)

或者使用:

print(x.assign(b=x['b'].str.extract('(.*\...)')))

关于python - Pandas - 用不同的长度对每一行进行子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57215355/

相关文章:

c++ - QLabel “break”单词如果太长

python - 防止我的 RAM 内存达到 100%

pandas - 如何在pandas中使用selenium来读取网页?

python - 对 Polyval 的输出感到困惑

python - 我想使用 django 模型表单生成 4 级下拉表单

c# - 在字符串的所有实例前面添加一个字符

c++ - 忽略包含特殊词的字符串(月)

python - 根据 Pandas 列表列中的条件创建新列

Python - 使用套接字设置源端口号

python - 使用 loc 在 pandas 数据框中设置值 - 多个选择条件允许在不同列中设置值