linus linus - 4 days ago 4
Python Question

Replace python dataframe values and store in another column

I want to replace ['Time Period'] value if it contains Q1,Q2,Q3,Q4 & update it in another column ['Date'] as per condition.
But, after execution of below script, last script result will update in ['Date'] column.

dt:

Time Period Frequency Date
2005Q1 2
2005Q2 2
2002Q3 2
2005Q4 2
2005Q1 2
2003Q2 2
2004Q3 2
2001Q4 2


Please help on this.

dt['Date'] = dt[dt['Frequency'] == '2']['Time Period'].apply(lambda x: x.replace('Q1','-01-01'))
dt['Date'] = dt[dt['Frequency'] == '2']['Time Period'].apply(lambda x: x.replace('Q2','-04-01'))
dt['Date'] = dt[dt['Frequency'] == '2']['Time Period'].apply(lambda x: x.replace('Q3','-07-01'))
dt['Date'] = dt[dt['Frequency'] == '2']['Time Period'].apply(lambda x: x.replace('Q4','-10-01'))

Answer

The following would work:

dt['Date'] = dt[dt['Frequency'] == '2']['Time Period'].apply(
    lambda x: x.replace('Q1','-01-01').replace('Q2','-04-01').replace('Q3','-07-01').replace('Q4','-10-01')
)