python-3.x - python3 - 将正则表达式映射应用于列
问题描述
如何将正则表达式应用于数据框列?
import pandas as pd
df = pd.DataFrame({'col1': ['negative', 'positive', 'neutral', 'neutral', 'positive']})
cdict = {'n.*': -1, 'p.*': 0}
df['col2'] = df['col1'].map(cdict)
print(df.head())
当前输出为:
: col1 col2
: 0 negative NaN
: 1 positive NaN
: 2 neutral NaN
: 3 neutral NaN
: 4 positive NaN
但预期的结果:
: col1 col2
: 0 negative -1
: 1 positive 1
: 2 neutral -1
: 3 neutral -1
: 4 positive 1
解决方案
而不是series.map
使用series.replace
withregex=True
df['col2'] = df['col1'].replace(cdict,regex=True)
推荐阅读
- python - 如何修复pythonnet安装期间的错误
- python - Python:用于抓取网站的 IP 轮换
- android - Android,原生广告,如何设置广告选择 btn 的位置
- terraform - Terraform 合并两个具有相同结构的列表
- php - 如果我不使用此代码,则永远不会显示 instagram 图像
- python - 不理解我的 discord.py 机器人代码中的 commands.command() - 我必须使用什么前缀/命令?
- python - 如何将 JSON 响应存储到数组 - Python 请求
- android - 如何在android中实现启动画面的执行程序
- python - XML的Spark结构化流动态解析
- python - 在熊猫中将字符串转换为日期时间