我希望将panda.DataFrame中的时间列(panda.DataFrame)转换为仅表示年份和月份的字符串。
如果列中的所有值都是有效的,则它将按预期工作。
0 2019-4
1 2017-12
dtype: object但是,由于列中缺少值(pandas.NaT),结果使我感到困惑。
0 -1 days +23:59:59.999979806
1 -1 days +23:59:59.999798288
2 NaT
dtype: timedelta64[ns]或者使用.unique(),它就是array([ -20194, -201712, 'NaT'], dtype='timedelta64[ns]')。
这里发生的事情似乎以某种方式将结果变成了timedelta64。但我不明白为什么会这样。问题是为什么会发生这种情况?
完整的示例代码:
#!/usr/bin/env pyhton3
import pandas as pd
import numpy as np
# series with missing values
series = pd.Series([
np.datetime64('2019-04-08'),
np.datetime64('2017-12-05')])
def year_month_string(cell):
"""Convert a datetime64 into string representation with
year and month only.
"""
if pd.isna(cell):
return pd.NaT
return '{}-{}'.format(cell.year, cell.month)
print(series.apply(year_month_string))
# 0 2019-4
# 1 2017-12
# dtype: object
# Series with a missing value
series_nat = pd.Series([
np.datetime64('2019-04-08'),
np.datetime64('2017-12-05'),
pd.NaT])
result = series_nat.apply(year_month_string)
print(result)
# 0 -1 days +23:59:59.999979806
# 1 -1 days +23:59:59.999798288
# 2 NaT
# dtype: timedelta64[ns]
print(result.unique())
# array([ -20194, -201712, 'NaT'], dtype='timedelta64[ns]')发布于 2022-05-18 09:37:46
不要使用自定义函数,使用strftime和%-m (减号去掉前导零):
series_nat.dt.strftime('%Y-%-m')产出:
0 2019-4
1 2017-12
2 NaN
dtype: object%m将保留前导零:
series_nat.dt.strftime('%Y-%m')产出:
0 2019-04
1 2017-12
2 NaN
dtype: objecthttps://stackoverflow.com/questions/72286632
复制相似问题