Combine two columns of text in pandas dataframe

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

    Use of a lamba function this time with string.format().

    import pandas as pd
    df = pd.DataFrame({'Year': ['2014', '2015'], 'Quarter': ['q1', 'q2']})
    print df
    df['YearQuarter'] = df[['Year','Quarter']].apply(lambda x : '{}{}'.format(x[0],x[1]), axis=1)
    print df
    
      Quarter  Year
    0      q1  2014
    1      q2  2015
      Quarter  Year YearQuarter
    0      q1  2014      2014q1
    1      q2  2015      2015q2
    

    This allows you to work with non-strings and reformat values as needed.

    import pandas as pd
    df = pd.DataFrame({'Year': ['2014', '2015'], 'Quarter': [1, 2]})
    print df.dtypes
    print df
    
    df['YearQuarter'] = df[['Year','Quarter']].apply(lambda x : '{}q{}'.format(x[0],x[1]), axis=1)
    print df
    
    Quarter     int64
    Year       object
    dtype: object
       Quarter  Year
    0        1  2014
    1        2  2015
       Quarter  Year YearQuarter
    0        1  2014      2014q1
    1        2  2015      2015q2
    

提交回复
热议问题