python - 如何拆分包含字符串的列

标签 python pandas

如果 _ 出现,我有一个数据框需要拆分列

Name = [('Hello'),
      ('Spider'),
      ('Captain'),
      ('Superman'),
       ('Hello_1'),
       ('Superman_1')]
dfName = pd.DataFrame(Name, columns=['Name'])

我的输出

    Name
0   Hello
1   Spider
2   Captain
3   Superman
4   Hello_1
5   Superman_1

预计结束

df1

    Name      
0   Hello
1   Spider
2   Captain
3   Superman

df2

    Name_
0   Hello_1
1   Superman_1

最佳答案

使用Series.str.contains对于掩码和过滤器,通过反转掩码不包含 ~ 对于 df1 而对于 df2 不包含 boolean indexing , 最后添加 DataFrame.reset_index对于默认 RangeIndex:

m = dfName['Name'].str.contains('_')

#is sample data .reset_index(drop=True) not necessary, added for general solution
df1 = dfName[~m].reset_index(drop=True)
print(df1)
       Name
0     Hello
1    Spider
2   Captain
3  Superman

df2 = dfName[m].reset_index(drop=True)
print(df2)
         Name
0     Hello_1
1  Superman_1   

关于python - 如何拆分包含字符串的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58543127/

相关文章:

python-3.x - Pandas:从列名称中存在的子字符串列表中的现有数据帧获取新数据帧

python - django 从主模板中的外部应用程序获取上下文

python - 子进程中 'shell=True'的实际含义

python - 按单列中的多个年份进行分组并绘制堆叠结果

python - 使用 pandas 在多列中应用 IF 条件

python - 从最后一行到第一行遍历 python pandas 数据框

python - 将 BASH 脚本更改为 Python

python - 名称 'slugify' 未定义

python - 按 Enter 键继续。 。 。然后删除语句 (Python)

python - 导入 pandas 时脚本挂起