首页 > 解决方案 > 合并两列,同时消除熊猫数据框中的重复字符串

问题描述

我有一个原始列 'All' 的数据框,我将其拆分为 RegionName1 和 RegioName2 列。有重复的条目,例如,德卢斯和德卢斯(明尼苏达德卢斯大学。我想将德卢斯(明尼苏达德卢斯大学)之类的字符串转换为 NaN 值。所以我试过了

unitown['RegionName2'] = [np.nan if '(' in x else x for x in unitown['RegionName2']]

并得到一个错误 TypeError: 'float' 类型的参数不可迭代。我还能尝试什么?

在此处输入图像描述

unitown=pd.read_table('university_towns.txt', header=None).rename(columns={0:'All'})
unitown['State']=unitown['All'].apply(lambda x: x.split('[edi')[0].strip() if x.count('[edi') else np.NaN).fillna(method="ffill")                       #.fillna(method="ffill")
unitown['RegionName1'] = unitown['All'].apply(lambda x: x.split('(')[0].strip() if x.count('(') else np.NaN)
unitown['RegionName2'] = unitown['All'].apply(lambda x: x.split(',')[0].strip() if x.count(',') else np.NaN)
unitown['RegionName2'] = [np.nan if '(' in x else x for x in     unitown['RegionName2']]
return unitown[unitown.State=='Minnesota']  

标签: stringpandasdataframelambdalist-comprehension

解决方案


您可以使用:

unitown.loc[unitown.RegionName2.str.contains("("), 'RegionName2'] = np.NaN

或者将此逻辑直接添加到生成的代码中,RegionName2如下所示:

unitown['RegionName2'] = unitown['All'].apply(
    lambda x: x.split(',')[0].strip() if x.count(',') and "(" not in x.split(',')[0] else np.NaN
)

推荐阅读