简体   繁体   中英

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'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM