英文:
datetime struggle with a pandas dataframe
问题
以下是您提供的代码的翻译部分:
我正在运行以下 **代码**:
```python
filled_df = (ts.set_index(date_col)
.groupby(grouping)
.apply(lambda d: d.reindex(
pd.date_range(
mf_heuristic(d.index, champion_end), pd.to_datetime(
dt.datetime.now()
),
freq='MS')
)
)
.drop(grouping, axis=1)
.reset_index(grouping)
.fillna(0)
使用以下预定义变量:
date_col = 'timepoint'
grouping = ['Level', 'Kontogruppe']
champion_end = fc_date - pd.DateOffset(months=13)
print(champion_end)
2021-03-01 00:00:00
print(ts)
Kontogruppe Level timepoint data_value
0 A ZBFO 2020-03-01 1
1 B ZBFO 2020-07-01 1612.59
2 A ZBFO 2020-08-01 1046.1
print(ts.dtypes)
Kontogruppe object
Level object
timepoint object
data_value float64
dtype: object
def mf_heuristic(date, champion_end):
if min(date) < champion_end:
start_date = min(date)
else:
start_date = min(date)
return start_date
当我运行代码时,我收到以下 错误消息:
TypeError: Cannot compare Timestamp with datetime.date. Use ts == pd.Timestamp(date) or ts.date() == date instead.
针对具有 mf_heuristic 函数的行。
如果我尝试在之前加入以下代码:
ts[date_col] = pd.Timestamp(ts[date_col])
我会收到以下错误消息:
TypeError: function missing required argument 'year' (pos 1)
<details>
<summary>英文:</summary>
I am running the following **code**:
filled_df = (ts.set_index(date_col)
.groupby(grouping)
.apply(lambda d: d.reindex(
pd.date_range(
mf_heuristic(d.index, champion_end), pd.to_datetime(
dt.datetime.now()
),
freq='MS')
)
)
.drop(grouping, axis=1)
.reset_index(grouping)
.fillna(0)
*with the predefinitions:*
date_col = 'timepoint'
grouping = ['Level', 'Kontogruppe']
champion_end = fc_date - pd.DateOffset(months=13)
print(champion_end)
2021-03-01 00:00:00
print(ts)
Kontogruppe Level timepoint data_value
0 A ZBFO 2020-03-01 1
1 B ZBFO 2020-07-01 1612.59
2 A ZBFO 2020-08-01 1046.1
print(ts.dtypes)
Kontogruppe object
Level object
timepoint object
data_value float64
dtype: object
def mf_heuristic(date, champion_end):
if min(date) < champion_end:
start_date = min(date)
else:
start_date = min(date)
return start_date
When I run the code, I get the following **error massage**:
> TypeError: Cannot compare Timestamp with datetime.date. Use ts ==
> pd.Timestamp(date) or ts.date() == date instead.
for the line with the mf_heuristic function.
If I try to put before:
ts[date_col] = pd.Timestamp(ts[date_col])
I get the error massage:
> TypeError: function missing required argument 'year' (pos 1)
</details>
# 答案1
**得分**: 2
尝试使用 `to_datetime`:
```python
ts[date_col] = pd.to_datetime(ts[date_col])
英文:
Try using to_datetime
:
ts[date_col] = pd.to_datetime(ts[date_col])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论