简体   繁体   English

替换python数据框值并存储在另一列中

[英]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.

相关问题 Python 数据框 = 用来自另一个数据框的值替换列字符串中的值 - Python dataframe = Replace values in column string with values from another dataframe 根据条件从另一个 dataframe 值替换列的值 - Python - Replace values of a column from another dataframe values based on a condition - Python 基于另一个数据框 python pandas 替换列值 - 更好的方法? - Replace column values based on another dataframe python pandas - better way? Pandas 将列的值替换为与另一个 Dataframe 的比较 - Pandas replace values of a column with comparison to another Dataframe 用另一列替换数据框值的一列 - Replace one column of a dataframe's values with another Python pandas 用模式(同一列 -A)相对于 Pandas 数据帧中的另一列替换一列(A)的 NaN 值 - Python pandas replace NaN values of one column(A) by mode (of same column -A) with respect to another column in pandas dataframe 用另一个数据帧的值替换一个数据帧中的列值 - replace column values in one dataframe by values of another dataframe 根据另一列的值替换Pandas数据框的Column的值 - Replace values of a Pandas dataframe's Column based on values of another column 替换列 dataframe python 中的数值 - replace numeric values in column dataframe python 为什么我无法根据另一列中的值替换 dataframe 的一列中的这些 NA 值? [Python] - Why am I unable to replace these NA values in one column of my dataframe based on the values in another? [Python]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM