0

So I want to take only the first three characters of a pandas column and match them. This is what I have come up with but the implementation is incorrect:

df.loc[df[0:2] == 'x, y] = 'x'
1

1 Answer 1

2

You are close, need str and define column for replacement if df is DataFrame, also for x, y there is 4 characters with whitespace:

df.loc[df['col'].str[:4] == 'x, y', 'col'] = 'x'

#another solution 
#df.loc[df['col'].str.startswith('x, y'), 'col'] = 'x'

If working with Series:

s[s.str[:4] == 'x, y'] = 'x'

Sample:

df = pd.DataFrame({'col':['x, y temp', 'sx, y', 'x, y', 's']})
print (df)
         col
0  x, y temp
1      sx, y
2       x, y
3          s

#if want replace substring
df['col1'] = df['col'].str.replace('^x\, y', 'x')

#if want set new value if condition
df.loc[df['col'].str[:4] == 'x, y', 'col'] = 'x'
print (df)
     col    col1
0      x  x temp <-col1 replace only substring
1  sx, y   sx, y
2      x       x
3      s       s

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.