首页 > 解决方案 > 根据 $ 符号将 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'.

标签: pandasdataframepandas-groupby

解决方案


我认为缺少值存在问题,因此最好先使用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

推荐阅读