How can i add new line break in pandas

Viewed 77

I want to add line break after transposing a data frame. I have tried this:

data = pd.read_csv("wwe/maw.csv")

df = pd.DataFrame(data).transpose()
print(df)
df.to_csv("wwe/mawmaw.csv")

After running the code all the data in the csv come to row wise:

enter image description here

But I want to show the data like, the data starts with current gimmik but when current come again it will have line break. How can I do this? I am using pandas

More likely. The column starts with 1 when its in 11 line the line will break. like

A B C D E F H J K L
a s d f g h j k l ;

after changing it should be look like this

A B C D E F
H J K L a s
d f g h j k
1 Answers

Since you did not provide a reproducible example, here is one of my own to illustrate one way to achieve what, I think, is your goal.

With the following toy dataframe:

import pandas as pd

df = pd.DataFrame(
    [["col0", "col1", "col2", "col3", "col4", "col0", "col1", "col2", "col3", "col4", "col0", "col1", "col2", "col3", "col4"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"]]
)

row = df.iloc[0]
df = df[1:]
df.columns = row
df.columns.name = ""
df = df.reset_index(drop=True)

print(df)
# Output
  col0 col1 col2 col3 col4 col0 col1 col2 col3 col4 col0 col1 col2 col3 col4
0    0    1    2    3    4    5    6    7    8    9   10   11   12   13   14

Then, to "split" the dataframe each time col0 is repeated and stack each slice as a new row:

indices = [i for i, col in enumerate(df.columns) if col == "col0"]

df = pd.concat(
    [
        df.iloc[:, indices[i] : indices[i + 1]]
        if i < len(indices) - 1
        else df.iloc[:, indices[i] :]
        for i in range(len(indices))
    ]
).reset_index(drop=True)
print(df)
# Output
  col0 col1 col2 col3 col4
0    0    1    2    3    4
1    5    6    7    8    9
2   10   11   12   13   14
Related