我有一个数据帧,有超过41500条记录和3个字段:ID
、start_date
和end_date
。你知道吗
我想用它创建一个单独的数据帧,其中只有两个字段:ID
和active_years
,这两个字段将包含在起始年和结束年范围(包括范围中的结束年)之间存在的所有可能年份的每个标识符的记录。你知道吗
这是我现在正在做的,但是对于41500行,完成它需要2个多小时。你知道吗
df = pd.DataFrame(columns=['id', 'active_years'])
ix = 0
for _, row in raw_dataset.iterrows():
st_yr = int(row['start_date'].split('-')[0]) # because dates are in the format yyyy-mm-dd
end_yr = int(row['end_date'].split('-')[0])
for year in range(st_yr, end_yr+1):
df.loc[ix, 'id'] = row['ID']
df.loc[ix, 'active_years'] = year
ix = ix + 1
那么有没有更快的方法来实现这一点呢?你知道吗
[编辑]一些尝试和解决的示例,
raw_dataset = pd.DataFrame({'ID':['a121','b142','cd3'],'start_date':['2019-10-09','2017-02-06','2012-12-05'],'end_date':['2020-01-30','2019-08-23','2016-06-18']})
print(raw_dataset)
ID start_date end_date
0 a121 2019-10-09 2020-01-30
1 b142 2017-02-06 2019-08-23
2 cd3 2012-12-05 2016-06-18
# the desired dataframe should look like this
print(desired_df)
id active_years
0 a121 2019
1 a121 2020
2 b142 2017
3 b142 2018
4 b142 2019
5 cd3 2012
6 cd3 2013
7 cd3 2014
8 cd3 2015
9 cd3 2016
动态增长的python列表比动态增长的numpy数组快得多(numpy数组是pandas数据帧的底层数据结构)。请参阅here以获取简要说明。记住这一点:
相关问题 更多 >
编程相关推荐