首页 > 解决方案 > Pandas 列索引字符串

问题描述

所以我只想取熊猫列的前三个字符并匹配它们。这是我想出的,但实现不正确:

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

标签: pythonpandas

解决方案


如果is ,您很接近,需要str并定义替换列,也因为存在带有空格的字符:dfDataFramex, y4

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

推荐阅读