用“ ;;”分隔单行分成同一列中的多个单独的行

时间:2019-12-12 05:52:16

标签: python pandas dataframe

目前,我正试图在每次';;'时拆分第一行出现在“材料描述”列中的新行中。导致这一点的代码是:

df.loc[df['mask'] == True, ['Material Description']] = ';;' + df['Material Description']
df['Material Description'] = df['Material Description'].str.cat()
df['Material Description'].tolist()
df['Material Description'].str.split(';;') 

我尝试过的代码是对此代码的操作,但是我似乎无法解决。

pd.concat([Series(row['var2'], row['var1'].split(','))
            for _, row in a.iterrows()]).reset_index()
        Material Description
0       Hello;; How are you doing;; This is good   
1
2

获得所需的输出:

        Material Description
0       Hello
1       How are you doing
2       This is good

2 个答案:

答案 0 :(得分:3)

这应该像您的输出一样拆分行:

df['Material Description'].apply(lambda x: x.split(';;')).explode().reset_index().drop(columns='index') 

输出:

  Material Description
0                Hello
1    How are you doing
2        This is good

答案 1 :(得分:2)

您可以更改:

int

收件人:

vector < struct Node* > par,chi;
vector < int > val;

说明

如果将df['Material Description'].str.split(';;') 添加到Series.str.split得到df1 = (df['Material Description'].str.split(';;', expand=True) .stack() .reset_index(drop=True) .to_frame('Material Description')) print (df1) Material Description 0 Hello 1 How are you doing 2 This is good ,则通过DataFrame.stack进行整形,最后通过DataFrame.reset_index进行一些数据清理,并保留一列{{1} }使用Series.to_frame