pandas - 根据 $ 符号将 pandas 中的行拆分为多行
问题描述
我知道这个问题已被多次问过,但在将其标记为重复之前,我找到的答案似乎都不起作用。我有一个形式的数据框:
category | description
------------------------------
puppy dog$pup
crappy cat$pet
squeeky animal
fluffy dog$pet
我想按符号将description
列拆分为多行,并获得如下内容:$
category | description
------------------------------
puppy dog
puppy pup
crappy cat
crappy pet
squeeky animal
fluffy dog
fluffy pet
对不起这个愚蠢的例子,但我希望它说明了问题。我尝试的最后一件事是:
new_df = pd.concat([pd.Series(row['category'], row['description'].split('$'))
for _, row in old_df.iterrows()]).reset_index()
但这会返回一个:
AttributeError: 'float' object has no attribute 'split'.
解决方案
我认为缺少值存在问题,因此最好先使用Series.str.split
,然后再DataFrame.explode
用于新行(适用于 pandas 0.25+):
df['description'] = df['description'].str.split('$')
df = df.explode('description')
print (df)
category description
0 puppy dog
0 puppy pup
1 crappy cat
1 crappy pet
2 squeeky animal
3 fluffy dog
3 fluffy pet
4 another val NaN
推荐阅读
- python - Pandas 绘图条顺序类别
- sql - Oracle DB 中复杂的 SELECT 语句
- html - 如何防止此导航栏崩溃?
- laravel - 如何在 Laravel 5.4 中组合模型和按模型排序两个数据
- reactjs - Webpack+SemanticUI+React:进程未定义
- python - 在散列中使用 .digest()?
- c++ - c ++ CreateThread非静态成员没有特定成员名称
- php - 具有非原始类型提示参数的 Laravel API 端点
- excel - VBA range.formula 问题(LEN、RIGHT 和 LEFT)
- python - 无法在 python 脚本中运行 os.popen