首页 > 解决方案 > 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

标签: python-3.xpandasdictionaryreplace

解决方案


而不是series.map使用series.replacewithregex=True

df['col2'] = df['col1'].replace(cdict,regex=True)

推荐阅读