如果Pandas Dataframe中的值不包含字符串,则将其替换为regex

2024-10-02 10:25:02 发布

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

我有一个相当大的数据帧(大约15米行,7列),我想替换一些不具有正确形状的值。在

我尝试在整个数据帧中迭代,但是一个一个地更改值需要太长时间。 我也尝试过使用regex,但是如果字符串与pandas不匹配,我无法找到如何替换。在

我的数据帧列如下:
1 : L8_P1_Local 2 : L8 3 : L8_P1_Local 4 : L8 5 : poste2 6 : poste6 7 : poste2 8 : Poste 2 9 : poste_6

编辑:有时poste2和poste6是不同的,比如poste2或posteu2或posteu2 这个正则表达式会匹配所有内容吗?[pP]奥斯特[\s]*[\u]*[0-9]

我要做的是在poste2或poste6前面的每一行上都有L8,这样它就会像L8_poste6。我在一个名为numline的变量中有'L8'字符串。在

编辑:因为答案在被接受的答案评论中,我会把它写在这里。在

text = numligne +'_\\1' dataframe['row'] = dataframe['row'].str.replace('([pP]oste[ _]*[0-9])', text)


Tags: 数据字符串答案text编辑dataframelocalpp
3条回答

如果您想添加L8它不在那里,您可以让pandas这样做:

因此,我假设您有一个DataFrame(比如df),其中有一个列(比如col)包含示例数据:

           col
0  L8_P1_Local
1           L8
2  L8_P1_Local
3           L8
4       poste2
5       poste6
6       poste2

你可以:

^{pr2}$

获得:

           col
0  L8_P1_Local
1           L8
2  L8_P1_Local
3           L8
4    L8_poste2
5    L8_poste6
6    L8_poste2
我想,对你来说,文本的大小写并不重要。请检查下面的解决方案。
s = pd.DataFrame({'ID':[1,2,3,4,5,6,7,8,9],
                     'Text':['L8_P1_Local','L8','L8_P1_Local','L8','poste2','poste6','poste2','Poste 2','poste_6']})


    def match_it(s):
        s['Text']=s['Text'].str.lower()
        s['Text']=s['Text'].str.replace(' ','')
        for i in range(len(s)):
            if 'poste' in s.loc[i,'Text']:
                s.loc[i,'Text']='l8'+'_'+s.loc[i,'Text']
        return s    

    match_it(s)
#Output



     ID  Text
    0   1   l8_p1_local
    1   2   l8
    2   3   l8_p1_local
    3   4   l8
    4   5   l8_poste2
    5   6   l8_poste6
    6   7   l8_poste2
    7   8   l8_poste2
    8   9   l8_poste_6

使用pd.Series.str.replace

s = pd.Series(["1 : L8_P1_Local",
"2 : L8",
"3 : L8_P1_Local",
"4 : L8",
"5 : poste2",
"6 : poste6",
"7 : poste2",])
s.str.replace(' (poste[26])', 'L8_\\1')

输出:

^{pr2}$

有多种方法可以在整个数据帧中实现这一点,包括(但可能不是最快的):

for c in df:
    df[c] = df[c].str.replace(' (poste[26])', 'L8_\\1')

相关问题 更多 >

    热门问题