2Obe
2Obe

Reputation: 3720

Create single row for each entry in df rows

Hello I read in an excel file as a DataFrame whose rows contains multiple values. The shape of the df is like:

                                             Welding
0  65051020                                      ...
1  66053510                          66053550    ...
2  66553540                66553560              ...
3  67053540                  67053505            ...

now I want to split each row and write each entry into an own row like

    Welding
0   65051020
1   66053510
2   66053550
....
n   67053505

I tried have tried:

[new.append(df.loc[i,"Welding"].split()) for i in range(len(df))]

df2=pd.DataFrame({"Welding":new})

print(df2)

                                             Welding
0                                            66053510
1                                            66053550
2                                            66053540
3                                            66053505
4                                            66053551
5   [65051020, 65051010, 65051030, 65051035, 65051...
6   [66053510, 66053550, 66053540, 66053505, 66053...
7   [66553540, 66553560, 66553505, 66553520, 66553...
8                      [67053540, 67053505, 67057505]
9   [65051020, 65051010, 65051030, 65051035, 65051...
10  [66053510, 66053550, 66053540, 66053505, 66053...
11  [66553540, 66553560, 66553505, 66553520, 66553...
12                     [67053540, 67053505, 67057505]
13  [65051020, 65051010, 65051030, 65051035, 65051...
14  [66053510, 66053550, 66053540, 66053505, 66053...
15  [66553540, 66553560, 66553505, 66553520, 66553...
16                     [67053540, 67053505, 67057505]

But this did not return the expected results.

Appreciate each help!

Upvotes: 1

Views: 50

Answers (1)

jezrael
jezrael

Reputation: 862741

Use split with stack and last to_frame:

df = df['Welding'].str.split(expand=True).stack().reset_index(drop=True).to_frame('Welding')
print (df)
    Welding
0  65051020
1  66053510
2  66053550
3  66553540
4  66553560
5  67053540
6  67053505

Upvotes: 1

Related Questions