【发布时间】:2021-08-15 23:13:26
【问题描述】:
假设我有一个带有如下关键字的非标准化数据框:
data = pd.DataFrame({'tool_description':['bond assy fixture', 'pierce die', 'cad geometrical non-template',
'707 bond assy fixture', 'john pierce die', '123 cad geometrical non-template',
'jjashd bond assy fixture', '10481 pierce die', '81235 cad geometrical non-template']})
数据框:
| tool_description |
|---|
| bond assy fixture |
| pierce die |
| cad geometrical non-template |
| 707 bond assy fixture |
| john pierce die |
| 123 cad geometrical non-template |
| jjashd bond assy fixture |
| 10481 pierce die |
| 81235 cad geometrical non-template |
如您所见,在本例中,关键字是bond assy fixture、pierce 和cad 几何非模板。 我想根据它们的关键字替换这些值以获得标准化的数据。所以我想了一个这样的解决方法:
# Pull the data matching my regex condition
X = data.loc[data.tool_description.str.contains((r"\b(bond assy fixture)\b"), case=False, regex=True), :]
# Replace values by a standardized name
X['tool_description] = 'bond assy fixture'
# Pull index from X dataset
index_list = X.tool_description.index.tolist()
# Create empty column in the original dataset
data['standardized_column'] = ""
# Loop to fill new column with a standardized description
for index in index_list:
data.loc[index, 'standardized_column'] = 'bond assy fixture'
输出:
| tool_description | standardized_column |
|---|---|
| bond assy fixture | bond assy fixture |
| pierce die | nan |
| cad geometrical non-template | nan |
| 707 bond assy fixture | bond assy fixture |
| john pierce die | nan |
| 123 cad geometrical non-template | nan |
| jjashd bond assy fixture | bond assy fixture |
| 10481 pierce die | nan |
| 81235 cad geometrical non-template | nan |
这很好用,但是对于一个条件,我需要为数百个正则表达式条件创建所有这些循环。当我尝试循环使用这行代码的那一行时
conditions = ['a', 'b', 'c']
for i in conditions:
X = data.loc[data.tool_description.str.contains((r"\b(i)\b"), case=False, regex=True), :]
我在将正则表达式条件作为迭代器时遇到问题。当循环从条件列表中提取 str 时,它将用引号将其拉出。
既然我已经把你放在上下文中,我有以下问题:
- 有没有更简单优雅的方法来替换这些值?
- 如果没有,我如何创建一个循环来迭代该正则表达式?
感谢您的时间和回答。我知道我可以询问如何使用正则表达式删除引号以用于迭代目的,但是,我还想知道是否有另一种方法可以解决一般问题,即替换值。
【问题讨论】:
-
我不明白你想要做什么或你希望得到什么输出
-
it will pull it with the quotation mark.是什么意思 看不到你在示例中提到的引号。 -
请注意,您需要在关键字周围使用一对单词边界
\b,以便pierce不会与例如匹配。mpierce。您最初使用正则表达式是正确的。仅使用像StringA in StringB这样的Python 检查会产生错误匹配,因为pierce in mpierce仍然是正确的。
标签: python pandas loops replace