Combine two columns of text in pandas dataframe

后端 未结 18 1316
-上瘾入骨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 02:03

    df = pd.DataFrame({'Year': ['2014', '2015'], 'quarter': ['q1', 'q2']})
    df['period'] = df[['Year', 'quarter']].apply(lambda x: ''.join(x), axis=1)
    

    Yields this dataframe

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

    This method generalizes to an arbitrary number of string columns by replacing df[['Year', 'quarter']] with any column slice of your dataframe, e.g. df.iloc[:,0:2].apply(lambda x: ''.join(x), axis=1).

    You can check more information about apply() method here

提交回复
热议问题