python - 如何删除 Pandas 列中特殊字符前面的部分字符串?

标签 python string pandas

我有这个简单的数据框:

In [101]: df = pd.DataFrame({'a':[1,2,3],'b':['ciao','hotel',"l'hotel"]})

In [102]: df
Out[102]: 
   a           b
0  1        ciao
1  2       hotel
2  3     l'hotel

这里的目标是删除 ' 撇号前面的字符串部分,以便 df:

   a           b
0  1        ciao
1  2       hotel
2  3       hotel

到目前为止,我尝试使用 sep=("'") 拆分字符串并仅获取第二个元素,但它失败了,因为我有不同长度的字符串(因此列表):

df['c'] = df['b'].apply(lambda x: x.split("'")[1])

最佳答案

您可以使用 -1 始终获取last 部分而不是second 部分。

df['c'] = df['b'].apply(lambda x: x.split("'")[-1])

print(df)

#    a        b      c
# 0  1     ciao   ciao
# 1  2    hotel  hotel
# 2  3  l'hotel  hotel 

但是,请记住,如果您的字符串包含 2 个或更多撇号(但您的要求并没有具体说明在这些情况下该怎么做),这将会停止。

关于python - 如何删除 Pandas 列中特殊字符前面的部分字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45919406/

相关文章:

python - 将 JSON 对象从 requests.get() 转换为字典

c - 如何在 C 中的 char 数组中搜索字符串?

sql - 计算 SQL 或 Pandas 中 GROUP BY 后的类别数

Python 新手 : trying to create a script that opens a file and replaces words

python - 是否有可能像在 Matlab 中一样快地在 Python 中计算稀疏矩阵的逆矩阵?

c++ - 如何在 C++ 中轻松管理 Unicode 字符串

python Pandas 数据框: need speed up process related to calculate 3 rows data

python - Pandas to_csv 仅保存上次运行脚本的数据。如何创建一个大表来保存所有模拟?

python - 当程序启动时运行Python脚本

regex - 如何根据时间间隔获取这些错误/不匹配字符串