【问题标题】:Merging two columns while eliminating duplicate strings in pandas dataframe合并两列,同时消除熊猫数据框中的重复字符串
【发布时间】:2020-03-13 11:41:46
【问题描述】:

我有一个原始列 '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']  

【问题讨论】:

    标签: string pandas dataframe lambda list-comprehension


    【解决方案1】:

    您可以使用:

    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
    )
    

    【讨论】:

    • 谢谢,foglerit!这正是我想要的。
    • 我很高兴@MariaBruevich。您能否点击接受按钮,以便其他人可以轻松知道此答案解决了您的问题?谢谢
    • 我没有看到接受按钮?我在你的答案旁边点击了“这个答案很有用”。顺便说一句,我发现我应该将 NaN 转换为类型“字符串”,以便我的列表理解起作用。
    【解决方案2】:
    #input data
    d = {'RegionName1': ["a", "b", "c", "d"], 'RegionName2': ['Duluth and Duluth (University of Minnesota Duluth', "Monkato(Minnesota", 'Other1', 'Other2']}
    df = pd.DataFrame(data=d)
    print("Input dataframe:")
    print(df)
    
    #searching for '(' in RegionName2 column and replacing with NaN
    z=0
    for i, row in df.iterrows():
      k = df.loc[z,'RegionName2']
      if '(' in str(k):
        df.loc[z,'RegionName2'] = np.nan
      z = z+1
    print("Output dataframe:")
    print(df)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-18
      • 1970-01-01
      • 2021-11-05
      • 2017-11-26
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      • 2015-02-03
      相关资源
      最近更新 更多