Need to separate the quarter and year into separate columns
df.head()
Period
Q1/2012
Q2/2012
Q3/2012
Q4/2012
Q1/2013
Want to have the column displayed as:
Period Year
Q1 2012
Q2 2012
Q3 2012
Q4 2012
Q1 2013
import pandas as pd
import numpy as np
df
Period
0 Q1/2012
1 Q2/2012
2 Q3/2012
3 Q4/2012
4 Q1/2013
df['Year'] = df['Period'].str.extract(r'(\w{4})', expand=False)
df['Period'] = df['Period'].str.extract(r'(.\d{1})',expand=False)
df
Period Year
0 Q1 2012
1 Q2 2012
2 Q3 2012
3 Q4 2012
4 Q1 2013
Use df.assign
with str.split
to do in the singleLine
df = pd.DataFrame({"data":["Q1/2018","Q1/2018","Q1/2018"]})
final_df = df.assign(Period=lambda x :x['data'].str.split("/").str[0],
Year = lambda x :x['data'].str.split("/").str[1])
print(final_df)
data Period Year
0 Q1/2018 Q1 2018
1 Q1/2018 Q1 2018
2 Q1/2018 Q1 2018
Use Series.str.split
:
df[['Period','Year']] = df['Period'].str.split('/', expand=True)
print (df)
Period Year
0 Q1 2012
1 Q2 2012
2 Q3 2012
3 Q4 2012
4 Q1 2013
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.