如何将编码日期的 DataFrame 转换为 pandas 中的 datetime 的 DataFrame?
Starting dataFrame:
| year | month | day |
| ---- | ----- | ---
| 2022 | 'F' | 9 |
| 2022 | 'J' | 1 |
| 2022 | 'K' | 5 |
code for month:
'F' = January,
'J' = April,
'K' = May
Desired dataFrame:
| datetime |
| ---------- |
| 2022-01-09 |
| 2022-04-01 |
| 2022-05-05 |
这样做的正确方法是什么?
此函数翻译单个代码;如何将此函数应用于 DataFrame?
def datefromcode(df):
match month:
case 'F': mo = 1
case 'J': mo = 4
case 'K': mo = 5
return datetime.date(year, mo, day)
您可以使用字典来映射月份数字并将其提供给pandas.to_datetime
接受 DataFrame 作为输入的带有年/月/日列名称的输入:
codes = {'F': 1, 'J': 4, 'K': 5}
pd.to_datetime(df.assign(month=df['month'].map(codes)))
输出:
0 2022-01-09
1 2022-04-01
2 2022-05-05
dtype: datetime64[ns]
或使用字符串连接:
months = {'F': 'January', 'J': 'April', 'K': 'May'}
pd.to_datetime(df['year'].astype(str)+df['month'].map(months)+df['day'].astype(str), format='%Y%B%d')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句