【问题标题】:modification of skipping empty list and continuing with function修改跳过空列表并继续功能
【发布时间】:2019-12-06 03:02:42
【问题描述】:

背景

以下代码由skipping empty list and continuing with function稍作修改

import pandas as pd
Names =    [list(['Jon', 'Smith', 'jon', 'John']),
               list([]),
               list(['Bob', 'bobby', 'Bobs']),
               list([]),
               list([])]
df = pd.DataFrame({'Text' : ['Jon J Smith is Here and jon John from ', 
                                       'get nothing from here', 
                                       'I like Bob and bobby and also Bobs diner ',
                                        'nothing here too',
                                        'same here'
                            ], 

                          'P_ID': [1,2,3, 4,5], 
                          'P_Name' : Names

                         })

    #rearrange columns
df = df[['Text', 'P_ID', 'P_Name']]
df

                                 Text         P_ID  P_Name
0   Jon J Smith is Here and jon John from       1   [Jon, Smith, jon, John]
1   get nothing from here                       2   []
2   I like Bob and bobby and also Bobs diner    3   [Bob, bobby, Bobs]
3   nothing here too                            4   []
4   same here                                   5   []

工作代码

以下代码取自skipping empty list and continuing with function

m = df['P_Name'].str.len().ne(0)
df.loc[m, 'New'] = df.loc[m, 'Text'].replace(df.loc[m].P_Name,'**BLOCK**',regex=True) 

并在df 中生成以下New

            Text   P_ID  P_Name   New
0                                 **BLOCK** J **BLOCK** is Here and **BLOCK** **BLOCK** ...
1                                 NaN
2                                 I like **BLOCK** and **BLOCK** and also **BLOCK** d..
3                                 NaN 
4                                 NaN

期望的输出

但是,我想保留原始文本,而不是 134 行中的 NaNget nothing from here 如下图所示

            Text   P_ID  P_Name   New
0                                 **BLOCK** J **BLOCK** is Here and **BLOCK** **BLOCK** ...
1                                 get nothing from here
2                                 I like **BLOCK** and **BLOCK** and also **BLOCK** d..
3                                 nothing here too 
4                                 same here

问题

如何调整下面的代码以实现我想要的输出?

m = df['P_Name'].str.len().ne(0)
df.loc[m, 'New'] = df.loc[m, 'Text'].replace(df.loc[m].P_Name,'**BLOCK**',regex=True)  

【问题讨论】:

    标签: python-3.x string pandas text empty-list


    【解决方案1】:

    @tawab_shakeel 很接近。只需添加:

    df['New'].fillna(df['Text'], inplace=True)
    

    fillna 将从df['Text'] 中获取正确的值。


    我还可以使用re 正则表达式模块提出替代解决方案。

    def replacing(x):
        if len(x['P_Name']) > 0:
            return re.sub('|'.join(x['P_Name']), '**BLOCK**', x['Text'])
        else:
            return x['Text']
    
    df['New'] = df.apply(replacing, axis=1)
    

    apply 方法将replacing 函数应用于每一行,替换由re.sub 函数完成。

    【讨论】:

      【解决方案2】:

      只要在最后加上这一行fillna

      df['New'].fillna(df['Text'],inplace=True)
      

      【讨论】:

      • 我更新了我的代码以反映我在寻找什么。此代码在此示例中适用于一行,但我有一个真正的df,它有几千行长。所以我在这里更新了我的例子来反映这个事实
      • @ER_18 你想让每个 nan 都有不同的值吗?
      猜你喜欢
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      • 2022-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-03
      相关资源
      最近更新 更多