我对 Python 和 Pandas 非常陌生,希望能得到一些帮助,使用 for 循环为 Date 添加一列。我已经尝试了下面的代码,以及这个代码的一些变体,但总是收到错误。我为“天”添加了一个列,这样我就可以返回一个日期;但后来我删除了该列。
对于 SAP Period = 0 的行,我想返回 1/1/YYYY。对于所有其他行,我想返回该月的最后一天。
for y in df_BW['SAP Period']:
if y == 0:
df_BW['Period'] = pd.to_datetime(df_BW[['Day', 'SAP Period2', 'Year']].astype(str).apply(' '.join, 1), format='%d %m %Y')
else:
df_BW['Period'] = pd.to_datetime(df_BW[['Day', 'SAP Period', 'Year']].astype(str).apply(' '.join, 1), format='%d %m %Y') + MonthEnd()
年份 | SAP 周期 | 日期 |
---|---|---|
2020 | 0 | 1/1/2020 |
2020 | 1 | 1/31/2020 |
2020 | 2 | 2/29/2020 |
2020 | 0 | 1/1/2020 |
2020 | 2 | 2/29/2020 |
2020 | 2 | 2/29/2020 |
2020 | 3 | 3/31/2020 |
2020 | 12 | 12/31/2020 |
2021 | 0 | 1/1/2021 |
2021 | 1 | 1/31/2021 |
2021 | 3 | 3/31/2021 |
2021 | 0 | 1/1/2021 |
2021 | 2 | 2/28/2021 |
2021 | 3 | 3/31/2021 |
答案 0 :(得分:1)
使用 np.where
和 MonthEnd
中的 pandas.teseries.offset.MonthEnd
from pandas.tseries.offsets import MonthEnd
df['date'] = pd.to_datetime(df['Year'].astype(str) +
df['SAP Period'].replace(0,1).astype(str).str.zfill(2) +
'01',format='%Y%m%d')
df['date'] = np.where(df['SAP Period'].ne(0), df['date'] + MonthEnd(1), df['date'])
Year SAP Period Date date
0 2020 0 1/1/2020 2020-01-01
1 2020 1 1/31/2020 2020-01-31
2 2020 2 2/29/2020 2020-02-29
3 2020 0 1/1/2020 2020-01-01
4 2020 2 2/29/2020 2020-02-29
5 2020 2 2/29/2020 2020-02-29
6 2020 3 3/31/2020 2020-03-31
7 2020 12 12/31/2020 2020-12-31
8 2021 0 1/1/2021 2021-01-01
9 2021 1 1/31/2021 2021-01-31
10 2021 3 3/31/2021 2021-03-31
11 2021 0 1/1/2021 2021-01-01
12 2021 2 2/28/2021 2021-02-28
13 2021 3 3/31/2021 2021-03-31
答案 1 :(得分:0)
试试这个:
from pandas.tseries.offsets import MonthEnd
df['Date'] = df.apply(lambda x: pd.to_datetime('1/1/' + str(x['Year'])) + MonthEnd(x['SAP Period']),axis=1)