regex 删除数据框列下文本结尾处显示的数字

rbl8hiat  于 2023-05-01  发布在  其他
关注(0)|答案(2)|浏览(83)

我想做一点清理和删除出现在文本末尾的数字,但根据其id的清理是不同的,我知道如何做到这一点时,它是一个字典,我开发的代码如下,但如果我有一个 Dataframe ?其中id作为一列,另一列名为text,必须被清理。如何更改此代码?

def remove(dic):
    suffix_map = {
        "id1": r'(?:0)$',
        "id2": r'(?:1)$',
        "id3": r'(?:2)$',
        "id4": r'(?:3)$',
    }

    for key, val in dic.items():
        suffix_pattern = suffix_map.get(key)
        if suffix_pattern:
            val.columns = val.columns.str.replace(suffix_pattern, '', regex=True)
            val.columns = val.columns.str.replace(r'_$', '', regex=True)

    return dic

the initioal dataframe:

df1 = pd.DataFrame([{'id': "id1", 'text': 'x11'}, {'id': "id2", 'text': 'x342'}, {'id': "id2",'text': 'b34'}])

the final output: 

out = pd.DataFrame([{'id': "id1", 'text': 'x1'}, {'id': "id2", 'text': 'x34'}, {'id': "id2",'text': 'b34'}])
xfb7svmp

xfb7svmp1#

您可以使用groupby.apply

suffix_map = {
        "id1": r'(?:1)$',
        "id2": r'(?:2)$',
        "id3": r'(?:3)$',
        "id4": r'(?:4)$',
    }

df1['text'] = (df1.groupby('id', group_keys=False)['text']
                  .apply(lambda s: s.str.replace(suffix_map[s.name], '', regex=True))
              )

print(df1)

或者,使用显式for循环:

for k, g in df1.groupby('id'):
    df1.loc[g.index, 'text'] = (df1.loc[g.index, 'text']
                                   .str.replace(suffix_map[k], '', regex=True)
                               )
print(df1)

输出:

id text
0  id1   x1
1  id2  x34
2  id2  b34
gzszwxb4

gzszwxb42#

如果您有df,如df = pd.DataFrame([{'id': 1, 'text': 'foo'}, {'id': 2, 'text': 'bar'}]),则可以通过以下方式将函数应用于列中的每个单元格:

df["text"] = df.text.apply(lambda x: my_func(x))

相关问题