请帮帮我。 我想基于 1D 重新采样。 我有以下格式的数据。 我想在 Pandas 中使用重采样。
我想根据日期和产品重新采样并填充缺失值。
但我一直犯这个错误:我尝试了 5 个选项,错误只在“instance of”之后发生了变化:我看到了 Multiindex,Index。
TypeError:仅对 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 有效,但得到了“RangeIndex”的实例
product value date
A 1.52 2016-01-01
A NULL 2016-09-20
A 1.33 2018-08-02
B 1.30 2016-01-01
B NULL 2017-01-02
B 1.54 2017-03-10
B 2.08 2017-06-28
B 2.33 2018-08-02
我把这些数据放入
df.reset_index().set_index('date','sku')
df= df.groupby('product').resample('1D')['value'].ffill().bfill().ffill()
我也试过:
df = df.set_index(['date','sku'])
df = df.set_index('date','sku')
df = df.reset_index().set_index(['date','sku'])
拜托,你能解释一下我做错了什么吗?谢谢!
今天早上它正在处理这些数据和来自 Jezrael 的命令:
df = df.set_index('date').groupby('product').resample('1D')['value'].ffill()
product value date
0 A 1.52 2016-01-01
1 A NaN 2016-09-20
2 A 1.87 2018-08-02
3 B 2.33 2016-01-01
4 B NaN 2016-09-20
5 B 4.55 2018-08-02
但突然间它不再存在了。 现在我在错误语句中有索引。
最佳答案
如果使用 DataFrameGroupBy.resample
,您需要 DatetimeIndex
, bfill
也被省略了,因为如果一些只有 NaN
的组是可能的,这些数据将被其他组替换:
#if necessary convert to datetimes
#df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date').groupby('product').resample('1D')['value'].ffill()
print (df)
product date
A 2016-01-01 1.52
2016-01-02 1.52
2016-01-03 1.52
2016-01-04 1.52
2016-01-05 1.52
2016-01-06 1.52
2016-01-07 1.52
2016-01-08 1.52
2016-01-09 1.52
2016-01-10 1.52
2016-01-11 1.52
2016-01-12 1.52
更改示例以获得更好的解释:
print (df)
product value date
0 A 1.52 2016-01-01
1 A NaN 2016-01-03
2 B NaN 2017-01-02
3 B NaN 2017-01-03
4 C 1.54 2017-03-10
5 C 2.08 2017-03-12
6 C 2.33 2017-03-14
df1 = df.set_index('date').groupby('product').resample('1D')['value'].ffill()
print (df1)
product date
A 2016-01-01 1.52
2016-01-02 1.52
2016-01-03 NaN < NaN is not changed because in original data
B 2017-01-02 NaN <- only NaN group B
2017-01-03 NaN
C 2017-03-10 1.54
2017-03-11 1.54
2017-03-12 2.08
2017-03-13 2.08
2017-03-14 2.33
Name: value, dtype: float64
df11 = df.set_index('date').groupby('product').resample('1D')['value'].ffill().bfill()
print (df11)
product date
A 2016-01-01 1.52
2016-01-02 1.52
2016-01-03 1.54 <- back filling value from group C
B 2017-01-02 1.54 <- back filling value from group C
2017-01-03 1.54 <- back filling value from group C
C 2017-03-10 1.54
2017-03-11 1.54
2017-03-12 2.08
2017-03-13 2.08
2017-03-14 2.33
Name: value, dtype: float64
关于python - Pandas 重采样 : TypeError: Only valid with DatetimeIndex, TimedeltaIndex 或 PeriodIndex,但得到了 'RangeIndex' 的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51656065/