使用`和`条件替换pandas列中字符串的一部分

时间:2017-11-14 19:24:28

标签: python string pandas dataframe replace

我的pandas dataframe看起来像这样:

    Size    Measure     Location    Messages
    Small     1         Washington  TXT0123 TXT0875 TXT874 TXT0867 TXT0875 TXT0874
    Medium    2         California  TXT020 TXT017 TXT120 TXT012
    Large     3         Texas       TXT0123 TXT0123 TXT0123 TXT0123 TXT0217 TXT0206
    Small     4         California  TXT020 TXT0217 TXT006
    Tiny      5         Nevada      TXT0206 TXT0217 TXT0206

如果长度等于7且第四个字符为0,我试图从Messages列中的单个单词中删除0.

我已经尝试过循环,但它正在删除所有0:

for line in df.Messages:
    for message in line.split():
        if len(message) == 7 and message[3] == '0':
            print(message.replace('0', ''))

我也试过了.map给了我一些错误:

df.Messages = df.Messages.map(lambda x: x.replace('0', '') for message in line.split() for line in df.Messages if (len(message) == 7 and message[3] == '0'))

TypeError: 'generator' object is not callable

对于包含.mapif条件的and,有没有办法做到这一点?

3 个答案:

答案 0 :(得分:4)

如果你想为每个单词执行此操作,请先使用str.split拆分列,调用apply,然后重新加入str.join

def f(l):
    return [w.replace('0', '') if len(w) == 7 and w[3] == '0' else w for w in l]

df.Messages.str.split().apply(f).str.join(' ')

0    TXT123 TXT875 TXT874 TXT867 TXT875 TXT874
1                  TXT020 TXT017 TXT120 TXT012
2     TXT123 TXT123 TXT123 TXT123 TXT217 TXT26
3                         TXT020 TXT217 TXT006
4                           TXT26 TXT217 TXT26
Name: Messages, dtype: object

如果您只想替换单个0(而不是全部),请改为使用功能w.replace('0', '', 1)中的f

答案 1 :(得分:3)

df.Messages.str.split().apply(pd.Series).fillna('').\
    applymap(lambda x : x[:2]+x[4:] if len(x)==7 and x[3]=='0' else x).\ 
       apply(' '.join,1)

出[597]:

0    TX123 TX875 TXT874 TX867 TX875 TX874
1           TXT020 TXT017 TXT120 TXT012  
2     TX123 TX123 TX123 TX123 TX217 TX206
3                  TXT020 TX217 TXT006   
4                    TX206 TX217 TX206   
dtype: object

答案 2 :(得分:3)

IIUC:

:PymodeRun