我有数据框。在相同的索引下,我有“ early_date”和“ latest_date”,它们是“ int” dtype。我想在“ early_date”和“ latest_date”行值之间创建其他值。顺便说一句,我想将生成的值堆叠到它们之间的新行中。
这是我做的
df = pd.DataFrame({'index': [1,1,2,2,3,3],
'variable': ['early_date', 'late_date']*3,
'value': [201952,202001,202002,202004,202006,202012]})
# This is what your data looks like unmelted
df_p = df.pivot('index', 'variable', 'value').reset_index()
df_p.columns.name = ''
df_p['new'] = [list(range(x,y+1)) for x, y in zip(df_p.pop('early_date'), df_p.pop('late_date'))]
在“新”列中,索引1中的“ 201952”和“ 202001”之间的填充已变为201952、201953、201954 ... 201999、202001。
但是,由于“新”列实际上代表年份和星期。在索引1的情况下,它不应在201952和202001之间填充任何内容,结果应为[201952,202001]。由于第52周是今年年底。
我该怎么办?
IIUC,您可以在for循环中添加条件:
df_p['new'] = [list(range(x,y+1)) if str(x)[-2:]!='52' else [x,y]
for x, y in zip(df_p.pop('early_date'), df_p.pop('late_date'))]
print(df_p)
index new
0 1 [201952, 202001]
1 2 [202002, 202003, 202004]
2 3 [202006, 202007, 202008, 202009, 202010, 20201...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句