1

I am still learning coding and would be grateful for any help that I can get.

I have a dataframe where a person's name is the column header. I would like to shift the column header down 1 row and rename the column 'Name'. The column header will be different with each dataframe, though. It won't always be the same person's name.

Here is an example of one of the dataframes:

index   Patrick
0       Stan
1       Frank
2       Emily
3       Tami

I am hoping to shift the entire column with names down 1 row and rename the column header 'Names' but am unable to find this during my research.

Here is an example of the desired output:

index   Names
0       Patrick
1       Stan
2       Frank
3       Emily
4       Tami

I have seen the option to use 'shift', however, I do not know if this will work correctly in this case.

I will post the url below for a similar problem that was been asked. In this problem they want to shift up by one. In my problem I want to shift down by one.

Shift column in pandas dataframe up by one?

The code example I found online is below:

df.gdp = df.gdp.shift(-1)

The issue I see is that I will be using multiple dataframes so the person's name (column header) will be different. I won't have the same name each time.

Any help? I will continue to work and this and will post the answer if I am able to find it. Thanks in advance for any help that you may offer.

Able Archer
  • 579
  • 5
  • 19

1 Answers1

1

Maybe this helps:

df = pd.DataFrame({'index': range(4), 'Patrick': ['Stan', 'Frank', 'Emily', 'Tami']})

names = pd.concat([pd.Series(df.columns[1]),df.iloc[:, 1]]).reset_index(drop=True)

df = pd.DataFrame({'Names': names})

df

  index    Names
      0  Patrick
      1     Stan
      2    Frank
      3    Emily
      4     Tami
Bruno Mello
  • 4,448
  • 1
  • 9
  • 39
  • Ty @Bruno Mello for your response! I will try this out now. Do you believe this code will still work if the length of the dataframes change? – Able Archer Apr 14 '21 at 00:53
  • 1
    I think it will since the new dataframe is set to have a length of `len(df)+1` – Bruno Mello Apr 14 '21 at 00:56
  • This looks perfect. I will take the time to study it and will learn a lot from the experience. Ty sir @Bruno Mello for your time! =) – Able Archer Apr 14 '21 at 01:00
  • it looks like it prints another index so there are 2 indexes now. Any suggestions? I am sure that I can find out how to eliminate the other index but was wondering if there is a small adjustment in the code that will prevent this. Thank you sir! – Able Archer Apr 14 '21 at 01:49
  • 1
    Sure, this happens because I thought that the `index` column on your question was an actual column not the index of the dataframe, I edited the question now, see if it works correctly now @AbleArcher – Bruno Mello Apr 14 '21 at 13:42
  • You're amazing! I tried hard to figure this out on my own and had no luck. Thanks for taking the time to help me. It means a lot! =) – Able Archer Apr 14 '21 at 16:53