首页 > 解决方案 > 使用 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 列不变。请指出正确的方向以达到我想要的结果?谢谢你的任何提示。

在此处输入图像描述

标签: python-3.xpandasdataframesplitstrip

解决方案


推荐阅读