我的初始数据框是
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
我真正的DataFrame的列(在此示例中为“ b”列)具有许多唯一值。
答案 0 :(得分:2)
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]})
# make datetime
df['a'] = pd.to_datetime(df['a'])
# create a group
g = df.groupby('b')
# list comprehension with reindex and date_range then concat list of frames
df2 = pd.concat([df.set_index('a').reindex(pd.date_range(df['a'].min(),
df['a'].max(),freq='D')) for _,df in g])
# ffill column b
df2['b'] = df2['b'].ffill()
b c
2020-01-01 a 1.0
2020-01-02 a NaN
2020-01-03 a NaN
2020-01-04 a NaN
2020-01-05 a NaN
2020-01-06 a 2.0
2020-01-04 b 3.0
2020-01-05 b NaN
2020-01-06 b NaN
2020-01-07 b 4.0
答案 1 :(得分:1)
使用groupby
和asfreq
的另一种方法:
(df.set_index('a')
.groupby('b').apply(lambda x: x.drop('b',axis=1).asfreq('D'))
.reset_index()
)
输出:
b a c
0 a 2020-01-01 1.0
1 a 2020-01-02 NaN
2 a 2020-01-03 NaN
3 a 2020-01-04 NaN
4 a 2020-01-05 NaN
5 a 2020-01-06 2.0
6 b 2020-01-04 3.0
7 b 2020-01-05 NaN
8 b 2020-01-06 NaN
9 b 2020-01-07 4.0