python - 根据正则表达式结果创建具有 0 和 1 值的新列

标签 python regex pandas dataframe

我的数据框有值:

data_df

0         student
1         sample text
2         student
3         no students
4         sample texting
5         random sample

我使用正则表达式提取包含单词“student”的行,结果如下:

regexdf
0         student
2         student

我的目标是在主数据框中创建一个包含 0 和 1 值的新列。即第 0 行应该是 1,第 5 行应该是 0。(因为“regexdf”在第 0 行和第 2 行中有“student”)如何匹配两者中的索引并创建列?

最佳答案

使用正则表达式:

data_df = data_df.assign(regexdf = data_df[1].str.extract(r'(student)\b', expand=False))
data_df['student'] = data_df['regexdf'].notnull().mul(1)
print(data_df)

输出:

                 1  regexdf  student
0         student  student        1
1     sample text      NaN        0
2         student  student        1
3     no students      NaN        0
4  sample texting      NaN        0
5   random sample      NaN        0

编辑

df_out = data_df.join(regexdf, rsuffix='regex')

df_out['pattern'] = df_out['1regex'].notnull().mul(1)

df_out['Count_Pattern'] = df_out['pattern'].cumsum()

print(df_out)

输出:

                1   1regex  pattern  Count_Pattern
0         student  student        1              1
1     sample text      NaN        0              1
2         student  student        1              2
3     no students      NaN        0              2
4  sample texting      NaN        0              2
5   random sample      NaN        0              2

关于python - 根据正则表达式结果创建具有 0 和 1 值的新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47637494/

相关文章:

python - 如何增加 csv 文件的默认列宽,以便在打开文件时所有文本都能正确显示?

改组 itertools.permutation(range(15)) 时出现 Python OOM 错误

regex - 惰性量词在 PCRE 中究竟是如何工作的?

python - Pandas groupby 应用 vs 具有特定功能的转换

python - 有效地将值分配给groupby中的第一行

python - 采用节点网络并插入缺失值的最佳方法

c++ - 使用 SWIG 包装对象从 C++ 调用 Python 函数的最简洁方法是什么

Python Numpy 问题和 Python 版本问题

python - 使用 Python 中的正则表达式提取具有开始和结束匹配项的字符串文本部分

从二次方程中提取系数的Java程序