【发布时间】:2019-01-01 13:33:03
【问题描述】:
python 新手。
我有这个数据:
sample = pd.DataFrame({'CustomerID': ['1', '2', '3', '4', '5', '6'],
'Date': np.random.choice(pd.Series(pd.date_range('2018-01-01',
freq='D', periods=180)), 6),
'Period': np.random.uniform(50, 200, 6),
}, columns=['CustomerID', 'Date', 'Period'])
sample
我想将'Period' 列添加到'Date' 列中,将每个新日期记录在一个单独的数据框中,其中包含CustomerID 和New Date 列。但是,我想记录每个新日期(迭代上一个新日期)直到新日期> 2020。
我做了一个函数:
def proj(ids=None):
end = pd.to_datetime('2020-01-01')
for x in ids:
date = projection.loc[projection['CustomerID'] == x, 'Date']
period = projection.loc[projection['CustomerID'] == x, 'Period'])
time_left = end - date
ratio = float(round(time_left.dt.days / period)) # how many times the period fits in time_left
itera = np.arange(1, ratio, 1)
for i in itera:
deltas = [i * period]
df = pd.Series(deltas).map(float).map(dt.timedelta)
pdates = pd.Series((date + df))
pdates = pdates.map(pd.to_datetime)
print(dates)
我显然不仅没有弄清楚如何为我的输出创建一个新的数据框,而且这个函数也只适用于我的一个 CustomerID,而不能用于其他的。
我真的很想知道接下来我能做什么。
感谢您的帮助。
编辑:作为参考,我希望输出看起来像
output = pd.DataFrame({'CustomerID': ['1', '1', '1', '1', '2', '2', '2'],
'New Date': ['2018-09-28', '2019-01-21', '2019-05-16','2019-09-08',
'2018-09-26', '2019-02-27', '2019-07-31']})
output
【问题讨论】:
-
你能发布想要的输出吗?
-
output = pd.DataFrame({'CustomerID': ['1', '1', '1', '1', '2', '2', '2'], 'New Date': ['2018-09-28', '2019-01-21', '2019-05-16','2019-09-08', '2018-09-26', '2019-02-27', '2019-07-31']})output -
您关心 Period 的小数部分,还是按四舍五入的天数移动就足够了?两者都是可能的,但圆形更干净一些。
-
理想情况下我们会尽可能准确,但实际上这很好。
-
但在您的输出示例中没有日期 > 2020...??
标签: python pandas numpy datetime for-loop