在 Python 中创建从原始列派生的两个新列 [英] Create two new columns derived from original columns in Python
本文介绍了在 Python 中创建从原始列派生的两个新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框 df,它包含两列,其中包含四分之一值.我想再创建两列,它们是等效的长日期".
I have a dataframe, df, that contains two columns that contain quarter values. I would like to create two more columns that are the equivalent "long dates".
数据
ID Quarter Delivery
A Q1 2022 Q3 2022
A Q1 2022 Q3 2022
B Q1 2022 Q3 2022
B Q1 2022 Q3 2022
需要
ID Quarter Delivery QuarterFull DeliveryFull
A Q1 2022 Q3 2022 1/1/2022 07/1/2022
A Q1 2022 Q3 2022 1/1/2022 07/1/2022
B Q4 2022 Q2 2023 10/1/2022 04/1/2023
B Q4 2022 Q2 2023 10/1/2022 04/1/2023
Q1 is 01
Q2 is 04
Q3 is 07
Q4 is 10
做
我的方法/逻辑是创建保存或映射到特定日期的变量或字典(键/值对)
My approach/logic is to create variables or a dictionary that holds or map to specific dates (key/value pairs)
dict = {
"Q1": "01",
"Q2": "04",
"Q3": "07"
"Q4": "10"
}
不确定如何将其实现为列.我仍在对此进行故障排除.任何建议表示赞赏
Not exactly sure how to implement this as columns. I am still troubleshooting this. Any suggestion is appreciated
推荐答案
代码
import pandas as pd
df = pd.DataFrame({'ID': ['A', 'B'], 'Quarter':['Q1 2020', 'Q2 2021']})
def convDate(date):
q, year = date.split()
q = int(q[1])
return f'{q*3-2:02d}/1/{year}'
df['QuarterFull'] = df['Quarter'].map(convDate)
df.head()
输出
ID Quarter QuarterFull
0 A Q1 2020 01/1/2020
1 B Q2 2021 04/1/2021
这篇关于在 Python 中创建从原始列派生的两个新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文