python-3.x - 使用 split 和 strip 将列中的字符串拆分为 2 列
问题描述
我正在尝试按如下方式拆分“State”列:如果字符串包含 ['edit'],则该字符串需要保留在“State”列中而没有 ['edit'],例如 Alabama[edit] 应该成为 Alabama。
其中一个字符串包含“(”,它需要进入 RegionName 列,去掉左括号“(”之后的所有内容。例如杰克逊维尔(杰克逊维尔州立大学)[2] 应该成为杰克逊维尔。
unitown 是我的数据框,带有索引列和状态列。
我试过这段代码:
for line in unitown:
if '[edit' in line:
unitown['State'] = unitown['State'].str.split('[', expand=True).apply(lambda x: x.str.strip()) if x.count('[edit' > 0 else np.NaN).fillna(method="ffill")
else:
if '(' in line:
unitown['RegionName'] = unitown['State'].str.split('(', expand=True).apply(lambda x: x.str.strip()) if x.count('[edit' > 0 else np.NaN)
我的结果是这样的,RegionName 中的“State”和 State 列不变。请指出正确的方向以达到我想要的结果?谢谢你的任何提示。
解决方案
推荐阅读
- html - 如何将文本对象放置在页面下方 90% 的位置?
- javascript - 在 JavaScript/TypeScript 中调用函数变量而不是函数
- .net - 如何将 Visual Studio 解决方案分解为不同的物理文件夹和项目
- python - Anaconda Jupyter Notebooks 内核问题
- python - 如何在scrapy脚本中集成几个'yield'命令
- hive - 蜂巢表是否会跳过所有文件的标题?
- ios - 通过重叠两个单元格创建“文件夹”的集合视图拖放
- php - show 方法什么时候执行?
- javascript - 可以将数字用作布尔值而不是将它们与零进行比较吗?
- java - 使用 if 条件返回字符的方法