我正在尝试连接Pandas DataFrame中的两个字符串列col1
和col2
。但是,如果col2
的值已经以col1
的值开始,我不想将它们连接起来。在这种情况下,我希望使用col2
而不进行串联。这将是预期的行为:
col1 | col2 | 结果 |
---|---|---|
ABC | ABC | |
ABC | XYC | ABCXYZ |
ABC |
受到这个答案的启发:https://stackoverflow.com/a/64332351/18090994
编写自己的startswith
函数,并使用numpy.vectorize对其进行矢量化。这样,就可以逐行比较col1
和col2
中的字符串。
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'])