Gony
Gony

Reputation: 25

Dividing pandas dataframe to to separate dataframes by rows

I have a dataframe, for example:

a b c
0 1 2
3 4 5
6 7 8

and i need to separate it by rows and create a new dataframe from each row. i tried to iterate over the rows and then for each row (which is a seriese) i tried the command row.to_df() but it gives me a weird result.

basicly im looking to create bew dataframe sa such:

a b c
0 1 2


a b c
3 4 5


a b c
7 8 9

Upvotes: 1

Views: 61

Answers (2)

Ofek Glick
Ofek Glick

Reputation: 1003

You can try doing:

for _, row in df.iterrows():
   new_df = pd.DataFrame(row).T.reset_index(drop=True)

This will create a new DataFrame object from each row (Series Object) in the original DataFrame df.

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195418

You can simply iterate row-by-row and use .to_frame(). For example:

for _, row in df.iterrows():
    print(row.to_frame().T)
    print()

Prints:

   a  b  c
0  0  1  2

   a  b  c
1  3  4  5

   a  b  c
2  6  7  8

Upvotes: 1

Related Questions