Combine two columns of text in pandas dataframe

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

    Here is my summary of the above solutions to concatenate / combine two columns with int and str value into a new column, using a separator between the values of columns. Three solutions work for this purpose.

    # be cautious about the separator, some symbols may cause "SyntaxError: EOL while scanning string literal".
    # e.g. ";;" as separator would raise the SyntaxError
    
    separator = "&&" 
    
    # pd.Series.str.cat() method does not work to concatenate / combine two columns with int value and str value. This would raise "AttributeError: Can only use .cat accessor with a 'category' dtype"
    
    df["period"] = df["Year"].map(str) + separator + df["quarter"]
    df["period"] = df[['Year','quarter']].apply(lambda x : '{} && {}'.format(x[0],x[1]), axis=1)
    df["period"] = df.apply(lambda x: f'{x["Year"]} && {x["quarter"]}', axis=1)
    

提交回复
热议问题