如果字符串不是以“ x”开头,则替换列值

时间:2020-05-26 21:59:40

标签: python pandas

我有一个用pandas读取的df,并且在特定的行中,如果该值不是以特定的字符串开头(在这种情况下为文件路径),我想用另一列中的值覆盖内容,同一行。

for R in df:
     if not R['O_path'].str.startswith('\\correct\\path\\here'):
         R['O_path'] = R['N_path']
     else:
         continue

我不断收到“ TypeError:字符串索引必须为整数”显然我做错了,有什么主意吗?

2 个答案:

答案 0 :(得分:1)

我认为您正在寻找这个:

df.loc[df["O_path"].str.startswith('\\correct\\path\\here'), 'O_path'] = df['N_path']

答案 1 :(得分:0)

您的意思是:

mask = df['O_path'].str.startswith('\\correct\\path\\here')
df.loc[mask, 'O_path'] = df['N_path']