从字符串末尾删除[edit]

时间:2020-05-15 19:24:59

标签: python pandas

我的数据框的状态为:

Alabama[edit]            8
Alaska[edit]             1
Arizona[edit]            3
Arkansas[edit]  

要从字符串末尾删除[edit]。

我尝试过: unit ['State'] = unit ['State']。str.rstrip('[edit]') 但是这段代码最终删除了州名末尾的字母编辑,例如特拉华州->德拉瓦州。

如何删除确切的[编辑]?

4 个答案:

答案 0 :(得分:2)

尝试一下:

unit['State'] = unit['State'].apply(lambda state : state[:state.index('[edit]')])

答案 1 :(得分:0)

您可以这样做:

unit.loc[:, 'State'] = [value.split('[edit]')[0].strip() for value in unit.loc[:, 'State']]

替换也可以像其他人提到的那样工作:

unit.loc[:, 'State'] = [value.replace('[edit]', '') for value in unit.loc[:, 'State']]

假设您的数据框是一个有效的熊猫数据框,称为“单位”,并且所需的列标签为“状态”

为了记录,这两种方法都优于公认的答案:

start_time = timeit.default_timer()
unit["State"] = unit["State"].apply(lambda state: state[: state.index("[edit]")])
print("ACCEPTED ANSWER -> The time difference is :", timeit.default_timer() - start_time)

start_time = timeit.default_timer()
unit.loc[:, 'State'] = [value.split('[edit]')[0] for value in unit.loc[:, 'State']]
print("SPLIT -> The time difference is :", timeit.default_timer() - start_time)

start_time = timeit.default_timer()
unit.loc[:, 'State'] = [value.replace('[edit]', '') for value in unit.loc[:, 'State']]
print("REPLACE -> The time difference is :", timeit.default_timer() - start_time)

ACCEPTED ANSWER -> The time difference is : 0.0015293000000000667
SPLIT -> The time difference is : 0.0010911999999998478
REPLACE -> The time difference is : 0.0007515000000002381

答案 2 :(得分:0)

这项工作

unit['State'] = unit['State'].str[:-6]

答案 3 :(得分:-1)

一种替代方法是用'

替换字符串'[edit]'
"Alabama[edit]".replace('[edit]', '')

或使用切片

"Alabama[edit]"[:-6]

这两个选项也会产生

"Alabama"

要将其映射到您上面的请求中:

unit['State'] = unit['State'].str.replace('[edit'], '')

unit['State'] = unit['State'].str.[:-6]

都应产生所需的输出。