1

I have a dataframe that's 13 columns by 557 rows. I've exported the data to excel, but I want to add the first row (the column names) every 56 rows so that when I print it, the header is at the top.

I've tried a bunch of things like .concat and .append but I'm a beginner with Pandas so I'm not very good

I have this near the end of my code to add the header, I have the right names in the list but it just messes everything up

header = []
for title in order:
    header.append(title)
panda.iloc[2] = header

Note that header = ['Age', 'RK', 'Team', ...]

JackB
  • 31
  • 6
  • add a sample dataframe and an expected output for a better understanding for us and ppl who will look up to this post later on. – anky May 17 '19 at 16:00
  • please see this post: https://stackoverflow.com/questions/15888648/is-it-possible-to-insert-a-row-at-an-arbitrary-position-in-a-dataframe-using-pan?rq=1 – Julia May 17 '19 at 16:02
  • Does this need to be done at the pandas level? If you're printing from excel, there are tools to always print the header row that are tolerant of formatting changes, etc. As a bonus, they also keep the header (and row indices, if you care about them) at the top (side) of the field when scrolling. – offbyone May 17 '19 at 17:04

1 Answers1

3

np.split

Assume k is the number of lines you want per split

df = pd.DataFrame(1, range(20), [*'ABC'])

k = 5
print(*np.split(df, range(k, len(df), k)), sep='\n\n')

   A  B  C
0  1  1  1
1  1  1  1
2  1  1  1
3  1  1  1
4  1  1  1

   A  B  C
5  1  1  1
6  1  1  1
7  1  1  1
8  1  1  1
9  1  1  1

    A  B  C
10  1  1  1
11  1  1  1
12  1  1  1
13  1  1  1
14  1  1  1

    A  B  C
15  1  1  1
16  1  1  1
17  1  1  1
18  1  1  1
19  1  1  1
piRSquared
  • 285,575
  • 57
  • 475
  • 624
  • Could you please explain using `*` before np – PIG May 17 '19 at 17:13
  • 1
    that's the same this as `for a in np.split(...): print(a)` – piRSquared May 17 '19 at 17:15
  • I think my explanation was a little unclear, here is a link to my new question [link] https://stackoverflow.com/questions/56200592/how-to-insert-a-header-multiple-times-in-a-pandas-dataframe – JackB May 18 '19 at 15:54
  • @PIG the asterisk operator * at both places before ABC and before np is used for unpacking. You may want to watch https://youtu.be/sYeqpnAA7U4 for detailed explaination – Dr Nisha Arora Jan 11 '21 at 16:46