python - pandas python中需要拆分的一列数据
问题描述
我有一个看起来像这样的数据框:
0 movie*
1 star wars
2 the godfather
3 zombieland
4 book*
5 romeo and juliet
6 harry potter
7 tv series*
8 breaking bad
9 game of thrones
...
所以类别后跟该类别中的项目,然后是其他类别,都在一个列中。假设这样的数据会持续一段时间,有许多不同的类别。
然后我想要将数据框定为:
type name
0 movie* star wars
1 movie* godfather
2 movie* zombieland
3 book* romeo and juliet
4 book* harry potter
5 tv series* breaking bad
6 tv series* game of thrones
...
我已经用 .endswith('*') 实现了一个布尔掩码,但不知道如何将它合并到一个新的数据框中。
解决方案
利用:
print (df)
name
0 movie*
1 star wars
2 the godfather
3 zombieland
4 book*
5 romeo and juliet
6 harry potter
7 tv series*
8 breaking bad
9 game of thrones
首先为第一个位置创建新列,如果不匹配,DataFrame.insert
则为缺失值,然后向前填充非缺失值,然后过滤掉两列中的相同值,最后删除:Series.where
Series.str.endswith
boolean indexing
Series.ne
*
Series.str.strip
df.insert(0, 'type', df['name'].where(df['name'].str.endswith('*')).ffill())
df = df[df['type'].ne(df['name'])].copy()
df['type'] = df['type'].str.strip('*')
print (df)
type name
1 movie star wars
2 movie the godfather
3 movie zombieland
5 book romeo and juliet
6 book harry potter
8 tv series breaking bad
9 tv series game of thrones
推荐阅读
- javascript - 如何使 useEffect 仅在更改单个依赖项时重新运行?
- apache-spark - 创建数据框时如何忽略 Databricks 中的空 Parquet 文件
- javascript - RXJS 链依赖的 observables 顺序,但获取进度条的每个发射
- javascript - Javascript/JQuery 获取数据进行处理
- batch-file - Jenkins Pipeline Batch 文件输出
- linux - 从命令行传递的 ansible-playbook 额外变量
- node.js - 如何在 Gatsby.js 的静态 html 文件中动态设置内容
- assembly - x86-64 asm 中的 .LX 例程标签是什么?
- nunjucks - 在 nunjucks 文件中调用 Api
- r - 在 R 的 1000 次迭代中没有发现符号变化