Python 把周期分成几年
我有一个电子表格,其中包含以下内容:Python 把周期分成几年,python,pandas,Python,Pandas,我有一个电子表格,其中包含以下内容: start_date | end_date | rating -----------|----------|-------- 01/01/2010 |01/01/2012| 2 01/12/2012 |01/01/2014| 4 -----------|----------|-------- 我想将这段时间分为几年,例如,鉴于上述示例,我希望得到以下结果: year | rating -----|-------- 2010 | 2 2011 | 2 20
start_date | end_date | rating
-----------|----------|--------
01/01/2010 |01/01/2012| 2
01/12/2012 |01/01/2014| 4
-----------|----------|--------
我想将这段时间分为几年,例如,鉴于上述示例,我希望得到以下结果:
year | rating
-----|--------
2010 | 2
2011 | 2
2012 | 2
2012 | 4
2013 | 4
2014 | 4
-----|--------
是否可以通过pandas方法执行此操作???您可以使用date_范围,在该范围内创建年份,我们使用repeat重新创建您的数据框
您可以使用date_范围,在该范围内创建年份,然后使用repeat重新创建数据帧
理解力
假设日期是相同格式的字符串
pd.DataFrame(
[(y, r) for s, e, r in zip(*map(df.get, df))
for y in range(int(s[-4:]), int(e[-4:]) + 1)],
columns=['year', 'rating']
)
year rating
0 2010 2
1 2011 2
2 2012 2
3 2012 4
4 2013 4
5 2014 4
类似,但使用f字符串和pd.date\u范围
理解力
假设日期是相同格式的字符串
pd.DataFrame(
[(y, r) for s, e, r in zip(*map(df.get, df))
for y in range(int(s[-4:]), int(e[-4:]) + 1)],
columns=['year', 'rating']
)
year rating
0 2010 2
1 2011 2
2 2012 2
3 2012 4
4 2013 4
5 2014 4
类似,但使用f字符串和pd.date\u范围
请提供用于复制示例数据帧和您尝试的内容的代码。请提供用于复制示例数据帧和您尝试的内容的代码。
pd.DataFrame(
[(y, r) for s, e, r in zip(*map(df.get, df))
for y in pd.date_range(s, f"12/31/{e[-4:]}", freq='Y').year],
columns=['year', 'rating']
)