数据帧列中的 Python 正则表达式

标签 python regex pandas dataframe

我已经为 Excel 自动化编写了一个 Python 脚本。在这个自动化过程中,我陷入了一个点之间。我想在数据帧的列中应用正则表达式。尝试了很多方法,但无法产生我想要的完全理想的结果。我有如下数据框(简短的示例示例)-

this is input

这是示例数据框,其中包含大量列。我想在名为 ID 列的 C 列中应用正则表达式。我想根据 $、& 分隔符拆分此数据框中的数据,但也想忽略(删除)* 和 & 或 * 和 $ 之间的所有值。我们可以删除或忽略 C 列(ID)中找到空单元格的行。以下是我想要的输出数据帧的示例-

this is output

我尝试过以下操作-

import pandas as pd
import re
df = pd.read_excel("Deal Id Part Comparison Master File.xlsx", "Data Dump", header=1)
splits= []
for i in df['ID']:
    s = str(i)
    splits.append(re.split('\$|\&',s))

print(f' final list {splits}')

上面的代码能够根据$和&拆分数据并将它们存储在列表中。但 * 和 $ 或 * 和 & 之间的数据不会被忽略。我还想爆炸数据。

我确信可以有一个类轮来完成这一任务,但无法生成最终输出

最佳答案

你可以使用

import pandas as pd
df = pd.DataFrame({'Order': ['10-112','10-115'], 'Owner':['shubhman', 'rishab'], 'ID':['89ab$cd&78','']})

df['ID'] = df['ID'].str.replace(r'\*[^&$]*[&$]', '').str.split(r'[$&]') # Remove substrings between * and $ or &
df = df.explode('ID') # Split the rows with multiple IDs into multiple rows
df = df[df['ID'].astype(bool)] # Discard the rows with an empty ID
>>> df
    Order     Owner    ID
0  10-112  shubhman  89ab
0  10-112  shubhman    cd
0  10-112  shubhman    78

这里的正则表达式匹配:

  • .replace(r'\*[^&$]*[&$]', '') - 替换 * 之间的所有子字符串(与 \*) 以及最近的、最左边的 &$ (先出现的),请参阅 regex demo
  • .str.split(r'[$&]') - 使用 $& 字符分割(请注意,您不需要在字符类中转义)。

关于数据帧列中的 Python 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65564407/

相关文章:

python - 用python解析文本并映射到字典单词

PHP 将 REQUEST_URI 解析成数组

python - 使用正则表达式查找重复操作数 - Python

python - Pandas dataframe - 如何分配索引?

python - 完全相同的文本字符串不匹配

arrays - 逐行计算数据框新列中数组的元素

python - 安装 Tensorflow 时出现 CondaVerificationError

python - 如何使用 selenium webdriver 和 python 等待并获取 Web 元素的状态

python - 如何避免不一致的 s[i :-j] slicing behaviour when j is sometimes 0?

c++ - 高效的字符串到 unordered_map 中的键匹配?