我有以下数据框:
id begcost endcost
100 1 3
200 10 12
我要:
id newcost
100 1
100 2
100 3
200 10
200 11
200 12
基本上,我需要为 begcost 和 endcost 列范围内包含的每个值创建一个新行。尝试了多种转置选项,但似乎无法找到我需要的 TIA。
请您参考如下方法:
pd.DataFrame(
[(i, j) for i, b, e in df.itertuples(index=False) for j in range(b, e + 1)],
columns=['id', 'newcost']
)
id newcost
0 100 1
1 100 2
2 100 3
3 200 10
4 200 11
5 200 12
时间
%%timeit
(df.set_index('id').apply(lambda x: pd.Series(np.arange(x.iloc[0],x.iloc[1]+1)), axis=1)
.reset_index()
.melt(id_vars='id')
.drop('variable', axis=1)
.rename(columns={'value':'newcost'}))
100 loops, best of 3: 3.03 ms per loop
%%timeit
pd.DataFrame(
[(i, j) for i, b, e in df.itertuples(index=False) for j in range(b, e + 1)],
columns=['id', 'newcost']
)
1000 loops, best of 3: 1.01 ms per loop
