【问题标题】:python3 - apply a regex map to columnpython3 - 将正则表达式映射应用于列
【发布时间】: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


【解决方案1】:

说实话,你根本不需要dict。你可以在那里节省一些空间。

将numpy.select 与Series.str.startswith 一起使用:

In [1927]: import numpy as np

In [1928]: conds = [df.col1.str.startswith('n'), df.col1.str.startswith('p')]

In [1929]: choices = [-1, 0]

In [1930]: df['col2'] = np.select(conds, choices)

In [1931]: df
Out[1931]: 
       col1  col2
0  negative    -1
1  positive     0
2   neutral    -1
3   neutral    -1
4  positive     0

【讨论】:

    【解决方案2】:

    不要使用series.map,而是使用series.replace 和regex=True

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 2023-02-01
      • 2015-06-19
      • 2017-04-06
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多