因此,我只想获取pandas列的前三个字符并将其匹配。这是我想出的,但是实现不正确:
df.loc[df[0:2] == 'x, y] = 'x'
答案 0 :(得分:2)
您很亲密,如果str
为df
,则需要DataFrame
并定义要替换的列,对于x, y
,还有4
个带有空格的字符:< / p>
df.loc[df['col'].str[:4] == 'x, y', 'col'] = 'x'
#another solution
#df.loc[df['col'].str.startswith('x, y'), 'col'] = 'x'
如果使用Series
:
s[s.str[:4] == 'x, y'] = 'x'
示例:
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