gpt4 book ai didi

python - 使用 Pandas 从两列获取值范围的优雅方法

转载 作者:行者123 更新时间:2023-12-04 09:36:38 24 4
gpt4 key购买 nike

我有一个如下所示的数据框(运行下面的完整代码)

df1 = pd.DataFrame({'person_id': [11,21,31,41,51],
'date_birth': ['05/29/1967', '01/21/1957', '7/27/1959','01/01/1961','12/31/1961']})
df1 = df1.melt('person_id', value_name='date_birth')
df1['birth_dates'] = pd.to_datetime(df1['date_birth'])
df_ranges = df1.assign(until_prev_year_days=(df1['birth_dates'].dt.dayofyear - 1),
until_next_year_days=((df1['birth_dates'] + pd.offsets.YearEnd(0)) - df1['birth_dates']).dt.days)
f = {'until_prev_year_days': 'min', 'until_next_year_days': 'min'}

min_days = df_ranges.groupby('person_id',as_index=False).agg(f)
min_days.columns = ['person_id','no_days_to_prev_year','no_days_to_next_year']
df_offset = pd.merge(df_ranges[['person_id','birth_dates']], min_days, on='person_id',how='inner')
请参阅下面关于我试图获得范围的内容
df_offset['range_to_shift'] = "[" + (-1 * df_offset['no_days_to_prev_year']).map(str) + "," + df_offset['no_days_to_next_year'].map(str) + "]"
虽然我的方法有效,但我想有什么更好、更优雅的方法来做同样的事情
请注意,对于来自 no_days_to_prev_year 的值, 我们必须加上前缀 minus标志
我希望我的输出如下所示
enter image description here

最佳答案

使用 DataFrame.mul 连同 DataFrame.to_numpy :

cols = ['no_days_to_prev_year', 'no_days_to_next_year']
df_offset['range_to_shift'] = df_offset[cols].mul([-1, 1]).to_numpy().tolist()
结果:
# print(df_offset)

person_id birth_dates no_days_to_prev_year no_days_to_next_year range_to_shift
0 11 1967-05-29 148 216 [-148, 216]
1 21 1957-01-21 20 344 [-20, 344]
2 31 1959-07-27 207 157 [-207, 157]
3 41 1961-01-01 0 364 [0, 364]
4 51 1961-12-31 364 0 [-364, 0]
timeit性能结果:
df_offset.shape
(50000, 5)

%%timeit -n100
cols = ['no_days_to_prev_year', 'no_days_to_next_year']
df_offset['range_to_shift'] = df_offset[cols].mul([-1, 1]).to_numpy().tolist()

15.5 ms ± 464 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

关于python - 使用 Pandas 从两列获取值范围的优雅方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62551096/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com