Combine two columns of text in pandas dataframe

后端 未结 18 1135
-上瘾入骨i
-上瘾入骨i 2020-11-22 01:32

I have a 20 x 4000 dataframe in Python using pandas. Two of these columns are named Year and quarter. I\'d like to create a variable called p

18条回答
  •  礼貌的吻别
    2020-11-22 01:58

    Let us suppose your dataframe is df with columns Year and Quarter.

    import pandas as pd
    df = pd.DataFrame({'Quarter':'q1 q2 q3 q4'.split(), 'Year':'2000'})
    

    Suppose we want to see the dataframe;

    df
    >>>  Quarter    Year
       0    q1      2000
       1    q2      2000
       2    q3      2000
       3    q4      2000
    

    Finally, concatenate the Year and the Quarter as follows.

    df['Period'] = df['Year'] + ' ' + df['Quarter']
    

    You can now print df to see the resulting dataframe.

    df
    >>>  Quarter    Year    Period
        0   q1      2000    2000 q1
        1   q2      2000    2000 q2
        2   q3      2000    2000 q3
        3   q4      2000    2000 q4
    

    If you do not want the space between the year and quarter, simply remove it by doing;

    df['Period'] = df['Year'] + df['Quarter']
    

提交回复
热议问题