所以我有一个像这样的DataFrame:
N start
1 1 08/01/2014 9:30:02
2 1 08/01/2014 10:30:02
3 2 08/01/2014 12:30:02
4 3 08/01/2014 4:30:02
我需要复制每一行N次,每次增加一小时,如下所示:
N start
1 1 08/01/2014 9:30:02
2 1 08/01/2014 10:30:02
3 2 08/01/2014 12:30:02
3 2 08/01/2014 13:30:02
4 3 08/01/2014 4:30:02
4 3 08/01/2014 5:30:02
4 3 08/01/2014 6:30:02
我怎么能在熊猫中做到这一点?
答案 0 :(得分:6)
您可以使用reindex扩展DataFrame,使用TimedeltaIndex来添加小时数:
import pandas as pd
df = pd.DataFrame({'N': [1, 1, 2, 3],
'start': ['08/01/2014 9:30:02',
'08/01/2014 10:30:02',
'08/01/2014 12:30:02',
'08/01/2014 4:30:02']})
df['start'] = pd.to_datetime(df['start'])
df = df.reindex(np.repeat(df.index.values, df['N']), method='ffill')
df['start'] += pd.TimedeltaIndex(df.groupby(level=0).cumcount(), unit='h')
产生
N start
0 1 2014-08-01 09:30:02
1 1 2014-08-01 10:30:02
2 2 2014-08-01 12:30:02
2 2 2014-08-01 13:30:02
3 3 2014-08-01 04:30:02
3 3 2014-08-01 05:30:02
3 3 2014-08-01 06:30:02
答案 1 :(得分:0)
这可能不是最有效的方式,但会得到结果:
import pandas as pd
l = []
for index,item in df.iterrows():
l.append([item[0],pd.to_datetime(item[1])])
i=1
# it was not clear if you want to repeat based on N or the index... if index then replace item[0] with index
while i<item[0]:
l.append([item[0],pd.to_datetime(item[1])+pd.Timedelta('1 hours')])
i=i+1
dfResult = pd.DataFrame(l,columns=['N','Start'])