我的初始数据帧是
df = pd.DataFrame({"a":["2020-01-01", "2020-01-06", "2020-01-04", "2020-01-07"],
"b":["a", "a", "b", "b"],
"c":[1, 2, 3,4]})
print(df)
a b c
0 2020-01-01 a 1
1 2020-01-06 a 2
2 2020-01-04 b 3
3 2020-01-07 b 4
我希望我的数据集是这样的
a b c
0 2020-01-01 a 1
1 2020-01-02 a NaN
2 2020-01-03 a NaN
3 2020-01-04 a NaN
4 2020-01-05 a NaN
5 2020-01-06 a 2
6 2020-01-04 b 3
7 2020-01-05 b NaN
8 2020-01-06 b NaN
3 2020-01-07 b 4
我试过了
d.set_index([d.a, d.b], inplace=True)
d.asfreq("D")
d.set_index([d.a, d.b], inplace=True)
d.resample("D")
但是我遇到了
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'MultiIndex'
enter code here
我的真实数据帧的列(本例中的“b”列)有许多唯一的值
使用
groupby
和asfreq
的另一种方法:输出:
我们可以使用来自pyjanitor的complete函数,它提供了一个方便的抽象来生成缺少的行:
by
选项主要是为了方便;为了获得更好的性能,需要做更多的工作:对于大型数据帧,性能将显著/更好。提供了一个类似的测试示例here
相关问题 更多 >
编程相关推荐