我正在尝试删除正则表达式,方括号,单引号和双引号,并将其替换为空字符串。我做错了。 输入如下:
Accident_type Injury_classification
['Strike fixed/station obj'] ["Assault in PI Cases", 'Other Injuries']
['Slip, trip, fall'] ["Work Related Injury", 'Other Injuries']
etc
我尝试了df['Injury_classification'].str.replace(r" \(.*\)","")
,但它没有删除任何内容。代码已运行,但结果相同,但未删除任何内容。
然后我尝试
df['Injury_classification'] = pd.DataFrame([str(line).strip('[').strip(']').strip('\'').strip('\'').strip('"') for line in df['Injury_classification']])
当前输出:
Accident_type Injury_classification
empty Assault in PI Cases", 'Other Injuries
empty Work Related Injury", 'Other Injuries
etc
如您所见,仍然有一些单引号,有时还有双引号。我想知道如何处理?我大约有20-30列结构相似的列。现在,我正在为同一命令逐行运行,但是对于这么多列来说效率不高。我想知道如何编写一个循环来删除所有列的正则表达式,单引号和双引号吗?
预期输出:
Accident_type Injury_classification
Strike fixed/station obj Assault in PI Cases, Other Injuries
Slip, trip, fall Work Related Injury, Other Injuries
etc
谢谢
答案 0 :(得分:0)
在这里我只将str.replace
与字符类一起使用:
df['Injury_classification'] = df['Injury_classification'].str.replace("[\[\]\"']", "")
这会将['Slip', 'trip', "fall"]
输入到Slip, trip fall
中。