【发布时间】:2023-03-29 07:50:01
【问题描述】:
我使用逗号作为分隔符将字符串拆分为行。
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)
但是,逗号“自然”出现的三个子字符串不应导致拆分:
- 与性偏好、性生活和/或性取向相关的数据
- 合同、工资和福利
- 采购、分包和供应商管理
我在想,因为只有这三个实例,如果有办法使用类似这样的东西做出一些例外:"preferences,", "sex life," 、“合同”、和“采购”。或者更优雅的解决方法?
这里是一个例子 df:
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 |
+-------------------------------------------------------------------------+
【问题讨论】:
-
我有一个类似的问题,但我希望利用 " 来表示应该忽略里面的逗号。下面的答案似乎没有注意到 "。