[英]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. 我想替换['Time Period']值,如果它包含Q1,Q2,Q3,Q4并根据条件在另一列['Date']中进行更新。 But, after execution of below script, last script result will update in ['Date'] column.
但是,执行以下脚本后,最后一个脚本结果将在['Date']列中更新。
dt: 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. 此代码根据您的要求工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.