Python 在dataframe中添加缺少的数据和日期
我有以下数据帧Python 在dataframe中添加缺少的数据和日期,python,pandas,dataframe,Python,Pandas,Dataframe,我有以下数据帧 A B C D date AU AT 0.9 0.7 3/31/1960 AU AT 0.3 0.6 6/30/1960 AT AU 0.7 0.5 4/30/1960 AT AU 0.65 0.4 6/30/1960 例如,假设我的最小开始日期是1960年3月31日,最大开始日期是1960年6月30日 我想根据A、B和日期分组的数据,向前填写C列和D列。 所以我最后的数据帧
A B C D date
AU AT 0.9 0.7 3/31/1960
AU AT 0.3 0.6 6/30/1960
AT AU 0.7 0.5 4/30/1960
AT AU 0.65 0.4 6/30/1960
例如,假设我的最小开始日期是1960年3月31日,最大开始日期是1960年6月30日
我想根据A、B和日期分组的数据,向前填写C列和D列。
所以我最后的数据帧是
A B C D date
AU AT 0.9 0.7 3/31/1960
AU AT 0.9 0.7 4/30/1960
AU AT 0.9 0.7 5/31/1960
AU AT 0.3 0.6 6/30/1960
AT AU 0.7 0.5 4/30/1960
AT AU 0.7 0.5 5/31/1960
AT AU 0.65 0.4 6/30/1960
谢谢你的帮助
非常感谢您可以在
groupby
df.date=pd.to_datetime(df.date)
df
Out[85]:
A B C D date
0 AU AT 0.90 0.7 1960-03-31
1 AU AT 0.30 0.6 1960-06-30
2 AT AU 0.70 0.5 1960-04-30
3 AT AU 0.65 0.4 1960-06-30
df.groupby('A').apply(lambda x : x.set_index(['date']).reindex(pd.date_range(x['date'].min(),x['date'].max(),freq='m')).ffill())
Out[91]:
A B C D
A
AT 1960-04-30 AT AU 0.70 0.5
1960-05-31 AT AU 0.70 0.5
1960-06-30 AT AU 0.65 0.4
AU 1960-03-31 AU AT 0.90 0.7
1960-04-30 AU AT 0.90 0.7
1960-05-31 AU AT 0.90 0.7
1960-06-30 AU AT 0.30 0.6
您可以在
groupby
df.date=pd.to_datetime(df.date)
df
Out[85]:
A B C D date
0 AU AT 0.90 0.7 1960-03-31
1 AU AT 0.30 0.6 1960-06-30
2 AT AU 0.70 0.5 1960-04-30
3 AT AU 0.65 0.4 1960-06-30
df.groupby('A').apply(lambda x : x.set_index(['date']).reindex(pd.date_range(x['date'].min(),x['date'].max(),freq='m')).ffill())
Out[91]:
A B C D
A
AT 1960-04-30 AT AU 0.70 0.5
1960-05-31 AT AU 0.70 0.5
1960-06-30 AT AU 0.65 0.4
AU 1960-03-31 AU AT 0.90 0.7
1960-04-30 AU AT 0.90 0.7
1960-05-31 AU AT 0.90 0.7
1960-06-30 AU AT 0.30 0.6
@qfd yw:-)快乐coding@qfdyw:-)快乐编码