")]]: #only on col-6ren">
gpt4 book ai didi

python - 字符串拆分有异常

转载 作者:行者123 更新时间:2023-12-04 08:46:50 24 4
gpt4 key购买 nike

我使用逗号作为分隔符将字符串拆分为行。

for col in [col for col in df.loc[:,df.columns.str.contains(">")]]: #only on colnames containing ">"
df[col] = df[col].str.split(", ")
df = df.explode(col).reset_index(drop=True)

但是,有三个子字符串的逗号“自然”出现,不应导致拆分:

  1. 与性偏好、性生活和/或性取向相关的数据
  2. 契约(Contract)、薪水和福利
  3. 采购、分包和供应商管理

我在想,因为只有这三种情况,如果有办法使用这样的东西来做一些异常(exception):“偏好”,“性生活”,“契约(Contract)”“采购”。或者更优雅的解决方法?

这是一个例子:

df = pd.DataFrame({"col > 1": ["Personals, Financials, Data related to sexual preferences, sex life, and/or sexual orientation", "Personals, Financials", "Vendors, Procurement, subcontracting and vendor management"]})

这是它应该输出的内容:

+-------------------------------------------------------------------------+
| col > 1 |
+-------------------------------------------------------------------------+
| Personals |
| Financials |
| Data related to sexual preferences, sex life, and/or sexual orientation |
| Personals |
| Financials |
| Vendors |
| Procurement, subcontracting and vendor management |
+-------------------------------------------------------------------------+

最佳答案

您可以在 df.str.split() 中使用带有多个负向回顾语句的正则表达式模式来本质上说 “在 上拆分行, 除非在某些情况下其中 , 前面有...”

要在 Python 中实现这一点,可能最好使用多个负向后视断言 - Python 正则表达式强制执行固定宽度的环视,因此它不像使用 | 分隔的子句的单个负向后视那么简单。

使用示例中的短语在 上拆分, 除非前面有您可以使用的任何列出的短语:

r"(?<!preferences)(?<!sex life)(?<!Contract)(?<!Procurement),"

完整代码示例:

import pandas as pd

df = pd.DataFrame({"col > 1": ["Personals, Financials, Data related to sexual preferences, sex life, and/or sexual orientation", "Personals, Financials", "Vendors, Procurement, subcontracting and vendor management"]})

df["col > 1"] = df["col > 1"].str.split(r"(?<!preferences)(?<!sex life)(?<!Contract)(?<!Procurement),")

df = df.explode("col > 1").reset_index(drop=True)

这将为您提供 df 以及您问题中概述的所需 ["col > 1"] 值 新索引 0...n.

                                             col > 1
0 Personals
1 Financials
2 Data related to sexual preferences, sex life,...
3 Personals
4 Financials
5 Vendors
6 Procurement, subcontracting and vendor manage...

关于python - 字符串拆分有异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64276564/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com