Python 克隆数据帧中的行
我有以下数据帧: 我希望dataframe在day列中每小时重复第一列值(Beaver Valley)。因此,dataframe应该包含一个带有日期时间戳的列以及对应于每天的值。虽然在这个数据框中,值是相同的,但其他数据框中的值将不同 任何帮助都将不胜感激Python 克隆数据帧中的行,python,pandas,numpy,Python,Pandas,Numpy,我有以下数据帧: 我希望dataframe在day列中每小时重复第一列值(Beaver Valley)。因此,dataframe应该包含一个带有日期时间戳的列以及对应于每天的值。虽然在这个数据框中,值是相同的,但其他数据框中的值将不同 任何帮助都将不胜感激 将Date移动到带有set\u index asfreq或resample创建小时索引 ffill向前重复现有值 reindex\u axis只是为了以相同的顺序返回列 示例 df = pd.DataFrame({ '
- 将
移动到带有Date
set\u index
或asfreq
创建小时索引resample
向前重复现有值ffill
只是为了以相同的顺序返回列reindex\u axis
示例
df = pd.DataFrame({
'Beaver Valley': [1, 2],
'Day': pd.date_range('2017-05-01', periods=2)
})
df
Beaver Valley Day
0 1 2017-05-01
1 2 2017-05-02
应用建议的解决方案
df.set_index('Day').asfreq('H').ffill().reset_index().reindex_axis(df.columns, 1)
Beaver Valley Day
0 1.0 2017-05-01 00:00:00
1 1.0 2017-05-01 01:00:00
2 1.0 2017-05-01 02:00:00
3 1.0 2017-05-01 03:00:00
4 1.0 2017-05-01 04:00:00
5 1.0 2017-05-01 05:00:00
6 1.0 2017-05-01 06:00:00
7 1.0 2017-05-01 07:00:00
8 1.0 2017-05-01 08:00:00
9 1.0 2017-05-01 09:00:00
10 1.0 2017-05-01 10:00:00
11 1.0 2017-05-01 11:00:00
12 1.0 2017-05-01 12:00:00
13 1.0 2017-05-01 13:00:00
14 1.0 2017-05-01 14:00:00
15 1.0 2017-05-01 15:00:00
16 1.0 2017-05-01 16:00:00
17 1.0 2017-05-01 17:00:00
18 1.0 2017-05-01 18:00:00
19 1.0 2017-05-01 19:00:00
20 1.0 2017-05-01 20:00:00
21 1.0 2017-05-01 21:00:00
22 1.0 2017-05-01 22:00:00
23 1.0 2017-05-01 23:00:00
24 2.0 2017-05-02 00:00:00
如果我理解正确,您希望以每小时一次的频率对数据帧行进行重采样,并向前填充“Beaver Valley”值,以填充重采样创建的每小时时段。下面是一个可运行的示例,我认为它符合您的需要,使用不同的Beaver Valley值来说明正向填充的结果:
import pandas as pd
df = pd.DataFrame({'Beaver Valley': [923.4, 100, 200, 300, 400, 500, 600],
'DAY': pd.date_range(start='2017-05-01', periods=7)})
# By default, df.reset_index() reinserts the index of df as a column into df, which is what we need here.
df2 = df.set_index('DAY')
# To make sure the last day gets resampled into 24 hour-long intervals,
# append a NaN row before resampling (there may be a more readable way of doing this):
df3 = df2.reindex(pd.date_range(start=df2.index[0], periods=df2.shape[0]+1))
df3.index.rename('DAY', inplace=True)
df4 = df3.resample('h').ffill().reset_index()
df4.head()
# Output:
# DAY Beaver Valley
# 0 2017-05-01 00:00:00 923.4
# 1 2017-05-01 01:00:00 923.4
# 2 2017-05-01 02:00:00 923.4
# 3 2017-05-01 03:00:00 923.4
# 4 2017-05-01 04:00:00 923.4
df4.tail()
# Output:
# DAY Beaver Valley
# 164 2017-05-07 20:00:00 600.0
# 165 2017-05-07 21:00:00 600.0
# 166 2017-05-07 22:00:00 600.0
# 167 2017-05-07 23:00:00 600.0
# 168 2017-05-08 00:00:00 NaN
如果需要,现在可以从最终数据框中删除最终占位符行:
df4 = df4[:-1]
非常感谢你!我试着用datetime而不是date的专栏来做这件事,但它似乎不起作用。也就是说,我的day专栏中有2017-05-01 00:00:00,所有行都有NaN的。请告诉我该换什么。非常感谢!我试着用datetime而不是date的专栏来做这件事,但它似乎不起作用。也就是说,我的day专栏中有2017-05-01 00:00:00,所有行都有NaN的。请告诉我该换什么。
df4 = df4[:-1]