我想在第一个单词不是 x 的列中的每一行的字符串开头插入一个单词。 如果是x,则继续。 对于下面的情况,x = BP。 因此,如果 cat 中的第一个单词不是 BP,则插入它。
df = pd.DataFrame({ 'cat': ['BP STATION', 'STATION', 'BP OLD', 'OLD OLD'], }) df['cat'] = df['cat'].str.replace(r'^\w+', 'BP')
intent:
cat 0 BP STATION 1 BP STATION 2 BP OLD 3 BP OLD OLD
您需要您的搜索正则表达式“不是 BP”,并且您需要捕获它,以便它不会在替换中被删除。 所以你想要'^([^B][^P])。 替换正则表达式是 r'BP \1'。
>>> df['cat'] = df['cat'].str.replace(r'^([^B][^P])', r'BP \1') <stdin>:1: FutureWarning: The default value of regex will change from True to False in a future version.>>> df cat0 BP STATION1 BP STATION2 BP OLD3 BP OLD OLD >>>