big11mac
big11mac

Reputation: 189

Pandas column indexing strings

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'

Upvotes: 0

Views: 4147

Answers (1)

jezrael
jezrael

Reputation: 863341

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

Upvotes: 2

Related Questions