string - 合并两列,同时消除熊猫数据框中的重复字符串
问题描述
我有一个原始列 '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']
解决方案
您可以使用:
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
)
推荐阅读
- android - 警告:找不到包 'system-images;android-30;google_apis_playstore;x86 平台
- css - 没有useBlockLayout的React-Table中的粘性列
- c++ - C ++中优先级队列自定义排序中的异常
- spring - 如何为 google pub sub gRPC 调用配置代理凭据?
- reactjs - 找不到模块:无法解析“/home/manujtiwari/Desktop/portfolio-react/node_modules/react-particles-js/cjs”中的“tsparticles”
- selenium - 如何仅通过指定平台使用 Selenium Grid 运行并行 Appium 测试
- android-studio - 如何避免翻译后的 EditText 被键盘覆盖
- visual-studio - 在 Visual Studio 任务运行器中取消 Webpack 监视任务
- c++ - 您可以通过 1、2 或 3 步爬楼梯的方式数量 - 记忆
- javascript - 反应错误:警告超出最大更新深度