How to combine two columns of text in pandas dataframe

0 votes
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 period that makes Year = 2000 and quarter= q2 into 2000q2.

Can anyone help with that?
Jan 5, 2021 in Python by Rajiv
• 8,870 points
1,954 views

1 answer to this question.

0 votes

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.

answered Jan 5, 2021 by Gitika
• 65,770 points

Related Questions In Python

+1 vote
1 answer

How to change the order of DataFrame columns in pandas?

Hi@akhtar, You can rearrange a DataFrame object by ...READ MORE

answered Oct 20, 2020 in Python by MD
• 95,460 points
860 views
0 votes
1 answer

How to find the sum of rows in Pandas dataframe?

You can use a combination groupby function with the sum() method. ...READ MORE

answered May 9, 2019 in Python by Jisha
4,608 views
0 votes
1 answer

How to convert multiple columns to string in pandas dataframe?

Hi, To convert multiple columns to string, include a list of ...READ MORE

answered Jul 19, 2019 in Python by Taj
• 1,080 points
27,864 views
0 votes
1 answer

How to add multiple columns to pandas dataframe in one assignment?

Hello @kartik, You could use assign with a dict of ...READ MORE

answered Jun 15, 2020 in Python by Niroj
• 82,840 points
15,932 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How to set value for particular cell in pandas DataFrame using index?

Why df.xs('C')['x']=10 does not work: df.xs('C') by default, returns a new ...READ MORE

answered Jan 5, 2021 in Python by Gitika
• 65,770 points
3,484 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP