python - 删除字符串变量的最后 n 个字符,其中 n 是变量
问题描述
所以我有一个数据框,我试图从一列的每个字符串中删除最后 n 个字符。通常,我会使用以下代码:
df['code_0'] = df.code_0.map(lambda x: str(x)[:-4])
这将删除 4 个字符。但是,需要删除的字符数取决于另一列中的值。因此,如果我有以下数据框:
d = {'text': ["text that needs to be removed", "more text that needs to be removed"], 'number of characters to remove': [2, 4]}
df = pd.DataFrame(data=d)
如何仅删除第一行的最后 2 个字符和第二行的 4 个字符?
解决方案
使用lambda
:
>>> df.apply(lambda x: x["text"][:-x["number of characters to remove"]], axis=1)
0 text that needs to be remov
1 more text that needs to be rem