【发布时间】:2021-07-04 15:08:22
【问题描述】:
如何将正则表达式应用于数据框列?
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
【问题讨论】:
-
请注意,对于您的预期输出,您的 dict 应该是
cdict = {'n.*': -1, 'p.*': 1},我认为这是一个错字
标签: python-3.x pandas dictionary replace