检查Pandas DataFrame中某列的字符串值是否以另一列的值开头



我正在尝试连接Pandas DataFrame中的两个字符串列col1col2。但是,如果col2的值已经以col1的值开始,我不想将它们连接起来。在这种情况下,我希望使用col2而不进行串联。这将是预期的行为:

col1 col2 结果
ABC ABC
ABC XYC ABCXYZ
ABC

受到这个答案的启发:https://stackoverflow.com/a/64332351/18090994

编写自己的startswith函数,并使用numpy.vectorize对其进行矢量化。这样,就可以逐行比较col1col2中的字符串。

from numpy import vectorize
def startswith(str1, str2):
"""Check if str1 starts with str2 (case insensitive)"""
return str1.lower().startswith(str2.lower())
startswith = vectorize(startswith)
df['result'] = df['col2'].where(startswith(df['col2'], df['col1']), df['col1'] + df['col2'])

相关内容

最新更新