【问题标题】:Remove elements from a column of tuples in a pandas dataframe从 pandas 数据框中的元组列中删除元素
【发布时间】:2020-07-31 01:52:39
【问题描述】:

我有一个数据框,其值为字符串或包含多个字符串的元组,如下所示:

           Country                                              Roles  \
0  Shell Record  (DSC Payroll Administrator Reporting, DSC HR S...   
1            PL  (DSC Payroll Administrator Reporting, DSC Payr...   
2            ES  (DSC HR Business Partner Reporting, DSC HR Bus...   
3  Shell Record  (DSC HR Business Partner Reporting, DSC HR Bus...   
4  Shell Record                     DSC BPM Worklist Administrator   

          Role vs Family  
0           Do not match  
1  (Match, Do not match)  
2                  Match  
3           Do not match  
4           Do not match  

有没有一种方法可以删除元组中的值(例如,删除匹配/不匹配,以便列中的值在没有括号的情况下是相同的)。我不想为此使用“替换”(甚至不知道是否可能)。

谢谢!

【问题讨论】:

  • 它可以像 here 那样完成,但是,他们确实使用正则表达式 replace
  • 不起作用,它实际上返回 NaN 值而不是只删除括号

标签: python pandas dataframe tuples


【解决方案1】:

示例数据框:

import pandas as pd
import re
df = pd.DataFrame({'col': ['(Match, Do not match)', 'Match', 'Do not match']})
print(df)

之前:

                     col
0  (Match, Do not match)
1                  Match
2           Do not match

此正则表达式应删除列中的所有括号。

df['col'] = df['col'].apply(lambda x: re.sub(r'[(|)]', '', x))
print(df)

之后:

                   col
0  Match, Do not match
1                Match
2         Do not match

【讨论】:

    猜你喜欢
    • 2022-07-15
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 2012-03-30
    • 2015-09-14
    相关资源
    最近更新 更多