Regex Sub和Pandas

2024-04-29 06:28:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力用字典中的数据替换pandas单元格中的字符串。我有一个熊猫架:

import pandas as pd
import numpy as np
import re

f = {'GAAP':['<1>','2','3','4'],'CP':['5','6','<7>','8']}
filter = pd.DataFrame(data=f)
filter

还有一本字典:

d = {'GAAP':['100','101'],'CP':['500','501','502']}
d

我正在尝试获得以下输出:

op = {'GAAP':['100|101','2','3','4'],'CP':['5','6','500|501|502','8']}
op = pd.DataFrame(data=op)
op  

我试过这样的方法:

def rep1(fr,di):
op=re.sub('\<.*?\>',fr,di)
return(op)


a='|'.join(d['GAAP'])
op=rep1(filter['GAAP'],a)
op

但是,如果序列对象是可变的且不能散列,则会出现错误。对我的错误有什么建议吗


Tags: importredataframepandasdata字典asfr
2条回答

让我们尝试使用pd.to_numeric转换<&燃气轮机;到NaN,然后fillna

filter=filter.apply(pd.to_numeric,errors='coerce').fillna(pd.Series(d).str.join('|'))
      GAAP           CP
0  100|101            5
1        2            6
2        3  500|501|502
3        4            8

使用replace的一种方法是:获取与<&燃气轮机;并将它们与字典中的替换项配对

outcome = filter.replace({'GAAP':"\<\d\>", 'CP':"\<\d\>"},
           {"GAAP":"|".join(d['GAAP']), "CP":"|".join(d["CP"])},
           regex=True)

    GAAP    CP
0   100|101 5
1   2       6
2   3      500|501|502
3   4       8

相关问题 更多 >