python - Pandas 列索引字符串
问题描述
所以我只想取熊猫列的前三个字符并匹配它们。这是我想出的,但实现不正确:
df.loc[df[0:2] == 'x, y] = 'x'
解决方案
如果is ,您很接近,需要str
并定义替换列,也因为存在带有空格的字符:df
DataFrame
x, y
4
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
推荐阅读
- python-3.x - pdfminer 无法从不可编辑(即展平)PDF 表单中的字段中提取文本和坐标
- tokbox - 开始连接后打开工具订阅者更改镜像属性
- bash - 在 bash 脚本中获取第一个未注释的行(即不以 # 开头)
- cryptography - 将 MetaMask 连接到币安链
- windows - EACCES:Windows Next js 中的权限被拒绝 0.0.0.0:3000
- omnet++ - 导入和运行 INET 框架的错误和警告
- python - 将列表从一个函数返回到另一个函数
- javascript - 我想制作一个标签来同时切换我的 4 个 iframe 内容
- .htaccess - 使用 .htaccess 重定向 URL
- android - 按返回后重新加载图像