0

Combine two columns of text in dataframe in pandas/python

So I am trying to change a line with the solution given at the answer above.

For example,

   Year     quarter period
0  2014    q1     2014q1
1  2015    q2     2015q2

what I'd like to see in my 'period' column is not 2014q1
but

2014   
 q1

q1 at the bottm of 2014

I wish I could put the content of one column below the content of the different column when two contents of different columns are combined.

I have tried

dataframe["period"] = dataframe["Year"].map(str) +'\n' + dataframe["quarter"]

but it doesn't work. The code above gives me

 2014 \n q1

Any advice?

Eiffelbear
  • 399
  • 1
  • 4
  • 23
  • You said you want `'2014 \n q1'` and also said that your code gives `'2014 \n q1'`. I don't understand whats wrong? – rafaelc May 06 '18 at 07:10
  • @RafaelC Thanks for your attention to my question. What I want was q1 at the bottom of 2014. Now you can see what I want exactly in the body of my question. Can you check it out once again? – Eiffelbear May 06 '18 at 07:13
  • 1
    I'm not entirely understanding your purpose. Maybe you should try to ask the next question (what is it you want to achieve next). But as to "it doesn't work", if you'd print the value it would display it as two rows, e.g. `print(dataframe['period'][0])`. It has to do with pandas display. – Anton vBR May 06 '18 at 07:20

1 Answers1

0

Use DataFrame.stack():

df = pd.DataFrame({'Year': [2014,2015], 'period': ['q1','q2']})
df.stack()

It gives you:

0  Year      2014
   period      q1
1  Year      2015
   period      q2

The first (index) column does not explicitly print 0 in the second row and 1 in the last row, but those are implied. It has the same meaning as:

0  Year      2014
0  period      q1
1  Year      2015
1  period      q2
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • While this answers the question, it also appears to ignore the [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Why would you want to combine year and quarter identifiers in a single column? This seems like a misuse of `pandas`. – jpp May 06 '18 at 11:19