我有身份证,购买日期,购买价格和期限的数据,
df
id purchased_date price duration
1 2020-01-01 16.50 2
2 2020-01-01 24.00 4我想做的是,在任何情况下,持续时间都大于1天,我希望额外的天数被分割成重复的行,价格除以每一天的天数,每一天增加1天。实际上给了我这个,
df_new
id purchased_date price duration
1 2020-01-01 8.25 1
1 2020-01-02 8.25 1
2 2020-01-01 6.00 1
2 2020-01-02 6.00 1
2 2020-01-03 6.00 1
2 2020-01-04 6.00 1到目前为止,已经成功地根据持续时间复制了行。
df['price'] = df['price']/df['duration']
df = df.loc[df.index.repeat(df.duration)]然后我试着用,
df.groupby(['id', 'purchased_date']).purchased_date.apply(lambda n: n + pd.to_timedelta(1, unit='d'))然而,这只是被困在一个无休止的循环,我有点卡住了。
我的计划是将所有这些都放在一个函数中,但就目前而言,我只想让这个过程正常工作。
谢谢你的帮助。
发布于 2022-05-11 08:40:51
使用GroupBy.cumcount作为计数器,这样就可以将时间增量传递到to_timedeltato_timedelta,并添加到列purchased_date
df['price'] = df['price']/df['duration']
df = df.loc[df.index.repeat(df.duration)].assign(duration=1)
df['purchased_date'] += pd.to_timedelta(df.groupby(level=0).cumcount(), unit='d')
df = df.reset_index(drop=True)
print (df)
id purchased_date price duration
0 1 2020-01-01 8.25 1
1 1 2020-01-02 8.25 1
2 2 2020-01-01 6.00 1
3 2 2020-01-02 6.00 1
4 2 2020-01-03 6.00 1
5 2 2020-01-04 6.00 1发布于 2022-05-11 08:46:45
一种基于pandas.date_range和explode的方法
(df.assign(price=df['price'].div(df['duration']),
purchased_date=df.apply(lambda x: pd.date_range(x['purchased_date'],
periods=x['duration']),
axis=1),
duration=1
)
.explode('purchased_date', ignore_index=True)
)产出:
id purchased_date price duration
0 1 2020-01-01 8.25 1
1 1 2020-01-02 8.25 1
2 2 2020-01-01 6.00 1
3 2 2020-01-02 6.00 1
4 2 2020-01-03 6.00 1
5 2 2020-01-04 6.00 1发布于 2022-05-11 09:27:45
下面是一种很容易理解的方法:
date-time
>G 213
代码:
df['price'] = df['price']/df['duration']
df['end_date'] = df.purchased_date + pd.to_timedelta(df.duration.sub(1), unit='d')
df['purchased_date'] = df.apply(lambda x: pd.date_range(start=x['purchased_date'], end=x['end_date']), axis=1)
df = df.explode('purchased_date').reset_index(drop=True)
df = df.assign(duration=1)
del df['end_date']
print (df)
id purchased_date price duration
0 1 2020-01-01 8.25 1
1 1 2020-01-02 8.25 1
2 2 2020-01-01 6.00 1
3 2 2020-01-02 6.00 1
4 2 2020-01-03 6.00 1
5 2 2020-01-04 6.00 1https://stackoverflow.com/questions/72197929
复制相似问题