【问题标题】:Separating Dates in Python [closed]在 Python 中分隔日期 [关闭]
【发布时间】:2020-03-16 10:40:30
【问题描述】:

我正在尝试使用日期对数据进行预测。问题是我有这样的数据集

    LeaveStartDate  TotalLeaveDays
0   2020-03-14  1.0
1   2020-03-18  2.0
2   2020-03-20  1.0
3   2020-01-13  3.0
4   2020-02-15  1.0

我想扩大总叶数,例如:

  LeaveStartDate   TotalLeaveDays

    0  2020-03-14       1.0

    1   2020-03-18      1.0

    2   2020-03-19      1.0

    3   2020-01-20      1.0

    4   2020-01-13      1.0

    5   2020-01-14      1.0

    6   2020-01-15      1.0

    7   2020-02-15      1.0 

我应该怎么做才能得到这种形式的数据

【问题讨论】:

  • 您确定您的预期输出正确吗?
  • 我更正了我的输出

标签: python pandas datetime python-datetime


【解决方案1】:

TotalLeaveDays 列中使用Index.repeat,然后添加由GroupBy.cumcountto_timedelta 转换为天时间增量的计数器值,最后将1 设置为TotalLeaveDays 列:

df['LeaveStartDate'] = pd.to_datetime(df['LeaveStartDate'])

df = df.loc[df.index.repeat(df['TotalLeaveDays'])]
df['LeaveStartDate'] += pd.to_timedelta(df.groupby(level=0).cumcount(), unit='D')
df['TotalLeaveDays'] = 1
df = df.reset_index(drop=True)
print (df)
  LeaveStartDate  TotalLeaveDays
0     2020-03-14               1
1     2020-03-18               1
2     2020-03-19               1
3     2020-03-19               1
4     2020-03-20               1
5     2020-03-21               1
6     2020-01-13               1
7     2020-02-17               1

【讨论】:

  • 我试过这个但是发生了这个错误 AttributeError: 'DataFrame' object has no attribute 'to_datetime'
  • @MuhammadIrtiza - 你使用pd.to_datetime,而不是df.to_datetime 吗?
  • 是的,我使用了 df.to_datetime。我的坏现在它工作完美。非常感谢你
猜你喜欢
  • 2020-06-10
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多