Combine two columns of text in pandas dataframe

后端 未结 18 1153
-上瘾入骨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:48

    This solution uses an intermediate step compressing two columns of the DataFrame to a single column containing a list of the values. This works not only for strings but for all kind of column-dtypes

    import pandas as pd
    df = pd.DataFrame({'Year': ['2014', '2015'], 'quarter': ['q1', 'q2']})
    df['list']=df[['Year','quarter']].values.tolist()
    df['period']=df['list'].apply(''.join)
    print(df)
    

    Result:

       Year quarter        list  period
    0  2014      q1  [2014, q1]  2014q1
    1  2015      q2  [2015, q2]  2015q2
    

提交回复
热议问题