简体   繁体   中英

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'))

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')
)
df['Date'] = df.loc[df['Frequency']==2, 'Time Period'].replace({
        'Q1': '-01-01',
        'Q2': '-04-01',
        'Q3': '-07-01',
        'Q4': '-10-01'
    })

this code work as per your requirement.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM