我想做一点清理和删除出现在文本末尾的数字,但根据其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'}])
2条答案
按热度按时间xfb7svmp1#
您可以使用
groupby.apply
:或者,使用显式
for
循环:输出:
gzszwxb42#
如果您有
df
,如df = pd.DataFrame([{'id': 1, 'text': 'foo'}, {'id': 2, 'text': 'bar'}])
,则可以通过以下方式将函数应用于列中的每个单元格: