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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.