Combine two columns of text in pandas dataframe

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

    if both columns are strings, you can concatenate them directly:

    df["period"] = df["Year"] + df["quarter"]
    

    If one (or both) of the columns are not string typed, you should convert it (them) first,

    df["period"] = df["Year"].astype(str) + df["quarter"]
    

    Beware of NaNs when doing this!


    If you need to join multiple string columns, you can use agg:

    df['period'] = df[['Year', 'quarter', ...]].agg('-'.join, axis=1)
    

    Where "-" is the separator.

提交回复
热议问题